88
Object Innovations Course 4111 Student Guide Revision 4.0 .NET Framework Using C#

NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

  • Upload
    others

  • View
    5

  • Download
    0

Embed Size (px)

Citation preview

Page 1: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

Object Innovations Course 4111

Student Guide Revision 4.0

.NET Framework Using C#

Page 2: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

Rev. 4.0 Copyright ©2010 Object Innovations Enterprises, LLC ii All Rights Reserved

.NET Framework Essentials Using C# Rev. 4.0 Student Guide Information in this document is subject to change without notice. Companies, names and data used in examples herein are fictitious unless otherwise noted. No part of this document may be reproduced or transmitted in any form or by any means, electronic or mechanical, for any purpose, without the express written permission of Object Innovations. Product and company names mentioned herein are the trademarks or registered trademarks of their respective owners.

® is a registered trademark of Object Innovations. Author: Robert J. Oberg Special Thanks: Michael Stiefel, Peter Thorsteinson, Dana Wyatt, Paul Nahay, Ed Strassberger, Robert Seitz, Sharman Staples Copyright ©2010 Object Innovations Enterprises, LLC All rights reserved. Object Innovations 877-558-7246 www.objectinnovations.com Published in the United States of America.

Page 3: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

Rev. 4.0 Copyright ©2010 Object Innovations Enterprises, LLC iii All Rights Reserved

Table of Contents (Overview) Chapter 1 .NET Fundamentals Chapter 2 Class Libraries Chapter 3 Assemblies, Deployment and Configuration Chapter 4 Metadata and Reflection Chapter 5 I/O and Serialization Chapter 6 .NET Programming Model Chapter 7 .NET Security Chapter 8 Interoperating with COM and Win32 Chapter 9 ADO.NET and LINQ Appendix A Learning Resources

Page 4: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

Rev. 4.0 Copyright ©2010 Object Innovations Enterprises, LLC iv All Rights Reserved

Directory Structure

• The course software installs to the root directory C:\OIC\NetCs.

− Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on.

− The Labs directory contains one subdirectory for each lab, named after the lab number. Starter code is frequently supplied, and answers are provided in the chapter directories.

− The Demos directory is provided for hand-on work during lectures.

• Data files install to the directory C:\OIC\Data.

• The directory C:\OIC\Deploy is provided to practice deployment.

Page 5: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

Rev. 4.0 Copyright ©2010 Object Innovations Enterprises, LLC v All Rights Reserved

Table of Contents (Detailed) Chapter 1 .NET Fundamentals...................................................................................... 1

What Is Microsoft .NET?.................................................................................................... 3 Open Standards and Interoperability .................................................................................. 4 Windows Development Problems....................................................................................... 5 Common Language Runtime .............................................................................................. 6 Serialization Example ......................................................................................................... 7 Attribute-Based Programming.......................................................................................... 10 Metadata............................................................................................................................ 11 Types................................................................................................................................. 12 NET Framework Class Library......................................................................................... 13 Interface-Based Programming .......................................................................................... 14 Everything is an Object..................................................................................................... 15 Common Type System...................................................................................................... 16 ILDASM ........................................................................................................................... 17 .NET Framework SDK Tools ........................................................................................... 19 Language Interoperability................................................................................................. 20 Managed Code .................................................................................................................. 21 Assemblies ........................................................................................................................ 22 Assembly Deployment...................................................................................................... 23 JIT Compilation ................................................................................................................ 24 ASP.NET and Web Services............................................................................................. 25 The Role of XML.............................................................................................................. 26 Performance ...................................................................................................................... 27 Summary ........................................................................................................................... 28

Chapter 2 Class Libraries ............................................................................................ 29 Objects and Components .................................................................................................. 31 Limitation of COM Components ...................................................................................... 32 Components in .NET ........................................................................................................ 33 Class Libraries at the Command Line............................................................................... 34 Component Example: Customer Management System .................................................... 35 Monolithic versus Component.......................................................................................... 37 Demo: Creating a Class Library ....................................................................................... 38 Demo: A Console Client Program .................................................................................... 40 Class Libraries Using Visual Studio................................................................................. 41 Demo: Creating a Class Library ....................................................................................... 42 References in Visual Studio.............................................................................................. 44 References at Compile Time and Run Time..................................................................... 46 Project Dependencies........................................................................................................ 47 Specifying Version Numbers............................................................................................ 48 Lab 2 ................................................................................................................................. 49 Summary ........................................................................................................................... 50

Page 6: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

Rev. 4.0 Copyright ©2010 Object Innovations Enterprises, LLC vi All Rights Reserved

Chapter 3 Assemblies, Deployment and Configuration ............................................ 55 Assemblies ........................................................................................................................ 57 Customer Management System ........................................................................................ 58 ILDASM ........................................................................................................................... 59 Assembly Manifest ........................................................................................................... 60 Assembly Dependency Metadata...................................................................................... 61 Assembly Metadata........................................................................................................... 62 Versioning an Assembly ................................................................................................... 63 AssemblyVersion Attribute .............................................................................................. 64 Strong Names.................................................................................................................... 65 Digital Signatures ............................................................................................................. 66 Verification with Digital Signatures ................................................................................. 67 Hash Codes ....................................................................................................................... 68 Digitally Signing an Assembly ......................................................................................... 69 Digital Signing Flowchart................................................................................................. 70 Signing the Customer Assembly....................................................................................... 71 Signed Assembly Metadata .............................................................................................. 72 Private Assembly Deployment ......................................................................................... 73 Assembly Cache................................................................................................................ 74 Deploying a Shared Assembly.......................................................................................... 75 Signed Assembly Demo.................................................................................................... 76 Versioning Shared Components ....................................................................................... 78 How the CLR Locates Assemblies ................................................................................... 79 Resolving an Assembly Reference ................................................................................... 80 Version Policy in a Configuration File ............................................................................. 81 Finding the Assembly ....................................................................................................... 82 Lab 3A .............................................................................................................................. 83 Application Settings.......................................................................................................... 84 Application Settings Using Visual Studio ........................................................................ 85 Application Settings Demo............................................................................................... 86 Application Configuration File ......................................................................................... 91 User Configuration File .................................................................................................... 92 Lab 3B............................................................................................................................... 93 Summary ........................................................................................................................... 94

Chapter 4 Metadata and Reflection .......................................................................... 101 Metadata.......................................................................................................................... 103 Reflection........................................................................................................................ 104 Sample Reflection Program ............................................................................................ 105 System.Reflection.Assembly .......................................................................................... 108 System.Type.................................................................................................................... 109 System.Reflection.MethodInfo ....................................................................................... 111 Dynamic Invocation........................................................................................................ 112 Late Binding ................................................................................................................... 113 LateBinding Example ..................................................................................................... 114 Lab 4 ............................................................................................................................... 115

Page 7: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

Rev. 4.0 Copyright ©2010 Object Innovations Enterprises, LLC vii All Rights Reserved

Summary ......................................................................................................................... 116

Chapter 5 I/O and Serialization ................................................................................ 121 Input and Output in .NET ............................................................................................... 123 Directories....................................................................................................................... 124 Directory Example Program ........................................................................................... 125 Files and Streams ............................................................................................................ 128 “Read” Command ........................................................................................................... 130 Code for “Write” Command ........................................................................................... 131 Serialization .................................................................................................................... 132 Attributes ........................................................................................................................ 133 Serialization Example ..................................................................................................... 135 Lab 5 ............................................................................................................................... 138 Summary ......................................................................................................................... 139

Chapter 6 .NET Programming Model ...................................................................... 141 Garbage Collection ......................................................................................................... 143 Finalize Method .............................................................................................................. 144 C# Destructor Notation................................................................................................... 145 Dispose............................................................................................................................ 146 Finalize/Dispose Example .............................................................................................. 147 Finalize/Dispose Test Program....................................................................................... 149 Garbage Collection Performance.................................................................................... 151 Generations ..................................................................................................................... 152 Processes ......................................................................................................................... 153 Threads............................................................................................................................ 154 .NET Threading Model................................................................................................... 155 Console Log Example..................................................................................................... 156 Race Conditions .............................................................................................................. 159 Race Condition Example ................................................................................................ 160 Thread Synchronization.................................................................................................. 164 Monitor ........................................................................................................................... 165 Monitor Example ............................................................................................................ 166 Synchronization of Collections....................................................................................... 167 Asynchronous Calls ........................................................................................................ 168 Asynchronous Delegates................................................................................................. 169 Using a CallBack Method............................................................................................... 170 BackgroundWorker......................................................................................................... 173 Lab 6A ............................................................................................................................ 174 Application Isolation....................................................................................................... 175 Application Domain........................................................................................................ 176 Application Domains and Assemblies ............................................................................ 177 AppDomain..................................................................................................................... 178 CreateDomain ................................................................................................................. 179 App Domain Events........................................................................................................ 180 Lab 6B............................................................................................................................. 181

Page 8: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

Rev. 4.0 Copyright ©2010 Object Innovations Enterprises, LLC viii All Rights Reserved

Distributed Programming in .NET.................................................................................. 182 Windows Communication Foundation ........................................................................... 183 .NET Remoting Architecture .......................................................................................... 184 Remote Objects and Mobile Objects .............................................................................. 186 Object Activation and Lifetime ...................................................................................... 187 Singleton and SingleCall ................................................................................................ 188 .NET Remoting Example................................................................................................ 189 .NET Remoting Example: Defs ..................................................................................... 190 .NET Remoting Example: Server .................................................................................. 191 .NET Remoting Example: Client ................................................................................... 193 Lab 6C............................................................................................................................. 195 Summary ......................................................................................................................... 196

Chapter 7 .NET Security............................................................................................ 203 Fundamental Problem of Security .................................................................................. 205 Authentication................................................................................................................. 206 Authorization .................................................................................................................. 207 The Internet and .NET Security ...................................................................................... 208 Code Access Security ..................................................................................................... 209 Role-Based Security ....................................................................................................... 210 .NET Security Concepts ................................................................................................. 211 Permissions ..................................................................................................................... 212 IPermission Interface ...................................................................................................... 213 IPermission Demand Method ......................................................................................... 214 IPermission Inheritance Hierarchy ................................................................................. 215 Stack Walking................................................................................................................. 216 Assert .............................................................................................................................. 217 Demand ........................................................................................................................... 218 Other CAS Methods........................................................................................................ 219 Security Policy Simplification ........................................................................................ 220 Simple Sandboxing API.................................................................................................. 221 Sandbox Example ........................................................................................................... 222 Setting up Permissions.................................................................................................... 223 Creating the Sandbox...................................................................................................... 224 Role-Based Security in .NET.......................................................................................... 225 Identity Objects............................................................................................................... 226 Principal Objects............................................................................................................. 227 Windows Principal Information...................................................................................... 228 Custom Identity and Principal ........................................................................................ 230 BasicIdentity.cs............................................................................................................... 231 BasicSecurity.cs .............................................................................................................. 232 Users.cs ........................................................................................................................... 235 Roles.cs ........................................................................................................................... 237 RoleDemo.cs................................................................................................................... 239 Sample Run..................................................................................................................... 240 PrincipalPermission ........................................................................................................ 241

Page 9: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

Rev. 4.0 Copyright ©2010 Object Innovations Enterprises, LLC ix All Rights Reserved

Lab 7 ............................................................................................................................... 242 Summary ......................................................................................................................... 243

Chapter 8 Interoperating with COM and Win32 .................................................... 247 Interoperating Between Managed and Unmanaged Code .............................................. 249 COM Interop and PInvoke.............................................................................................. 250 Calling COM Components from Managed Code ........................................................... 251 The TlbImp.exe Utility ................................................................................................... 252 TlbImp Syntax ................................................................................................................ 253 Using TlbImp.................................................................................................................. 254 Demonstration: Wrapping a Legacy COM Server.......................................................... 255 Register the COM Server................................................................................................ 257 OLE/COM Object Viewer .............................................................................................. 258 Run the COM Client ....................................................................................................... 259 Implement the .NET Client Program.............................................................................. 261 Import a Type Library Using Visual Studio ................................................................... 264 Platform Invocation Services (Pinvoke) ......................................................................... 266 A Simple Example .......................................................................................................... 267 Marshalling out Parameters ............................................................................................ 269 Translating Types ........................................................................................................... 271 Lab 8 ............................................................................................................................... 273 Summary ......................................................................................................................... 274

Chapter 9 ADO.NET and LINQ................................................................................ 277 ADO.NET ....................................................................................................................... 279 ADO.NET Architecture .................................................................................................. 280 .NET Data Providers....................................................................................................... 282 ADO.NET Interfaces ...................................................................................................... 283 .NET Namespaces........................................................................................................... 284 Connected Data Access .................................................................................................. 285 AcmePub Database ......................................................................................................... 286 Creating a Connection .................................................................................................... 287 Using Server Explorer .................................................................................................... 288 Performing Queries......................................................................................................... 289 Connecting to a Database ............................................................................................... 290 Database Code ................................................................................................................ 291 Using Commands............................................................................................................ 293 Creating a Command Object........................................................................................... 294 Using a Data Reader ....................................................................................................... 295 Data Reader: Code Example........................................................................................... 296 Generic Collections......................................................................................................... 297 Executing Commands ..................................................................................................... 298 Parameterized Queries .................................................................................................... 299 Parameterized Query Example ....................................................................................... 300 Lab 9A ............................................................................................................................ 301 DataSet............................................................................................................................ 302

Page 10: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

Rev. 4.0 Copyright ©2010 Object Innovations Enterprises, LLC x All Rights Reserved

DataSet Architecture....................................................................................................... 303 Why DataSet? ................................................................................................................. 304 DataSet Components....................................................................................................... 305 DataAdapter .................................................................................................................... 306 DataSet Example Program.............................................................................................. 307 Data Access Class ........................................................................................................... 308 Retrieving the Data ......................................................................................................... 309 Filling a DataSet ............................................................................................................. 310 Accessing a DataSet........................................................................................................ 311 Using a Standalone DataTable........................................................................................ 312 DataTable Update Example ............................................................................................ 313 Adding a New Row......................................................................................................... 316 Searching and Updating a Row ...................................................................................... 317 Deleting a Row ............................................................................................................... 318 Row Versions.................................................................................................................. 319 Row State ........................................................................................................................ 320 Iterating Through DataRows .......................................................................................... 321 Command Builders ......................................................................................................... 322 Updating a Database ....................................................................................................... 323 Data Binding ................................................................................................................... 324 DataGridView Control.................................................................................................... 325 Language Integrated Query (LINQ) ............................................................................... 326 Bridging Objects and Data.............................................................................................. 327 LINQ Demo .................................................................................................................... 328 Object Relational Designer ............................................................................................. 329 IntelliSense...................................................................................................................... 331 Basic LINQ Query Operators ......................................................................................... 332 Obtaining a Data Source ................................................................................................. 333 LINQ Query Example..................................................................................................... 334 Filtering........................................................................................................................... 335 Ordering .......................................................................................................................... 336 Aggregation .................................................................................................................... 337 Obtaining Lists and Arrays ............................................................................................. 338 Deferred Execution ......................................................................................................... 339 Modifying a Data Source ................................................................................................ 340 Performing Inserts via LINQ to SQL.............................................................................. 341 Performing Deletes via LINQ to SQL ............................................................................ 342 Performing Updates via LINQ to SQL ........................................................................... 343 Lab 9B............................................................................................................................. 344 Summary ......................................................................................................................... 345

Appendix A Learning Resources .............................................................................. 355

Page 11: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 1 All Rights Reserved

Chapter 1

.NET Fundamentals

Page 12: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 2 All Rights Reserved

.NET Fundamentals

Objectives

After completing this unit you will be able to:

• Understand the problems Microsoft .NET is designed to solve.

• Understand the basic programming model of Microsoft .NET.

• Understand the basic programming tools provided by Microsoft .NET.

Page 13: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 3 All Rights Reserved

What Is Microsoft .NET?

• Microsoft .NET was developed to solve three fundamental problems.

• First, the Microsoft Windows programming model must be unified to remove the widely varied programming models and approaches that exist among the various Microsoft development technologies.

• Second, Microsoft based solutions must be capable of interacting with the modern world of heterogeneous computing environments.

• Third, Microsoft needs a development paradigm that is capable of being expanded to encompass future development strategies, technologies, and customer demands.

Page 14: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 4 All Rights Reserved

Open Standards and Interoperability

• The modern computing environment contains a vast variety of hardware and software systems.

− Computers range from mainframes and high-end servers, to workstations and PCs, and to small mobile devices such as PDAs and cell phones.

− Operating systems include traditional mainframe systems, many flavors of Unix, Linux, several versions of Windows, real-time systems and special systems such as PalmOs for mobile devices.

− Many different languages, databases, application development tools and middleware products are used.

• Applications need to be able to work in this heterogeneous environment.

− Even shrink-wrapped applications deployed on a single PC may use the Internet for registration and updates.

• The key to interoperability among applications is the use of standards, such as HTML, HTTP, XML, SOAP, and TCP/IP.

Page 15: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 5 All Rights Reserved

Windows Development Problems

• In classic Windows development design and language choice often clashed.

− Visual Basic vs. C++ approach

− IDispatch, Dual, or Vtable interfaces

− VB vs. MFC

− ODBC or OLEDB or ADO

• Application deployment was hard.

− Critical entries in Registry for COM components

− No versioning strategy

− DLL Hell

• Security was difficult to implement.

− No way to control code or give code rights to certain actions and deny it the right to do other actions.

− Security model is difficult to understand. Did you ever pass anything but NULL to a LPSECURITY_ATTRIBUTES argument?

• Too much time is spent in writing plumbing code that the system should provide.

− MTS/COM+ a step in the right direction.

Page 16: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 6 All Rights Reserved

Common Language Runtime

• The first step in solving the three fundamental problems is for Microsoft .NET to provide a set of underlying services available to all languages.

• The runtime environment provided by .NET that provides these services is called the Common Language Runtime or CLR.

− A runtime provides services to executing programs.

− Traditionally there are different runtimes for different programming environments. Examples of runtimes include the standard C library, MFC, the Visual Basic 6 runtime and the Java Virtual Machine.

• These services are available to all languages that follow the rules of the CLR.

− C# and Visual Basic are examples of Microsoft languages that are fully compliant with the CLR requirements.

− Not all languages use all the features of the CLR.

• As a terminology note, beginning with .NET 2.0, Microsoft has dropped the “.NET” in the Visual Basic language.

− The pre-.NET version of the language is now referred to as Visual Basic 6 or VB6.

Page 17: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 7 All Rights Reserved

Serialization Example

• Let us use serialization to illustrate how the CLR provides a set of services that unifies the Microsoft development paradigm.

− Every programmer has to do it.

− It can get complicated with nested objects, complicated data structures, and a variety of data storages.

− The programmer should also be able to override the system service if necessary.

• See the Serialize example in this chapter.

Page 18: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 8 All Rights Reserved

Serialization Example (Cont’d)

• Ignore the language details covered in a later chapter. [Serializable] class Customer { public string name; public long id; } class Test { static void Main(string[] args) { ArrayList list = new ArrayList(); Customer cust = new Customer(); cust.name = "Charles Darwin"; cust.id = 10; list.Add(cust); cust = new Customer(); cust.name = "Isaac Newton"; cust.id = 20; list.Add(cust); foreach (Customer x in list) Console.WriteLine(x.name + ": " + x.id); Console.WriteLine("Saving Customer List"); FileStream s = new FileStream("cust.txt", FileMode.Create); SoapFormatter f = new SoapFormatter(); SaveFile(s, f, list);

Page 19: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 9 All Rights Reserved

Serialization Example (Cont’d)

Console.WriteLine("Restoring to New List"); s = new FileStream("cust.txt", FileMode.Open); f = new SoapFormatter(); ArrayList list2 = (ArrayList)RestoreFile(s, f); foreach (Customer y in list2) Console.WriteLine(y.name + ": " + y.id); } public static void SaveFile(Stream s, IFormatter f, IList list) { f.Serialize(s, list); s.Close(); } public static IList RestoreFile(Stream s, IFormatter f) { IList list = (IList)f.Deserialize(s); s.Close(); return list; } }

Page 20: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 10 All Rights Reserved

Attribute-Based Programming

• We add two Customer objects to the collection, and print them out. We save the collection to disk and then restore it. The identical list is printed out.

Charles Darwin: 10 Isaac Newton: 20 Saving Customer List Restoring to New List Charles Darwin: 10 Isaac Newton: 20 Press enter to continue...

• We wrote no code to save or restore the list!

− We just annotated the class we wanted to save with the Serializable attribute.

− We specified the format (SOAP) that the data was to be saved.

− We specified the medium (disk) where the data was saved.

− This is typical class partitioning in the .NET Framework.

• Attribute-based programming is used throughout .NET to describe how code and data should be treated by the framework.

Page 21: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 11 All Rights Reserved

Metadata

• The compiler adds the Serializable attribute to the metadata of the Customer class.

• Metadata provides the Common Language Runtime with information it needs to provide services to the application.

− Version and locale information

− All the types

− Details about each type, including name, visibility, etc.

− Details about the members of each type, such as methods, the signatures of methods, etc.

− Attributes

• Metadata is stored with the application so that .NET applications are self-describing. The registry is not used.

− The CLR can query the metadata at runtime. It can see if the Serializable attribute is present. It can find out the structure of the Customer object in order to save and restore it.

Page 22: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 12 All Rights Reserved

Types

• Types are at the heart of the programming model for the CLR.

− Most of the metadata is organized by type.

• A type is analogous to a class in most object-oriented programming languages, providing an abstraction of data and behavior, grouped together.

• A type in the CLR contains:

− Fields (data members)

− Methods

− Properties

− Events (which are now full fledged members of the Microsoft programming paradigm).

Page 23: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 13 All Rights Reserved

NET Framework Class Library

• The SoapFormatter and FileStream classes are two of the thousands of classes in the .NET Framework that provide system services.

• The functionality provided includes:

− Base Class Library (basic functionality such as strings, arrays and formatting).

− Networking

− Security

− Remoting

− Diagnostics

− I/O

− Database

− XML

− Web Services

− Web programming

− Windows User Interface

• This framework is usable by all CLR compliant languages.

Page 24: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 14 All Rights Reserved

Interface-Based Programming

• Interfaces allow you to work with abstract types in a way that allows for extensible programming.

• The SaveFile and RestoreFile routines are written using the IList and IFormatter interfaces.

• These routines will work with all the collection classes that support the IList interface, and the formatters that support the IFormatter interface.

• Implementation inheritance permits code reuse.

• You can implement the ISerializable interface to override the framework’s implementation.

− The metadata for the type tells the framework that the class has implemented the interface.

• Interface-based programming allows classes to provide implementations of standard functionality that can be used by the framework.

Page 25: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 15 All Rights Reserved

Everything is an Object

• Every type in .NET derives from System.Object.1

• Every type, system or user defined, has metadata.

− In the sample the framework can walk through the ArrayList of Customer objects and save each one as well as the array itself.

• All access to objects in .NET is through object references.

1 An exception is the pointer type, which is rarely used in C#.

Page 26: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 16 All Rights Reserved

Common Type System

• The Common Type System (CTS) defines the rules for the types and operations that the CLR will support.

− The CTS limits .NET classes to single implementation inheritance.

− The CTS is designed for a wide range of languages, not all languages will support all features of the CTS.

• The CTS makes it possible to guarantee type safety.

− Access to objects can be restricted to object references (no pointers), each reference refers to a defined memory. Access to that layout is only through public methods and fields.

− By performing a local analysis of the class, you can verify to make sure that the code does not perform any inappropriate memory access. You do not have to analyze the users of the class.

• .NET compilers emit Microsoft Intermediate Language (MSIL or IL) not native code.

− MSIL is platform independent.

− Type-safe code can be restricted to a subset of verifiable MSIL expressions.

− Once code is verified, it is verified for all platforms.

Page 27: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 17 All Rights Reserved

ILDASM

• The Microsoft Intermediate Language Disassembler (ILDASM) can display the metadata and MSIL instructions associated with .NET code.

− It is a very useful tool both for debugging and increasing your understanding of the .NET infrastructure.

• You may wish to add ILDASM to your Tools menu in Visual Studio 2010.

− Use the command Tools | External Tools. Click the Add button, enter ILDASM for the Title, and click the ... button to navigate to the folder \Program Files\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools.

Page 28: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 18 All Rights Reserved

ILDASM (Cont’d)

• You can use ILDASM to examine the .NET framework code.

− Here is a fragment of the MSIL from the Serialize example.

Page 29: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 19 All Rights Reserved

.NET Framework SDK Tools

• Installing Visual Studio 2010 will also install the .NET Framework SDK, version 7.0A.

− These tools are located in the folder C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin.

− They can be run at the command line from the Visual Studio 2010 Command Prompt, which can be started from All Programs | Microsoft Visual Studio 2010 | Visual Studio Tools | Visual Studio Command Prompt (2010).

Page 30: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 20 All Rights Reserved

Language Interoperability

• Having all language compilers use a common intermediate language and common base class makes it possible for languages to interoperate.

− All languages need not implement all parts of the CTS.

− One language can have a feature that another does not.

• The Common Language Specification (CLS) defines a subset of the CTS that represents the basic functionality that all .NET languages should implement if they are to interoperate with each other.

− For example, a class written in Visual Basic can inherit from a class written in C#.

− Interlanguage debugging is possible.

− CLS rule: Method calls need not support a variable number of arguments even though such a construct can be expressed in MSIL.

− CLS prohibits the use of pointers.

• CLS compliance only applies to public features.

− C# code should not define public and protected class names that differ only by case sensitivity since languages as Visual Basic are not case sensitive. Private C# fields could have such names.

Page 31: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 21 All Rights Reserved

Managed Code

• In the serialization example we never freed any allocated memory.

− Memory that is no longer referenced can be reclaimed by the CLR’s garbage collector.

− Automatic memory management eliminates the common programming error of memory leaks.

− Garbage collection is one of the services provided to .NET applications by the Common Language Runtime.

• Managed code uses the services of the CLR.

− MSIL can express access to unmanaged data in legacy code.

• Type-safe code cannot be subverted.

− For example, a buffer overwrite is not able to corrupt other data structures or programs. Security policy can be applied to type-safe code.

• Type-safe code can be secured.

− Access to files or user interface features can be controlled.

− You can prevent the execution of code from unknown sources.

− You can prevent access to unmanaged code to prevent subversion of .NET security.

− Paths of execution of .NET code to be isolated from one another.

Page 32: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 22 All Rights Reserved

Assemblies

• .NET programs are deployed as an assembly.

− The metadata about the entire assembly is stored in the assembly’s manifest.

− An assembly has one or more EXEs or DLLs with associated metadata information.

Page 33: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 23 All Rights Reserved

Assembly Deployment

• The assemblies can be uniquely named.

− Assemblies can be versioned and the version is part of the assembly’s name.

− Unique (strong) names use a public/private encryption scheme.

− The culture used can also be made part of the assembly name.

• Assemblies are self-describing. Information is in the metadata associated with the assembly, not in the System Registry.

• Private, or xcopy deployment requires only that all the assemblies an application needs are in the same directory.

− This makes deployment of components much simpler.

• Public assemblies require a strong name and an entry in the Global Assembly Cache (GAC).

• Either approach means the end of DLL Hell!

− Components with different versions can be deployed side by side and need not interfere with each other.

Page 34: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 24 All Rights Reserved

JIT Compilation

• Before executing on the target machine, MSIL is translated by a just-in-time (JIT) compiler to native code.

• Some code typically will never be executed during a program run.

− Hence it may be more efficient to translate MSIL as needed during execution, storing the native code for reuse.

• When a type is loaded, the loader attaches a stub to each method of the type.

− On the first call the stub passes control to the JIT, which translates to native code and modifies the stub to save the address of the translated native code.

− On subsequent calls to the method transfer is then made directly to the native code.

• As part of JIT compilation code goes through a verification process.

− Type safety is verified, using both the MSIL and metadata.

− Security restrictions are checked.

Page 35: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 25 All Rights Reserved

ASP.NET and Web Services

• .NET includes a totally redone version of the popular Active Server Pages technology, known as ASP.NET.

• Whereas ASP relied on interpreted script code interspersed with page formatting commands, ASP.NET relies on compiled code.

− The code can be written in any .NET language, including C#, Visual Basic, JScript.NET and C++/CLI.

• ASP.NET provides Web Forms which vastly simplifies creating Web user interfaces.

− Drag and drop in Visual Studio 2010 makes it very easy to lay out forms.

− You can add code to form events such as a button click.

• For application integration across the internet, Web services use the SOAP protocol.

− The beautiful thing about a Web service is that from the perspective of a programmer, a Web service is no different from any other kind of service implemented by a class in a .NET language.

− Or you can use third-party web services which you did not know existed when you designed your application.

• Web services and C# (or Visual Basic) as a scripting language allows Web programming to follow an object-oriented programming model.

Page 36: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 26 All Rights Reserved

The Role of XML

• XML is ubiquitous in .NET and is highly important in Microsoft’s overall vision.

• Some uses of XML in .NET include:

− XML is used for encoding requests and responses in the SOAP protocol.

− XML is the serialization format for disconnected datasets in ADO.NET.

− XML is used extensively in configuration files.

− XML documentation can be automatically generated by .NET languages.

− .NET classes provide a very convenient API for XML programming as an alternative to DOM or SAX.

Page 37: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 27 All Rights Reserved

Performance

• Concerns about performance of managed code are similar to the concerns assembly language programmers had with high level languages.

• Garbage collection usually produces faster allocation than C++ unmanaged heap allocation. Deallocation is done on a separate thread by the garbage collector.

• JIT compilation takes a hit the first time when verification and translation take place, but subsequent executions pay no penalty.

• There is a penalty when security checks have to be made that require a stack walk.

• Compiled ASP.NET code is going to be a lot faster than interpreted ASP pages.

• Bottom line: for most of the code that is written, any small loss in performance is far outweighed by the gains in reliability and ease of development.

− High performance servers might still have to use technologies such as ATL Server and C++.

Page 38: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 1

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 28 All Rights Reserved

Summary

• .NET solves problems of past Windows development.

• One development paradigm for all languages exists.

• Design and programming language no longer conflict.

• Web services provide an API for applications across the Internet, typically using the SOAP protocol.

• SOAP supports a high degree of interoperability, since it is based on widely adopted standards such as HTTP and XML.

• .NET has many features which will create a much more robust Windows operating system.

• .NET uses managed code with services provided by the Common Language Runtime that uses the Common Type System.

• The .NET Framework is a very large class library available consistently across many languages.

• Deployment is more rational and includes a versioning strategy.

• Metadata, attribute-based security, code verification, and type-safe assembly isolation make developing secure applications much easier.

• Plumbing code for fundamental system services is there, yet you can extend it or replace it if necessary.

Page 39: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 5

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 121 All Rights Reserved

Chapter 5

I/O and Serialization

Page 40: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 5

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 122 All Rights Reserved

I/O and Serialization

Objectives

After completing this unit you will be able to:

• Describe and use .NET Framework classes for working with directories and files.

• Explain streams and use them for performing file I/O.

• Describe the use of metadata in serialization, and implement serialization in your classes.

• Use attributes in .NET to hook into code supplied by the system.

Page 41: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 5

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 123 All Rights Reserved

Input and Output in .NET

• The .NET Framework provides a very flexible and consistent framework for performing input and output.

• The classes supporting input and output are in the System.IO namespace.

• In this section, we will first examine how the .NET Framework handles directories.

• Then we will look at file I/O, which makes use of an intermediary called a stream.

• We conclude with a discussion of serialization, which we illustrated in Chapter 1 and which depends on the concept of metadata that we have discussed.

Page 42: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 5

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 124 All Rights Reserved

Directories

• The classes Directory and DirectoryInfo contain routines for working with directories.

− All the methods of Directory are static, and so you can call them without having a directory instance.

− The DirectoryInfo class contains instance methods.

− In many cases, you can accomplish the same objective using methods of either class.

− The methods of Directory always perform a security check.

− If you are going to reuse a method several times, it may be better to obtain an instance of DirectoryInfo and use its instance methods, because a security check may not always be necessary.

− Security will be discussed in later in the course.

Page 43: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 5

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 125 All Rights Reserved

Directory Example Program

• We illustrate both classes with a simple program DirectoryDemo, which contains DOS-like commands:

− dir to show the contents of the current directory

− cd to change the current directory

• A directory can contain both files and other directories.

− The method GetFiles returns an array of FileInfo objects, and the method GetDirectories returns an array of DirectoryInfo objects.

• In this program we only use the Name property of FileInfo.

• In the following section we will see how to read and write files using streams.

Page 44: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 5

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 126 All Rights Reserved

Directory Example Program (Cont’d)

using System; using System.IO; public class DirectoryDemo { private static string path; private static DirectoryInfo dir; public static void Main() { path = Directory.GetCurrentDirectory(); Console.WriteLine("path = {0}", path); dir = new DirectoryInfo(path); InputWrapper iw = new InputWrapper(); string cmd; Console.WriteLine( _ "Enter command, quit to exit"); cmd = iw.getString("> "); while (! cmd.Equals("quit")) { try { if (cmd.Equals("cd")) { path = iw.getString("path: "); dir = new DirectoryInfo(path); Directory.SetCurrentDirectory(path); } ...

Page 45: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 5

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 127 All Rights Reserved

Directory Example Program (Cont’d)

... else if (cmd.Equals("dir")) { FileInfo[] files = dir.GetFiles(); Console.WriteLine("Files:"); foreach (FileInfo f in files) Console.WriteLine(" {0}", f.Name); DirectoryInfo[] dirs = dir.GetDirectories(); Console.WriteLine("Directories:"); foreach (DirectoryInfo d in dirs) Console.WriteLine(" {0}", d.Name); } else help(); ...

• Here is a sample run. Note that the current directory starts out as the directory containing the program’s executable.

path = C:\OIC\NetCs\Chap05\DirectoryDemo\bin\Debug Enter command, quit to exit > cd path: .. > dir Files: Directories: Debug >

Page 46: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 5

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 128 All Rights Reserved

Files and Streams

• Programming languages have undergone an evolution in how they deal with the important topic of file I/O.

− Early languages, such as FORTRAN, COBOL, and the original BASIC, had I/O statements built into the language.

− Later languages have tended not to have I/O built into the language, but instead rely on a standard library for performing I/O, such as the <stdio.h> library in C. The library in languages like C works directly with files.

• Still later languages, such as C++ and Java, introduced a further abstraction called a stream.

− A stream serves as an intermediary between the program and the file.

− Read and write operations are done to the stream, which is tied to a file.

− This architecture is very flexible, because the same kind of read and write operations can apply not only to a file, but to other kinds of I/O, such as network sockets.

− This added flexibility introduces a slight additional complexity in writing programs, because you have to deal not only with files but also with streams, and there exists a considerable variety of stream classes.

− But the added complexity is well worth the effort, and .NET strikes a nice balance, with classes that make performing common operations quite simple.

Page 47: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 5

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 129 All Rights Reserved

Files and Streams (Cont’d)

• As with directories, the System.IO namespace contains two classes for working with files.

− The File class has all static methods, and the FileInfo class has instance methods.

• The program FileDemo extends the DirectoryDemo example program to illustrate reading and writing text files.

− We will illustrate binary file I/O later in this chapter, when we discuss serialization.

• The directory commands are retained so that you can easily exercise the program on different directories.

• The two new commands are “read” and “write.”

− The “read” command illustrates using the File class.

− The “dir” command, already present in the DirectoryDemo program, illustrates using the FileInfo class.

Page 48: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 5

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 130 All Rights Reserved

“Read” Command

• The code for the “read” command is shown below.

− The user is prompted for a file name. The static OpenText method returns a StreamReader object, which is used for the actual reading.

− There is a ReadLine method for reading a line of text, similar to the ReadLine method of the Console class. A null reference is returned by ReadLine when at end of file.

• Our program simply displays the contents of the file at the console. When done, we close the StreamReader.

... else if (cmd.Equals("read")) { string fileName = iw.getString("file name: "); StreamReader reader = File.OpenText(fileName); string str; while ((str = reader.ReadLine()) != null) { Console.WriteLine(str); } reader.Close(); } ...

Page 49: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 5

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 131 All Rights Reserved

Code for “Write” Command

• The code for the “write” command is shown below.

− Again we prompt for a file name. This time we also prompt for whether or not to append to the file.

− There is a special constructor for the StreamWriter class that will directly return a StreamWriter without first getting a file object.

− The first parameter is the name of the file, and the second a bool flag specifying the append mode. If true, the writes will append to the end of an already existing file. If false, the writes will overwrite an existing file. In both cases, if a file of the specified name does not exist, a new file will be created.

... else if (cmd.Equals("write")) { string fileName = iw.getString("file name: "); string strAppend = iw.getString( "append (yes/no): "); bool append = (strAppend == "yes" ? true : false); StreamWriter writer = new StreamWriter( fileName, append); Console.WriteLine( "Enter text, blank line to terminate"); string str; while ((str = iw.getString(">>") != "") { writer.WriteLine(str); } writer.Close(); } ...

Page 50: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 5

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 132 All Rights Reserved

Serialization

• Using the File and Stream classes can be quite cumbersome if you have to save a complicated data structure with linked objects.

− You have to save the individual fields to disk, remembering which field belongs to which object, and which object instance was linked to another object instance.

− When restoring the data structure you have to reconstitute that arrangement of fields and object references.

• The serialization technology provided by the .NET Framework does this for you.

− “Serialize” means convert a graph of objects into a linear sequence of bytes.

− This sequence of bytes can then be written to a stream or otherwise used to transmit all the data associated with the object instance.

− Objects can be serialized without writing special code, because the metadata knows the object’s memory layout.

• To hook into the serialization mechanism provided by the .NET Framework, you mark your class with a special attribute.

Page 51: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 5

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 133 All Rights Reserved

Attributes

• The traditional approach to implementing functionality is to write code.

− A whole different approach to implementing complex code is to let the system do it for you. There must be a way for the programmer to inform the system of what is desired. In the .NET Framework such cues can be given to the system by means of attributes.

• Microsoft introduced attribute-based programming in Microsoft Transaction Server.

− The concept was that MTS, not the programmer, would implement complex tasks such as distributed transactions.

− The programmer would “declare” the transaction requirements for a COM class, and MTS would implement it.

− This use of attributes was greatly extended in the next generation of MTS, known as COM+.

− In MTS and COM+ attributes are stored in a separate repository, distinct from the program itself.

Page 52: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 5

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 134 All Rights Reserved

Attributes (Cont’d)

• Attributes are also used in Interface Definition Language (IDL), which gives a precise specification of COM interfaces.

− Part of the function of IDL is to make it possible for a tool to generate proxies and stubs for remoting a method call across a process boundary or even across a network.

− When parameters are passed remotely, it may be necessary to supply additional information.

− For example, within a process, you can simply pass a reference to an array. But in passing an array across a process boundary, you must inform the tool of the size of the array.

− This information is communicated in IDL by means of attributes, which are specified using a square bracket notation. Again, attribute information is stored in a location separate from program code.

• A problem with attributes in both MTS/COM+ and IDL is that they are separate from the program source code. When the source code is modified, the attribute information may become out of synch with the code.

• In C#, attributes are declared with square brackets. Unlike IDL, the attributes are part of the program source code. When compiled into intermediate language, the attributes become part of the metadata.

Page 53: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 5

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 135 All Rights Reserved

Serialization Example

• The program SerializeAccount illustrates serialization of the Account class by means of an attribute.

• The code for the Account class is shown below, and only one line of code is involved:

− The attribute [System.Serializable] is placed before the class. In this case, all the data members of the class will be serialized.

− If you want to exclude a data member from being serialized, for example, because it contained some kind of temporary cache of data, you can place the attribute [System.NonSerialized] in front of the member you want excluded.

− Serialization applies only to instance data members; static members are never serialized.

using System; [System.Serializable] public class Account { private decimal balance; private string owner; private int id; ...

Page 54: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 5

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 136 All Rights Reserved

Serialization Example (Cont’d)

• While making a class serializable is simply a matter of using an attribute, you must write a little code to cause an object graph to serialize itself.

• If you are using serialization to implement persistence, you need to perform the following four basic steps to save the data.

1. Instantiate a FileInfo object where the data will be saved.

2. Open up a Stream object for writing to the file.

3. Instantiate a formatter object for laying out the objects in a suitable format.

4. Apply the formatter’s Serialize method to the root object and the stream.

• There are various built-in formatters provided by the .NET Framework, including:

− BinaryFormatter lays out object data in a binary format.

− SOAPFormatter lays out object data in an XML format.

• If you use a binary formatter, you will need the following two namespaces in order to perform the serialization:

− System.Runtime.Serialization

− System.Runtime.Serialization.Formatters.Binary

Page 55: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 5

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 137 All Rights Reserved

Serialization Example (Cont’d)

• See the file SerializeAccount.cs for a test program that provides commands to save and load a collection of accounts.

using System; using System.Collections; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; public class SerializeAccount { private static ArrayList accounts; public static void Main() { ... else if (cmd.Equals("save")) { FileInfo f = new FileInfo("accounts.bin"); Stream s = f.Open(FileMode.Create); BinaryFormatter b = new BinaryFormatter(); b.Serialize(s, accounts); s.Close(); } else if (cmd.Equals("load")) { FileInfo f = new FileInfo("accounts.bin"); Stream s = f.Open(FileMode.Open); BinaryFormatter b = new BinaryFormatter(); accounts = (ArrayList) b.Deserialize(s); s.Close(); } ...

Page 56: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 5

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 138 All Rights Reserved

Lab 5

Serializing the Customer Class

In this lab you will implement serialization code for the Customer class in the Acme Customer Management System, enabling you to store the list of customers persistently in a file. You will provide both a binary and a SOAP version of your solution.

Detailed instructions are contained in the Lab 5 write-up at the end of the chapter.

Suggested time: 30 minutes

Page 57: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 5

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 139 All Rights Reserved

Summary

• The .NET Framework provides a flexible and consistent framework for performing input and output.

• The classes DirectoryInfo and FileInfo contain instance methods.

• The classes Directory and File contain static methods and always perform a security check.

• File I/O is accomplished with the aid of stream classes.

• Serialization makes effective use of metadata to persist data structures to streams.

• Attributes in .NET make it easy for your programs to hook into code supplied by the system.

Page 58: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 5

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 140 All Rights Reserved

Lab 5

Serializing the Customer Class

Introduction In this lab you will implement serialization code for the Customer class in the Acme Customer Management System, enabling you to store the list of customers persistently in a file. You will provide both a binary and a SOAP version of your solution. Suggested Time: 30 minutes Root Directory: OIC\NetCs Directories: Labs\Lab5\SerializeCustomer (do your work here) Chap02\CustomerMonolithic (backup of starter code) Chap05\SerializeCustomer\BinaryFormat (answer, binary) Chap05\SerializeCustomer\SoapFormat (answer, SOAP) Instructions 1. In the working directory you will find a copy of the CustomerMonolithic program

from Chapter 2. Build and verify that it is working.

2. In Customer.cs add the [System.Serializable] attribute to the Customer class.

3. Add using for the Runtime.Serialization.Formatters.Binary namespace.

4. Add public methods Store and Load to the Customers class, to implement serialization and deserialization using the binary formatter. Base your code on the SerializeAccount example.

5. Add two buttons to the form to Store and Load the customer list.

6. Implement handlers for these buttons that will call the Store and Load methods that you implemented. When you load, be sure to update the customers listbox.

7. Build and test. Be sure to verify that data is persisted between separate runs of the program.

8. Modify your solution to use a SOAP formatter. Note that you will need to add a reference to System.Runtime.Serialization.Formatters.Soap.dll.

9. Build and test. Examine the XML in the text file where the data is saved.

Page 59: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 8

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 247 All Rights Reserved

Chapter 8

Interoperating with COM and Win32

Page 60: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 8

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 248 All Rights Reserved

Interoperating with COM and Win32

Objectives

After completing this unit you will be able to:

• Discuss issues of interoperability between managed and unmanaged code.

• Call legacy COM components from within the managed .NET environment using a Runtime Callable Wrapper or RCW.

• Use Platform Invocation Services (PInvoke) to call unmanaged exported DLL functions from managed client code.

Page 61: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 8

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 249 All Rights Reserved

Interoperating Between Managed and Unmanaged Code

• Microsoft .NET is a powerful platform, and there are many advantages in writing a new application within the .NET Framework.

• However, a typical application is not a world unto itself, but is built from legacy components as well as new components, and interoperability is very important.

• One kind of interoperability is Web services.

− Using the SOAP protocol it is possible for .NET applications to call Web services on other platforms, including UNIX, mainframes, and mobile devices.

• In this chapter we will look at another kind of interoperability, the interfacing of managed and unmanaged code running under Windows.

Page 62: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 8

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 250 All Rights Reserved

COM Interop and PInvoke

• The dominant programming model in modern Windows systems is the Component Object Model, or COM.

• There exist a great many legacy COM components, and so it is desirable for a .NET program, running as managed code, to be able to call unmanaged COM components.

• The converse situation, in which a COM client needs to call a .NET server, can also arise.

• Apart from COM, we may also have need for a .NET program to call any unmanaged code that is exposed as a DLL, including the Win32 API.

• The .NET Framework supports all these interoperability scenarios through COM Interoperability and the Platform Invocation Services or PInvoke.

• In this chapter we assume that you understand the concepts behind the legacy technologies.

Page 63: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 8

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 251 All Rights Reserved

Calling COM Components from Managed Code

• The first interoperability scenario we will look at is managed code calling COM components.

• The .NET Framework makes it easy to create a Runtime Callable Wrapper (RCW), which acts as a bridge between managed and unmanaged code.

• The RCW is illustrated in the figure.

Native Win32 Code(Unmanaged)

RuntimeCallableWrapper(RCW)

Managed Code

.NET ManagedClient

Legacy COMComponent

Page 64: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 8

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 252 All Rights Reserved

The TlbImp.exe Utility

• The TlbImp.exe tool (Type Library to .NET Assembly Converter) can read type library information, and automatically generate the appropriate RCW for you.

− The tool is located in the directory: \Program Files\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools.

• It is used to generate managed classes that wrap unmanaged COM classes.

− The resulting RCW is a .NET component (i.e. a managed DLL assembly) that managed client code can use to access the COM interface methods that are implemented in the COM component.

− The TlbImp tool is a command line program that reads COM type library information, and generates a managed wrapper class along with the associated metadata, and places the result into the RCW assembly.

− You can view the resulting contents in this assembly using the Ildasm tool.

Page 65: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 8

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 253 All Rights Reserved

TlbImp Syntax

• The command line syntax for TlbImp is shown below. TlbImp TypeLibName [options]

− where options may contain the following:

/out:FileName Assembly file name /namespace:Namespace Assembly Namespace /asmversion:Version Assembly version number /reference:FileName Reference assembly /publickey:FileName Public key file /keyfile:FileName Key pair file /keycontainer:FileName Key pair key container /delaysign Delay digital signing /unsafe Suppress security checks /nologo Suppress displaying logo /silent Suppress output except errors /verbose Display extra information /primary Make primary interop assembly /sysarray SAFEARRAY as System.Array /strictref Only /reference assemblies /? or /help Display help information

Page 66: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 8

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 254 All Rights Reserved

Using TlbImp

• When the TlbImp tool imports a COM type library, it creates a .NET namespace with the same name as the library defined in the type library (that is the name of the actual library, not the name of the type library file that contains it).

− TlbImp converts each COM coclass defined in the type library into a managed .NET wrapper class in the resulting .NET assembly that has one constructor with no parameters.

− Each COM interface defined in the type library is converted into a .NET interface in the resulting .NET assembly.

• Consider the typical COM IDL file library statement shown below that would be used to create a type library using Midl.exe.

− The resulting type library (TLB) or DLL file would cause TlbImp.exe to generate an assembly containing metadata, including the namespace BANKDUALLib, a managed wrapper class named Account2, and a managed interface named IAccount2.

library BANKDUALLib {... [ uuid(04519632-39C5-4A7E-AA3C-3A7D814AC91C), helpstring("Account2 Class") ] coclass Account2 { [default] interface IAccount2; }; };

Page 67: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 8

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 255 All Rights Reserved

Demonstration: Wrapping a Legacy COM Server

• The best way to get a feel for how this wrapping process works is to perform the operations yourself.

• The directory LegacyComServer contains the following files for a COM server:

BankDual.dll COM server DLL BankDual.tlb Type library reg_bankdual.bat Batch file to register the server unreg_bankdual.bat Batch file to unregister the server BankConsole.exe Client executable file

• The source code for the client and server are in the directories ClientSource and ServerSource respectively.

− Both programs are written in Visual C++, and project files are provided for Visual C++ 6.0.

− Unless you have Visual C++ 6.0 installed on your system in addition to Visual Studio 2010, you will not be able to build these projects, but that will not prevent you from running the program and creating a .NET client.

Page 68: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 8

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 256 All Rights Reserved

Demonstration: Wrapping a Legacy COM Server (Cont’d)

• This COM server implements a simple bank account class that has Deposit and Withdraw methods and a Balance property.

− The simple code is shown in Account2.cpp in the ServerSource directory.

STDMETHODIMP CAccount2::get_Balance(long *pVal) { *pVal = m_nBalance; return S_OK; } STDMETHODIMP CAccount2::Deposit(long amount) { m_nBalance += amount; return S_OK; } STDMETHODIMP CAccount2::Withdraw(long amount) { m_nBalance -= amount; return S_OK; }

Page 69: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 8

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 257 All Rights Reserved

Register the COM Server

• The first step is to register the COM server.

− You can do that by running the batch file reg_bankdual.bat, which executes the command:

regsvr32 bankdual.dll

• You can now see the registration entries using the Registry Editor (regedit.exe) or the OLE/COM Object Viewer (oleview.exe).

− The latter program is provided in this folder:

\Program Files\Microsoft SDKs\Windows\v7.0A\bin

− Make sure you are in “Expert Mode” (View menu).

− It groups related registry entries together, providing a convenient display.

− You can also perform other operations, such as instantiating objects.

− The figure shows the entries for the Account2 class that is implemented by this server. (Look under All Objects.)

− We have clicked the little “+” in the left-hand pane, which instantiates an object and queries for the standard interfaces.

− You can release the object by right-clicking over the class and choosing Release Instance from the context menu.

Page 70: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 8

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 258 All Rights Reserved

OLE/COM Object Viewer

Page 71: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 8

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 259 All Rights Reserved

Run the COM Client

• You can now run the COM client by double-clicking on BankConsole.exe in Windows Explorer.

− The starting balance is shown, followed by a withdrawal of 25, and the balance is shown again.

• The source code is in the file BankConsole.cpp in ClientSource.

• For simplicity, no error checking is done.

− Robust code should check the HRESULT that is returned from each of the COM calls.

• Here is the output from running the client program: balance = 150 balance = 125 Press Enter to quit:

Page 72: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 8

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 260 All Rights Reserved

Use TlbImp Tool

• With the Visual Studio 2010 command prompt, use TlbImp.exe to generate the wrapper assembly.

tlbimp bankdual.dll

− This creates BANKDUALLib.dll. You can view its contents using the Ildasm tool, as shown in the figure.

− Note that the namespace shown by Ildasm.exe is BANKDUALLib, the name of the interface is IAccount2, and the wrapper class is named Account2.

Page 73: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 8

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 261 All Rights Reserved

Implement the .NET Client Program

• It is now easy to implement the .NET client program.

− See the directory NetClient. The runtime callable wrapper (RCW) BANKDUALLib.dll is copied to this directory.

− Here is the source code of the client NetClient.cs:

using System; using BANKDUALLib; class NetClient { public static void Main() { Account2 acc; acc = new Account2(); Console.WriteLine( "balance = {0}", acc.Balance); acc.Withdraw(25); Console.WriteLine( "balance = {0}", acc.Balance); } }

• As with the COM client program, for simplicity we do no error checking.

− In the .NET version we should use exception handling to check for errors.

− The RCW uses the namespace BANKDUALLib, based on the name of the type library.

Page 74: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 8

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 262 All Rights Reserved

Implement the .NET Client (Cont’d)

• You must add a reference to BANKDUALLib.dll.

− In the Visual Studio Solution Explorer you can right-click over References, choose “Add Reference”, and use the ordinary .NET tab of the Add Reference dialog.

• Build and run the project inside of Visual Studio.

− You should see the following output:

balance = 150 balance = 125 Press any key to continue

• Once you have added a reference to a RCW, you have all the features of the IDE available for .NET assemblies, including Intellisense and the Object Browser.

− You can bring up the Object Browser from View | Object Browser.

Page 75: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 8

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 263 All Rights Reserved

Object Browser

• The figure illustrates the information shown in the Object Browser.

Page 76: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 8

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 264 All Rights Reserved

Import a Type Library Using Visual Studio

• When you are using Visual Studio you can import a COM type library directly, without first running TlbImp.exe.

− We’ll demonstrate with the project in Demos\NetClientVs, which is a copy of NetClient.

1. In Solution Explorer, delete the reference to BANKDUALLib.dll, and delete the file itself.

2. Now right-click over References, choose “Add Reference”, and this time select the COM tab from the Add Reference dialog.

3. The listbox will show all the COM components with a registered type library.

Page 77: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 8

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 265 All Rights Reserved

Import a Type Library (Cont’d)

4. Select “BankDual 1.0 Type Library”, as illustrated in the figure.

5. Click OK. Visual Studio will generate a wrapper for you. The generated “interop assembly” is Interop.BANKDUALLib.dll in the directory obj\Debug.

6. You should be able to build and run the .NET client program. (If you should delete the interop assembly, it will be regenerated when you build the program.)

Page 78: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 8

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 266 All Rights Reserved

Platform Invocation Services (Pinvoke)

• Platform Invocation Services, also known as "PInvoke", makes unmanaged exported DLL functions available to managed client code.

− PInvoke allows this to be done from managed code written in any .NET programming language.

− Notice that PInvoke is not the name of a class, or a method, but is just a nickname for Platform Invocation Services.

• PInvoke allows marshaling between CLR data types and native data types, and bridges other differences between the managed and unmanaged runtime environments.

• Although PInvoke is primarily used to access the Win32 APIs, it can be used to call into your own legacy DLLs that you may find are still useful.

Page 79: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 8

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 267 All Rights Reserved

A Simple Example

• Let’s begin with a very simple example of the use of PInvoke, to call the Windows MessageBox function.

• Our sample program is in the directory SimplePInvoke.

using System; using System.Runtime.InteropServices; class SimplePInvoke { [DllImport("user32.dll", EntryPoint="MessageBoxA")] public static extern int ShowMessage( int hWnd, string text, string caption, int type); public static void Main(string[] args) { ShowMessage( 0, "Hello, World", "From PInvoke", 0); } }

Page 80: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 8

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 268 All Rights Reserved

A Simple Example (Cont’d)

• The key step is to place a DllImport attribute before the prototype of the function we want to call.

− The function must take ordinary C# data types as parameters, which have natural mappings to the C data types of the native function.

− The function will be treated as a static method in the class where it is defined.

− The one required parameter to the DllImport attribute is the name of the DLL exporting the function.

− There are various optional, named parameters, that can be used with DllImport.

− For a complete list, consult the documentation of the DllImportAttribute class in the System.Runtime.InteropServices namespace.

Page 81: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 8

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 269 All Rights Reserved

Marshalling out Parameters

• The previous PInvoke example did not demonstrate how PInvoke automatically marshals out parameters for you where there is a clear mapping between Win32 and the CLR types.

− This is because the MessageBox takes only in parameters.

• The next example calls the GetComputerName and GetLastError APIs via PInvoke.

• The code for this example is in the directory PInvoke. using System; using System.Text; using System.Runtime.InteropServices; public class Test { [DllImport("kernel32.dll", CharSet=CharSet.Ansi)] public static extern bool GetComputerName( StringBuilder name, out uint buffer); [DllImport("kernel32.dll")] public static extern uint GetLastError(); ...

Page 82: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 8

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 270 All Rights Reserved

PInvoke.cs (Cont’d)

... public static int Main(string[] args) { bool result = true; uint error = 0; StringBuilder name = new StringBuilder(128); uint length = 128; result = GetComputerName(name, out length); if (result == true) Console.WriteLine(name); else { error = GetLastError(); Console.WriteLine("Error: {0:x}", error); } return 0; } }

Page 83: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 8

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 271 All Rights Reserved

Translating Types

• Since GetComputerName returns a name, StringBuilder was used instead of string .

− For input only arguments you can use string.

− An out keyword was placed on the length parameter because the second argument to GetComputerName is a pointer.

− Unsigned types were used because DWORD is a 32-bit integer quantity.

− For comparison, here are the prototypes of the corresponding Win32 functions:

BOOL GetComputerName( LPTSTR lpBuffer, // computer name LPDWORD lpnSize // size of name buffer ); DWORD GetLastError(VOID);

Page 84: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 8

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 272 All Rights Reserved

Translating Types (Cont’d)

• Some CLR types do not map directly into unmanaged types.

− You have to tell the Execution Engine (mscoree.dll) how to translate to a BSTR.

− You do that by annotating the declaration with the MarshalAs attribute:

[MarshalAs(UnmanagedType.BStr)] public string foo

• The UnmanagedType enumeration lists all the translatable types.

Page 85: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 8

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 273 All Rights Reserved

Lab 8

Using COM Servers in C#

In this lab, you will use a COM server from within a C# application.

Detailed instructions are contained in the Lab 8 write-up at the end of the chapter.

Suggested time: 30 minutes

Page 86: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 8

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 274 All Rights Reserved

Summary

• The .NET interoperability services lets you interface managed and unmanaged code running under Windows

• You can call legacy COM components from within the managed .NET environment using a Runtime Callable Wrapper or RCW.

• This wrapper can be generated both by the TlbImp tool and also automatically by Visual Studio.

• Platform Invocation Services (PInvoke), makes unmanaged exported DLL functions available to managed client code.

Page 87: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 8

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 275 All Rights Reserved

Lab 8

Using COM Servers in C#

Introduction In this lab, you will use a COM server that is provided. This server is found in the Lab8 directory in the file Diceman.dll. A DiceMan object is used to roll an imaginary n-sided dice: Property: Sides Type: short represents the number of sides of the dice Method: Roll Returns: short returns the value of a "roll" Method: Reseed Returns: n/a resets the internal starting point of the random number generator Suggested Time: 30 minutes Root Directory: OIC\NetCs Directories: Labs\Lab8\DiceTest (do your work here) Chap08\DiceTest (answer) Files: Labs\Lab8\DiceMan.dll (COM server) Instructions 1. Before you build the application, you must register the DiceMan COM Server on

your machine using the Windows utility regsvr32.

ex: C:\ > regsvr32 diceman.dll

2. Create a C# Windows Forms Application and name it DiceTest.

3. Design a form that resembles the form on the following page:

Page 88: NET Framework Using C# - itcourseware.com€¦ · − Example programs for each chapter are in named subdirectories of chapter directories Chap01, Chap02, and so on. − The Labs

NetCs Chapter 8

Rev. 4.0 Copyright © 2010 Object Innovations Enterprises, LLC 276 All Rights Reserved

Type Name Text

Button cmdRoll Roll Label lblResult Roll Result: Textbox* txtResult <none> * read only Button cmdReseed Re-seed Label lblSides Sides: Textbox txtSides <none> Button cmdSetSides Set Sides

4. Use the Project | Add Reference menu to add a reference to the COM component "Diceman 1.0 Type Library". Visual Studio’s Intellisense will now recognize DiceMan as a valid type.

5. Declare an instance of a DiceMan object in the form. Use it as follows:

a. Initialize txtSides with the value of DiceMan's Sides property when the form is initialized.

b. Trap the click event on cmdSetSides; use the value of txtSides to set DiceMan's Sides property.

c. Trap the click event on cmdRoll; call DiceMan's Roll function and set txtResult the value it returns.

d. Trap the click event on cmdReseed; call DiceMan's Reseed subroutine.

Random number generators are usually pseudo-random. That is, they produce the same stream of numbers given the same starting point (or seed). If you run your application two times, you will see that you get the same sequence of results. The Reseed method seeds the generator with the current time. So if you press Reseed before the first Roll, you will notice that results are different on each run.

6. Build and run your program.