.NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide...

106
Object Innovations Course 4111 Student Guide Revision 4.0.1 .NET Framework Essentials Using C#

Transcript of .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide...

Page 1: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

Object Innovations Course 4111

Student Guide Revision 4.0.1

.NET Framework Essentials Using C#

Page 2: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

Rev. 4.0.1 Copyright ©2011 Object Innovations Enterprises, LLC ii All Rights Reserved

.NET Framework Essentials Using C# Rev. 4.0.1 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 ©2011 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 Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

Rev. 4.0.1 Copyright ©2011 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 Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

Rev. 4.0.1 Copyright ©2011 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 Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

Rev. 4.0.1 Copyright ©2011 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 Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

Rev. 4.0.1 Copyright ©2011 Object Innovations Enterprises, LLC vi All Rights Reserved

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

Chapter 4 Metadata and Reflection ............................................................................ 99 Metadata.......................................................................................................................... 101 Reflection........................................................................................................................ 102 Sample Reflection Program ............................................................................................ 103 System.Reflection.Assembly .......................................................................................... 106 System.Type.................................................................................................................... 107 System.Reflection.MethodInfo ....................................................................................... 109 Dynamic Invocation........................................................................................................ 110 Late Binding ................................................................................................................... 111 LateBinding Example ..................................................................................................... 112 Lab 4 ............................................................................................................................... 113

Page 7: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

Rev. 4.0.1 Copyright ©2011 Object Innovations Enterprises, LLC vii All Rights Reserved

Summary ......................................................................................................................... 114

Chapter 5 I/O and Serialization ................................................................................ 119 Input and Output in .NET ............................................................................................... 121 Directories....................................................................................................................... 122 Directory Example Program ........................................................................................... 123 Files and Streams ............................................................................................................ 126 “Read” Command ........................................................................................................... 128 Code for “Write” Command ........................................................................................... 129 Serialization .................................................................................................................... 130 Attributes ........................................................................................................................ 131 Serialization Example ..................................................................................................... 133 Lab 5 ............................................................................................................................... 136 Summary ......................................................................................................................... 137

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

Page 8: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

Rev. 4.0.1 Copyright ©2011 Object Innovations Enterprises, LLC viii All Rights Reserved

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

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

Page 9: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

Rev. 4.0.1 Copyright ©2011 Object Innovations Enterprises, LLC ix All Rights Reserved

Lab 7 ............................................................................................................................... 240 Summary ......................................................................................................................... 241

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

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

Page 10: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

Rev. 4.0.1 Copyright ©2011 Object Innovations Enterprises, LLC x All Rights Reserved

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

Appendix A Learning Resources .............................................................................. 353

Page 11: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 1

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 1 All Rights Reserved

Chapter 1

.NET Fundamentals

Page 12: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 1

Rev. 4.0.1 Copyright © 2011 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 Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 1

Rev. 4.0.1 Copyright © 2011 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 Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 1

Rev. 4.0.1 Copyright © 2011 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 Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 1

Rev. 4.0.1 Copyright © 2011 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 Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 1

Rev. 4.0.1 Copyright © 2011 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 Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 1

Rev. 4.0.1 Copyright © 2011 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 Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 1

Rev. 4.0.1 Copyright © 2011 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 Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 1

Rev. 4.0.1 Copyright © 2011 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 Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 1

Rev. 4.0.1 Copyright © 2011 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 Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 1

Rev. 4.0.1 Copyright © 2011 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 Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 1

Rev. 4.0.1 Copyright © 2011 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 Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 1

Rev. 4.0.1 Copyright © 2011 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 Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 1

Rev. 4.0.1 Copyright © 2011 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 Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 1

Rev. 4.0.1 Copyright © 2011 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 Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 1

Rev. 4.0.1 Copyright © 2011 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 Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 1

Rev. 4.0.1 Copyright © 2011 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 Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 1

Rev. 4.0.1 Copyright © 2011 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 Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 1

Rev. 4.0.1 Copyright © 2011 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 Prompt2, which can be started from All Programs | Microsoft Visual Studio 2010 | Visual Studio Tools | Visual Studio Command Prompt (2010).

2 With Windows 7 you may need to run the Command Prompt as Administrator in some cases.

Page 30: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 1

Rev. 4.0.1 Copyright © 2011 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 Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 1

Rev. 4.0.1 Copyright © 2011 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 Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 1

Rev. 4.0.1 Copyright © 2011 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 Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 1

Rev. 4.0.1 Copyright © 2011 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 Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 1

Rev. 4.0.1 Copyright © 2011 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 Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 1

Rev. 4.0.1 Copyright © 2011 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 Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 1

Rev. 4.0.1 Copyright © 2011 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 Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 1

Rev. 4.0.1 Copyright © 2011 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 Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 1

Rev. 4.0.1 Copyright © 2011 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 Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 2

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 29 All Rights Reserved

Chapter 2

Class Libraries

Page 40: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 2

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 30 All Rights Reserved

Class Libraries

Objectives

After completing this unit you will be able to:

• Describe the role of components in software development.

• Compare components in COM and .NET.

• Build .NET class libraries at the command line.

• Create class libraries using Visual Studio 2010.

• Use components in client programs by obtaining references to class libraries.

Page 41: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 2

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 31 All Rights Reserved

Objects and Components

• An object encapsulates data and behavior, and it facilitates reuse—at the source code level.

− A class library, such as Microsoft Foundation Classes (MFC) provides reusable code in the form of a hierarchy of classes.

− But you cannot use MFC classes in a Visual Basic 6 program.

• By contrast, a component is a binary piece of software that can be reused in many different programming languages.

− For example, you can use COM components and ActiveX controls (a particularly rich type of COM component, typically with a graphical user interface) in Visual Basic 6 programs.

− The component could be implemented in some other language, such as C++. The Visual Basic 6 programmer does not care.

• The basic concept of component is a black box piece of software that can be reused.

− By this loose definition, a DLL would be a component.

• Usually, somewhat more is meant, such as some kind of “object orientation.”

− Examples of such object-oriented components are COM objects, JavaBeans, and CORBA objects.

Page 42: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 2

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 32 All Rights Reserved

Limitation of COM Components

• COM lacks support for implementation inheritance.

− You cannot start with a base component and inherit its methods. (You can achieve similar reuse by other techniques, such as containment and aggregation, but such reuse is not as easy or convenient as inheritance.)

• Another drawback of COM components is the requirement that the component implement “plumbing” code that allows it be called in a black box fashion from another piece of software.

− Visual Basic 6 hid the plumbing code, but it was there, and VB6 programs could only use a subset of the capabilities of COM.

− In C++ you could fully utilize COM, but there was a lot of work to be done in implementing the plumbing code. Specialized libraries like the Active Template Library (ATL) could do a lot of the work for you, but that required you to learn yet another piece of technology, and it applied only to C++.

Page 43: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 2

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 33 All Rights Reserved

Components in .NET

• The .NET Framework provides an exceptionally attractive environment for creating and using software components.

• By simply setting an appropriate compiler switch or choosing a specific project type in Visual Studio, you can build a class library.

− A class library is the .NET version of a component and is a DLL that packages the code for a set of classes.

• There is no special plumbing code that must be provided.

• These class library DLLs can easily be used by other .NET programs, and you can mix .NET languages freely.

• Also, you can inherit from a class implemented in a class library.

− This inheritance mechanism extends across languages, since a class library is a binary component.

Page 44: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 2

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 34 All Rights Reserved

Class Libraries at the Command Line

• To create a .NET class library from the command line, compile using the switch /target:library.

− You can abbreviate the /target switch as simply /t.

csc /t:library Customer.cs

− This command creates the DLL Customer.dll.

• To use the class library from another program, you must obtain a reference to the class library.

− Compiling at the command line, you can use the /reference or /r switch.

csc /r:Customer.dll TestCustomer.cs

− This command creates the executable TestCustomer.exe.

• Run commands from the Visual Studio 2010 command-line prompt.

− Start it via All Programs | Microsoft Visual Studio 2010 | Visual Studio Tools | Visual Studio Command Prompt (2010).

• If you have Visual C# 2010 Express Edition, you can add the bin directory containing the SDK tools to your Path environment variable.

− You can edit the Path environment variable from the Advanced tab of the System applet in the Control Panel.

Page 45: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 2

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 35 All Rights Reserved

Component Example: Customer Management System

• We will illustrate how to work with components in .NET by componentizing a monolithic application.

• The application manages a list of customers.

− The Customers class manages a collection of customers, as defined by the CustomerListItem structure.

public struct CustomerListItem { public int CustomerId; public string FirstName; public string LastName; public string EmailAddress; }

• The Customers class implements the ICustomer interface.

public interface ICustomer { int RegisterCustomer(string firstName, string lastName, string emailAddress); void UnregisterCustomer(int id); ArrayList GetCustomer(int id); void ChangeEmailAddress(int id, string emailAddress); }

− The GetCustomer method returns a list of customers (all customers if input ID is –1).

Page 46: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 2

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 36 All Rights Reserved

Customer Management (Cont’d)

• The folder CustomerMonolithic contains a GUI version of a customer management system, with all code in one project.

− Examine the code, and then build and exercise the program.

− The list of customers is shown in the list box, and buttons are provided to register a new customer, unregister a customer, and change the email address of a customer.

Page 47: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 2

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 37 All Rights Reserved

Monolithic versus Component

• In this monolithic version of the program, the business logic (as specified by the ICustomer interface) and the user interface code are mixed together.

• A better structure is to isolate the business logic in a separate component.

− Create a DLL Customer.dll that contains the Customers class implementing the ICustomer interface.

• The .NET Framework then provides various mechanisms by which a client program can access this functionality, and there can be different kinds of clients:

− Windows GUI client

− Console application client

− Web client

− and so forth

Page 48: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 2

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 38 All Rights Reserved

Demo: Creating a Class Library

• We will create a class library Customer.dll from the C# source file Customer.cs.

− See CustomerLib in this chapter’s directory.

1. Examine the code file Customer.cs. Note that the code is within the namespace OI.Acme.

using System; using System.Collections; namespace OI.Acme { public struct CustomerListItem { public int CustomerId; public string FirstName; public string LastName; public string EmailAddress; } public interface ICustomer { int RegisterCustomer(string firstName, string lastName, string emailAddress); void UnregisterCustomer(int id); ArrayList GetCustomer(int id); void ChangeEmailAddress(int id, string emailAddress); } ...

Page 49: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 2

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 39 All Rights Reserved

Creating a Class Library (Cont’d)

2. Create the class library Customer.dll via the command:

csc /t:library Customer.cs 3. Examine the assembly Customer.dll that was created by using

the ILDASM tool. Notice that this assembly looks a little different from the ones we’ve created before (for example, there is no Main method).

Page 50: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 2

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 40 All Rights Reserved

Demo: A Console Client Program

• Create a console client program TestCustomer.exe from the C# source file TestCustomer.cs.

− See TestCustomer.

1. Examine the code file TestCustomer.cs. Notice the using statement to bring in the OI.Acme namespace.

using System; using System.Collections; using OI.Acme; class TestCustomer { ... 2. Copy Customer.dll from CustomerLib to TestCustomer.

3. Create the assembly TestCustomer.exe via the command:

csc /r:Customer.dll TestCustomer.cs

4. You can now run the test program, which exercises the Customers class by adding a new customer, changing the email address of a customer, and unregistering a customer.

Output:

1 Rocket Squirrel [email protected] 2 Bullwinkle Moose [email protected] New customer Christopher Robin id = 3 1 Rocket Squirrel stallone.com 3 Christopher Robin [email protected]

Page 51: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 2

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 41 All Rights Reserved

Class Libraries Using Visual Studio

• Visual Studio makes it very easy to work with .NET class libraries.

− You can create a class library by using the Class Library project type.

− You can use Solution Explorer to add references.

− It is all quite painless.

• There is one nuance involved when using Visual Studio that you need to be aware of.

− Visual Studio by default creates a root namespace based on the name of the project.

using System; using System.Collections.Generic; using System.Text; namespace ClassLibrary1 { public class Class1 { } }

− This applies to both class library and application projects.

Page 52: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 2

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 42 All Rights Reserved

Demo: Creating a Class Library

• We will use Visual Studio to create a class library containing the Customers class.

− Do your work in the Demos directory.

1. Bring up the New Project dialog from the menu File | New | Project. For Installed Templates choose Visual C# Windows from the left pane and Class Library from the right pane. Navigate to the desired Location, and type CustomerLib for the Name. Check “Create directory for solution.” That will facilitate adding a second project to the solution for a client test program. For the Solution Name type CustomerVs. Click OK.

Page 53: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 2

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 43 All Rights Reserved

Creating a Class Library (Cont’d)

2. Delete Class1.cs from the new project.

3. Copy the file Customer.cs from the CustomerMonolithic folder to the folder for this new project, and add this file to the project.

4. You should now be able to build the class library. The new DLL CustomerLib.dll will be created in Demos\CustomerVs\CustomerLib\bin\Debug.

5. Next, let’s create a test project, a second project in the solution. Right-click over the solution and choose Add | New Project from the context menu. Choose Windows Forms Application as the template, with name CustomerGui.

6. Delete all the files Form1.* from the new solution.

7. Copy all the files Form1.* from the CustomerMonolithic folder and add them to the CustomerGui project.

8. Try building the application. You will get a number of build errors. The biggest problem is that you are missing a reference to the class library.

Page 54: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 2

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 44 All Rights Reserved

References in Visual Studio

9. In Solution Explorer, right-click over the CustomerGui project and choose Add Reference from the context menu, bringing up the Add References dialog.

10. Click the Projects tab.

11. You will find the CustomerLib project highlighted.

12. Click OK.

Page 55: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 2

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 45 All Rights Reserved

References in Visual Studio (Cont’d)

13. If you try building, you will still get errors. You need to fix up the namespace in Form1.cs and Form1.Designer.cs

namespace CustomerGui { public partial class Form1 : Form { ... 14. Build. You should now get a clean compile.

• In a multiple-project solution, you should specify a startup project.

− Right-click over the desired project and choose Set As Startup Project from the context menu. In our case, make CustomerGui the startup project.

15. Run the application. The program should now behave identically to the CustomerMonolithic application.

Page 56: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 2

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 46 All Rights Reserved

References at Compile Time and Run Time

• The assembly CustomerLib.dll is used both at compile time and at runtime.

− At compile time the metadata in the assembly is used, and at runtime the code is called.

− When you build the application, Visual Studio will copy the DLL into the bin\Debug or the bin\Release folder, so it will reside in the proper place at runtime.

− Examine the folder CustomerGui\bin\Debug. You should now see both CustomerGui.exe and Customer.dll.

• In this case we are using private deployment in which all assemblies reside in the same directory.

• With .NET it is also possible to have shared deployment, using the Global Assembly Cache.

− We will discuss these issues in detail in the next chapter.

Page 57: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 2

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 47 All Rights Reserved

Project Dependencies

• When you have multiple projects in a solution, it becomes important to specify project dependencies.

− In our example, you need to build the class library before the Windows application.

• To set project dependencies, right-click over the solution and choose Project Dependencies from the context menu.

− When we specified a Project Reference, the dependency was set automatically for us.

Page 58: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 2

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 48 All Rights Reserved

Specifying Version Numbers

• It is easy to specify version numbers and other assembly information using Visual Studio.

− A generated project contains a file AssemblyInfo.cs in the Properties folder.

− Edit the [assembly] attributes.

... [assembly: AssemblyTitle("CustomerGui")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Object Innovations")] [assembly: AssemblyProduct("CustomerGui")] [assembly: AssemblyCopyright("Copyright © 2010")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] ... // Version information for an assembly consists of // the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]

− You can then specify the Assembly Version and the File Version, as well as other information about the assembly.

• You can view the Assembly Version of an assembly using ILDASM, and you can view the File Version of a file using Windows Explorer.

Page 59: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 2

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 49 All Rights Reserved

Lab 2

Implementing a Class Library

In this lab you will implement a class library SimpleMath.dll that performs elementary arithmetic operations. You will also create a GUI test program to exercise your class library.

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

Suggested time: 30 minutes

Page 60: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 2

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 50 All Rights Reserved

Summary

• A component is a binary piece of software that can be reused in many different programming languages.

• The .NET Framework makes it easy to create and use components, known in .NET as class libraries.

• You can build class libraries at the command line by using the /target compiler switch.

• You can build class libraries in Visual Studio by creating a class library project.

• To use a class library in a client program you must specify a reference to it.

Page 61: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 2

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 51 All Rights Reserved

Lab 2

Implementing a Class Library

Introduction In this lab you will implement a class library SimpleMath.dll that performs elementary arithmetic operations. You will also create a GUI test program to exercise your class library. Rather than create two projects in the same solution, in this exercise you will create two separate solutions. This structure is carried over into the next chapter on assemblies. Suggested Time: 30 minutes Root Directory: OIC\NetCs Directories: Labs\Lab2\SimpleMath (create your class library here) Labs\Lab2\TestMath (create your test program here) Chap02\SimpleMath\Step1 (class library answer) Chap02\TestMath (test program answer) Instructions 1. Use Visual Studio 2010 to create a class library project SimpleMath in the folder

Labs\Lab2. Clear the checkbox “Create directory for solution.”

2. Rename the file Class1.cs to SimpleMath.cs. Rename the class to Calc. Note that the wizard generated code places your class inside the namespace SimpleMath.

3. Implement static methods to add and subtract two integers.

4. Edit the AssemblyInfo.cs file in the Properties folder to set both the Assembly Version number and the File Version number to 1.1.0.0. The former will be shown in ILDASM, and the latter using Windows Explorer.

[assembly: AssemblyVersion("1.1.0.0")] [assembly: AssemblyFileVersion("1.1.0.0")] 5. Build your class library, and examine it in ILDASM.

6. Use Visual Studio to create a Windows Application project TestMath in the folder Labs\Lab2.

7. Create a GUI consisting of three text boxes and two buttons that can test your SimpleMath class library.

Page 62: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 2

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 52 All Rights Reserved

8. Copy the SimpleMath.dll to the TestMath directory. Add a reference to this assembly. Instead of using the Projects tab, use the Browse tab.

9. Examine the SimpleMath DLL in the Object Browser, which you can bring up from the View menu.

10. Notice that the class Calc is in the namespace SimpleMath. Provide an appropriate using statement in the file Form1.cs.

11. Implement handlers for the two buttons that will call the corresponding methods of the SimpleMath class library.

12. Build and test.

Page 63: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 7

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 201 All Rights Reserved

Chapter 7

.NET Security

Page 64: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 7

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 202 All Rights Reserved

.NET Security

Objectives

After completing this unit you will be able to:

• Describe the fundamental security issues of authorization and authentication.

• Discuss the influence of the Internet on .NET security.

• Outline the fundamental security concepts of .NET.

• Describe the use of evidence in code access security.

• Explain permissions and their use in both code access and role-based security.

• Use the simple sandboxing API to host assemblies with restricted permissions.

• Implement role-based security.

Page 65: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 7

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 203 All Rights Reserved

Fundamental Problem of Security

• In simplest terms, the basic problem of security can be expressed by the question:

− "Who is allowed to do what to whom?"

• An example is accessing files in an operating system.

− "Who" is a user.

− "What" is a file operation, such as Write.

− "Whom" is a particular file.

• There is a guard standing watch over the operation, called the Security Reference Monitor.

− The rules followed by the guard are spelled out in a Policy. In our file example, many operating systems have the concept of "access control list" (ACL) that can spell out in detail what users have what rights to a file resource.

Who WhatSecurity

ReferenceMonitor

Policy

Whom

e.g. User e.g. Write e.g. File

e.g. ACL

Page 66: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 7

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 204 All Rights Reserved

Authentication

• In order for the Security Reference Monitor to do its job, a fundamental question must be answered first: are the parties who they say they are?

• This is the issue of authentication.

• In the building example the security guard may require a photo ID, which can be used to establish that the person asking admission really is who he says he is and not some imposter.

• Issues of security are even more compelling in a distributed computing environment.

• Consider an online transaction over the Internet.

− Clearly the server wants to know who the client is before providing a service, such as permitting a piece of software that has been purchased to be downloaded. No pirates, please!

− And authentication can work both ways. The client may want to know the identity of the server. You don't want to type in your credit card number if you don't trust that the party at the other end is the party you think it is.

Page 67: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 7

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 205 All Rights Reserved

Authorization

• The job of the Security Reference Monitor is to apply the policy to find out if the request is legitimate and should be allowed.

• This is the issue of authorization.

• A non-computer example of the same issue is the role of a security guard in a building granting access to people coming in.

− Only authorized persons, according to some policy, should be admitted.

Page 68: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 7

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 206 All Rights Reserved

The Internet and .NET Security

• The security system in .NET is very extensive, involving many concepts and a large number of classes.

• A good way to approach understanding it is by looking at some of the problems it is intended to solve (or help solve).

• Foremost among these are the issues that arise in the Internet age, with code of various sorts being widely available over the Internet.

• No longer is the security question only one of securing resources against users.

− It is also vital to have a security system that addresses what code is allowed to do.

• A major part of the .NET Security system is Code Access Security or CAS.

Page 69: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 7

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 207 All Rights Reserved

Code Access Security

• Code can originate from many sources, not all of them trusted:

− Attached to email

− Contained in documents

− Downloaded over the Internet

• Unfortunately, we are all too familiar with the cost of malicious code such as viruses and worms.

• With code access security, code can be trusted to varying degrees, depending on where the code originates and on other aspects of the code's identity.

• Code access security provides a fine degree of granularity over what code is allowed to do based on the degree of trust you have of it.

• The code access security model was considerably simplified in .NET 4.0.

− There is no longer a concept of machine-wide code access security policy specified by an administrator.

− The configuration tool for specifying such a policy no longer ships with the .NET Framework.

Page 70: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 7

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 208 All Rights Reserved

Role-Based Security

• The other primary security model supported by .NET is role-based security, which was introduced with Microsoft Transaction Server (and continued in COM+) and represents a substantial simplification in how you can configure and program security.

• A role is a logical group of users who are authorized to access a component, interface or method.

• A role can map into a natural business rule about who is allowed access to what.

• In short, roles are a good abstraction for specifying security policy.

Who WhatSecurity

ReferenceMonitor

Policy

Whom

User Call Component

Role

Page 71: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 7

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 209 All Rights Reserved

.NET Security Concepts

• The .NET Framework provides a consistent model, so if you are familiar with code access security you can easily use role-based security, and vice versa.

− The common language runtime use permissions to enforce restrictions on managed code.

− With the proper compilers, managed code can be verified to be type-safe, providing the foundation for application isolation and the enforcing of security.

− Security policy is configured by administrators to specify rules that the common language runtime follows when it decides what it will allow code to do. (In .NET 4.0 such configured policy applies to role-based security and not code access security.)

− A principal represents a user’s identity and role. It is the foundation of role-based security in .NET.

− Authentication allows you to discover and verify the identity of a principal by examining the user's credentials. When you discover the identity of the principal, you can use .NET role-based security to determine whether to allow that principal to access your code.

− Authorization allows you to determine whether a principal is allowed to perform a requested action. It occurs after authentication and uses information about the principal's identity and roles to determine what the principal is allowed to do.

Page 72: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 7

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 210 All Rights Reserved

Permissions

• Permissions are objects that describe sets of operations that can be permitted or denied for securing specific resources, based on existing security policy.

− The .NET CLR uses a stack walking mechanism to check and determine if all calling stack frames have been granted a specified permission.

− A permission object contains specific permission information.

− If a permission reference is set to null, then it is treated in the same way as a permission object with the state PermissionState.None, meaning that it provides no permissions.

• Permission sets are collections that can contain many different types of permission objects.

− This is accommodated by the PermissionSet class, which allows a permission set to be managed as a group of permissions.

Page 73: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 7

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 211 All Rights Reserved

IPermission Interface

• The IPermission interface encapsulates the fundamental idea of permission. It supports the following public methods:

− Copy creates an identical copy of an existing permission object.

− Demand causes a SecurityException to be thrown if any callers higher on the call stack have not been granted the permission specified by the permission object. This method is used defensively to prevent other code from tricking the current code into doing inappropriate actions (luring attack).

− Intersect creates a permission object that contains the intersection (i.e. overlapping set) of permissions of two existing permission objects.

− IsSubsetOf determines whether or not a permission object contains a subset of the permissions contained in another specified permission object.

− Union creates a permission object that contains the union (i.e. combined set) of permissions of two existing permission objects.

Page 74: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 7

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 212 All Rights Reserved

IPermission Demand Method

• The Demand method checks that all callers of the current method have permission to access a specified resource in a specified way, and throws its exception if this check fails.

− The particular type of resource that is being protected depends on the specific type of IPermission interface-implementing derived class that is being used.

− For example, the FileIOPermission class protects disk files and the RegistryPermission class protects registry entries, and so on.

• Before the Demand can be used, the permission object must first be established, specifying the resource to be protected, and the type of access being considered.

− In the case of file IO permissions, a FileIOPermission object must be established that specifies the file to be protected, and the type of file access being considered, such as read, write, and append operations.

− This can be established using the appropriate constructor, and the Copy, Intersect, and Union methods may be used to tailor new objects from existing ones.

• The permissions of the code that calls the Demand method are not checked.

− The checking begins with the immediate caller on the call stack and continues on up the call stack.

− Demand succeeds only if no exception is raised.

Page 75: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 7

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 213 All Rights Reserved

IPermission Inheritance Hierarchy

• The IPermission interface has two derived implementation classes:

− PrincipalPermission allows security checks to be made against the current active principal object, which is the basic idea behind role-based security.

− CodeAccessPermission is the base class for different kinds of CAS permissions.

IPermission

PrincipalPermission

CodeAccessPermission

DBDataPermission

PrintingPermission

...FileIOPermission

...UrlIdentityPermission

ZoneIdentityPermission

Page 76: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 7

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 214 All Rights Reserved

Stack Walking

• A key concept of code access security is stack walking.

− The runtime security system walks the call stack, comparing the permission being demanded with the permission that has been granted.

− If any caller in the call stack does not have the demanded permission, access is refused and a security exception is thrown.

• Stack walking can prevent luring attacks.

− In a luring attack, less-trusted code calls highly trusted code and uses it to perform unauthorized actions.

• Walking the call stack at runtime affects performance, but is essential for robust security.

− In specific situations where you can determine it is safe, you can optimize performance by calling Assert, which prevents the stack walk proceeding up the stack frame.

• Note the terminology of the stack frame growing down, typically ending at mscorlib.

A

B

mscorlib

Page 77: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 7

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 215 All Rights Reserved

Assert

• The CodeAccessPermission class has several methods that are found in all of the derived permission classes that you will be working with.

• Assert allows the specified permission in the current method and methods further down the call stack, even if code in higher stack frames have denied the permission.

− This method works by stopping a stack walk from proceeding further up the call stack, preventing a potential SecurityException from being thrown.

− This method is only successful if the calling code passes the security checks required for granting the specified permission according to security policy.

− An assertion is in effect from the time that Assert is called until the method that called Assert returns, or the RevertAssert method is called on the current stack frame.

− Only one assert can be active on a given stack frame, and calling Assert more than once on the same stack frame will throw a SecurityException.

− This method should be used judiciously, since it liberalizes permission usage, and may introduce luring attack security risks.

Page 78: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 7

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 216 All Rights Reserved

Demand

• Demand is used to ensure that calling methods have the specified permission.

− It does this by performing a stack walk, checking the permissions of each method found higher on the call stack.

− This method throws a SecurityException if any of the calling methods do not have the specified permission.

− Demand is used as an upfront test for the specified permission before going ahead and performing an operation that requires that permission.

• Many .NET Framework classes make extensive use of the Demand method to ensure that they only perform permissible operations according to established security policy.

− For example, many FileStream methods create a FileIOPermission object for the appropriate path and operation and then call its Demand method to ensure that it has the necessary permission to carry on with the intended operation.

• You can also define your own permission classes, and call on the Demand method for implementing your own security protection mechanisms.

Page 79: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 7

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 217 All Rights Reserved

Other CAS Methods

• Several abstract methods must be implemented by derived classes to support set operations on permission objects:

− Copy

− Intersect

− Union

− IsSubsetOf

• FromXml is an abstract method that each derived class must implement to reconstruct a permission object from an XML representation.

• ToXml is an abstract method that each derived class must implement to create an XML representation of the specified permission object.

Page 80: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 7

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 218 All Rights Reserved

Security Policy Simplification

• Prior to .NET 4.0 system administrators could specify, at a fine degree of granularity, security policies for managed applications.

− Although the CAS policy provided by .NET was very powerful, it was also very complex and difficult to get right.

− Moreover, policies configured for one version of .NET did not move to a new version of .NET, requiring elaborate security configuration to be done with each update.

• CAS security policy did not apply at all to native applications.

• It is better to specify machine-wide security policy at the operating system level.

− An appropriate Windows solution is Software Restriction Policies (SRP), which applies to both managed and native applications.

• In .NET 4.0 machine-wide security policy is turned off by default.

− This means that non-hosted applications (ones started at the command line or through Windows Explorer) run as full trust.

− Hosted applications, for examples one run by Internet Explorer, are partially trusted and are confined to a sandbox.

Page 81: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 7

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 219 All Rights Reserved

Simple Sandboxing API

• The unit of program isolation in .NET is the AppDomain.

• A sandbox then is a particular AppDomain that has restrictions on the operations permitted to assemblies that are loaded into it.

• The simple sandboxing API is an overload of AppDomain.CreateDomain().

public static AppDomain CreateDomain( string friendlyName, Evidence securityInfo, AppDomainSetup info, PermissionSet grantSet, params StrongName[] fullTrustAssemblies )

− friendlyName is a string that can be used in a user interface for identifying the domain.

− securityInfo is Evidence to be associated with the new domain (typically not used in .NET 4.0).

− info is setup information for the domain, containing at least the ApplicationBase specifying a path to the directory where the partially trusted assemblies are stored.

− grantSet is the set of permissions granted to all assemblies that are loaded into the domain.

− fullTrustAssemblies is a list of strong names representing assemblies that are considered fully trusted in the new domain.

Page 82: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 7

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 220 All Rights Reserved

Sandbox Example

• The Simple Sandboxing API is illustrated in the example program SandboxHost.

• Two sample assemblies are provided in the folder Sandbox.

− HelloWorld does console output.

− FileDemo (from Chapter 5) does console I/0 and file I/O.

• To successfully run these programs in the sandbox you must provide suitable permissions by checking the corresponding check boxes.

Page 83: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 7

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 221 All Rights Reserved

Setting up Permissions

PermissionSet pset; private void SetPermissions() { pset = new PermissionSet(PermissionState.None); if (chkExecute.Checked) pset.AddPermission(new SecurityPermission( SecurityPermissionFlag.Execution)); if (chkUI.Checked) pset.AddPermission(new UIPermission( PermissionState.Unrestricted)); if (chkFileIO.Checked) pset.AddPermission(new FileIOPermission( PermissionState.Unrestricted)); }

Page 84: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 7

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 222 All Rights Reserved

Creating the Sandbox

SetPermissions(); AppDomainSetup ads = new AppDomainSetup(); // Identify the folder to use for the sandbox. ads.ApplicationBase = @"..\..\..\Sandbox"; // Create the sandboxed domain. AppDomain sandbox = AppDomain.CreateDomain( "Sandboxed Domain", null, ads, pset, null); sandbox.ExecuteAssemblyByName(cmbAssembly.Text);

Page 85: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 7

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 223 All Rights Reserved

Role-Based Security in .NET

• The second basic security system in .NET is user-based or role-based security.

• .NET makes authorization decisions based on the principal associated with the current thread.

• A principal has an associated identity, which may be based on a Windows account or a custom identity unrelated to a Windows account.

• A role is a named set of principals that have the same set of security privileges.

− A principal can be a member of one or more roles.

− Applications can use role membership to determine if a principal has the authority to perform a requested action.

• The .NET Framework uses PrincipalPermission objects for security checks in a manner similar to the use of permission objects in code access security.

Page 86: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 7

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 224 All Rights Reserved

Identity Objects

• An identity object encapsulates information about a user or other entity being validated.

• An identity object contains a name and an authentication type.

− The name can be a user’s name or the name of a Windows account.

− The authentication type may be a supported login protocol like Kerberos, or a custom value.

• .NET provides for a number of identity objects:

− WindowsIdentity objects when relying on Windows accounts.

− GenericIdentity objects that can support many custom logons.

− Custom identity objects that you define.

− There are other identity objects such as FormsIdentity and PassportIdentity.

• The IIdentity interface must be supported by all identity objects.

interface IIdentity { string AuthenticationType {get;} bool IsAuthenticated {get;} string Name {get;} }

Page 87: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 7

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 225 All Rights Reserved

Principal Objects

• A principal object represents the security context under which code is running.

• In role-based security, rights are granted based on the role associated with a principal object.

• The .NET Framework provides various principal objects:

− A WindowsPrincipal object is based on a Windows identity.

− A GenericPrincipal object is based on a generic identity.

− You can also define your own custom principal classes.

• The IPrincipal interface must be supported by all principal objects.

interface IPrincipal { IIdentity Identity {get;} bool IsInRole(string role); }

• Principal classes may also implement additional properties and methods that are necessary.

− For example, the WindowsPrincipal class implements additional functionality for mapping Windows group membership to roles.

Page 88: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 7

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 226 All Rights Reserved

Windows Principal Information

• The program PrincipalInfo that is provided as part of the SDK documentation illustrates the information stored in a Windows principal object.

// Get the current identity and put it into an // identity object. WindowsIdentity MyIdentity = WindowsIdentity.GetCurrent(); // Put the previous identity into a principal // object. WindowsPrincipal MyPrincipal = new WindowsPrincipal(MyIdentity); //Principal values. string Name = MyPrincipal.Identity.Name; string Type = MyPrincipal.Identity.AuthenticationType; string Auth = MyPrincipal.Identity.IsAuthenticated.ToString(); //Identity values. string IdentName = MyIdentity.Name; string IdentType = MyIdentity.AuthenticationType; string IdentIsAuth = MyIdentity.IsAuthenticated.ToString(); string ISAnon = MyIdentity.IsAnonymous.ToString(); string IsG = MyIdentity.IsGuest.ToString(); string IsSys = MyIdentity.IsSystem.ToString(); string Token = MyIdentity.Token.ToString();

Page 89: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 7

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 227 All Rights Reserved

Windows Principal Information (Cont’d)

• Here is the output from running the program.

− The output depends on the name of the machine and the account under which it is running.

Principal Values for current thread: Principal Name: BETAPRO\Administrator Principal Type: NTLM Principal IsAuthenticated: True Identity Values for current thread: Identity Name: BETAPRO\Administrator Identity Type: NTLM Identity IsAuthenticated: True Identity IsAnonymous: False Identity IsGuest: False Identity IsSystem: False Identity Token: 356

Page 90: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 7

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 228 All Rights Reserved

Custom Identity and Principal

• The Windows principal and identity are convenient on a Windows system, but in the case of the Internet you may have users that do not have a Windows account.

• The IIdentity and IPrincipal are very simple. Hence it is easy to provide your own implementation.

• The example program RoleDemo provides an illustration of a custom implementation of these two interfaces.

− You can exercise creating users and roles and then test for users in roles.

− A help command shows the options available.

Please add users first, then roles Enter command, quit to exit > help The following commands are available: adduser -- add a user auth -- test authentication login -- login a user addrole -- add a role inrole -- is user in role? users -- show users roles -- show roles protect -- call protected procedure quit -- exit the program >

Page 91: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 7

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 229 All Rights Reserved

BasicIdentity.cs

• The class BasicIdentity implements IIdentity. // BasicIdentity.cs using System.Security.Principal; public class BasicIdentity : IIdentity { string m_name; public BasicIdentity(string vName) { m_name = vName; } public string AuthenticationType { get { return "BASIC-1"; } } public bool IsAuthenticated { get { return true; } } public string Name { get { return m_name; } } }

Page 92: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 7

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 230 All Rights Reserved

BasicSecurity.cs

• The class BasicPrincipal implements IPrincipal, with the aid of another class, BasicSecurity.

using System; using System.Collections; using System.Security.Principal; using System.Threading; public class BasicPrincipal : IPrincipal { private BasicIdentity m_identity; private BasicSecurity m_bs; public BasicPrincipal(IIdentity id, BasicSecurity bs) { m_identity = (BasicIdentity) id; m_bs = bs; } public IIdentity Identity { get { return m_identity; } } public bool IsInRole(string role) { return m_bs.InRole(role, m_identity.Name); } } ...

Page 93: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 7

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 231 All Rights Reserved

BasicSecurity.cs (Cont’d)

• The class BasicSecurity maintains collections of users and roles, defined in the classes Users and Roles.

... public class BasicSecurity { private Users m_users; private Roles m_roles; public string CurrentUser; public BasicSecurity(Users usrs, Roles rls) { m_users = usrs; m_roles = rls; CurrentUser = null; } public Roles CurrentRoles { set { m_roles = value; } } ...

Page 94: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 7

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 232 All Rights Reserved

BasicSecurity.cs (Cont’d)

• The Login method creates an identity and a principal, and associates the principal with the thread.

... public bool Login(string usr, string pwd) { bool ok = m_users.AuthenticateUser(usr, pwd); if (ok) { CurrentUser = usr; // Create a basic identity BasicIdentity MyIdentity = new BasicIdentity(usr); // Create a basic principal BasicPrincipal MyPrincipal = new BasicPrincipal(MyIdentity, this); Thread.CurrentPrincipal = MyPrincipal; } return ok; } ...

• The InRole method is used by BasicPrincipal in its implementation of IsInRole.

... public bool InRole(string role, string usr) { return m_roles.InRole(role, usr); } public ArrayList GetRoles() { return m_roles.GetRoles(); }

Page 95: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 7

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 233 All Rights Reserved

Users.cs

• The class Users maintains a collection of users as an array list, where a user has a name and a password.

− For simplicity the password is not encrypted.

using System; using System.Collections; struct User { public string Name; public string Password; } public class Users { private ArrayList m_list; public Users() { m_list = new ArrayList(); } ...

Page 96: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 7

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 234 All Rights Reserved

Users.cs (Cont’d)

• The key method AuthenticateUser returns True if the name and password match an entry in the list of users.

... public void AddUser(string name, string pwd) { User usr; usr.Name = name; usr.Password = pwd; m_list.Add(usr); } public bool AuthenticateUser(string name, string pwd) { foreach (User usr in m_list) { if (usr.Name == name) return usr.Password == pwd; } return false; } public ArrayList GetUsers() { ArrayList list = new ArrayList(); foreach (User usr in m_list) { list.Add(usr.Name); } return list; } }

Page 97: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 7

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 235 All Rights Reserved

Roles.cs

• The class Role has a role name and a collection of user names.

using System.Collections; public class Role { public string RoleName; private ArrayList m_users; public Role(string rollName) { m_users = new ArrayList(); RoleName = rollName; } public void AddUserToRole(string name) { m_users.Add(name); } public bool IsInRole(string name) { foreach (string usr in m_users) { if (usr == name) return true; } return false; } public ArrayList GetUsers() { return m_users; } } ...

Page 98: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 7

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 236 All Rights Reserved

Roles.cs (Cont’d)

• The class Roles maintains a collection of roles. ... public class Roles { private ArrayList m_list; public Roles() { m_list = new ArrayList(); } public void AddRole(Role vRole) { m_list.Add(vRole); } public bool InRole(string roleName, string usr) { foreach (Role rl in m_list) { if (rl.RoleName == roleName) return rl.IsInRole(usr); } return false; } public ArrayList GetRoles() { return m_list; } }

Page 99: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 7

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 237 All Rights Reserved

RoleDemo.cs

• The test program in the file RoleDemo.cs exercises our basic security system.

− You can show users and roles, and also add users and roles (some starting data is provided).

− The “login” command does the basic authentication of a user via a password (shown in plaintext for simplicity).

− The “protect” command exercises the basic security check of whether the authenticated user is in the requested role, throwing an exception on failure.

− Exceptions are handled as part of the command loop processing.

• The transcript of a sample run on the following page shows the following

− Users and roles are listed. There is one role, CustomerAdmin.

− First Ellen, who is in the role, logs in. She gains access to the protected data.

− Then Amy, who is not in the role, logs in. A security exception is thrown when she tries to access the protected data.

Page 100: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 7

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 238 All Rights Reserved

Sample Run

> users Amy Bob Carol David Ellen > roles CustomerAdmin Ellen Bob Carol > login name: Ellen password: 55 Login successful > protect role: CustomerAdmin usr = Ellen You have access to the private data! > login name: Amy password: 11 Login successful > protect role: CustomerAdmin usr = Amy Exception: Request for principal permission failed. >

Page 101: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 7

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 239 All Rights Reserved

PrincipalPermission

• The .NET Framework has a special kind of permission class, PrincipalPermission, for use in role-based security.

− The underlying principles are the same as in working with code access security.

• There are two steps in using PrincipalPermission.

− Initialize a new PrincipalPermission object with the name of the identity and the name of the role.

− You request a permission by making a Demand method call. The system will throw a security exception if permission is not granted.

private static void protect(string usr, string roleName) { // Protected procedure // Create a PrincipalPermission object. Console.WriteLine("usr = {0}", usr); PrincipalPermission MyPermission = new PrincipalPermission(usr, roleName); // Demand this permission. MyPermission.Demand(); // Print secret data. Console.WriteLine( "You have access to the private data!"); }

Page 102: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 7

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 240 All Rights Reserved

Lab 7

A Security System for Acme

In this lab you will implement a simple security system for the Acme Customer Management system. There will be one role, CustomerAdmin. A login dialog will be used for login prior to displaying the main form. Any authenticated user may see the list of customers and may register a new customer and change the email. Only a CustomerAdmin may unregister a customer. (Note that the users of the system are employees of Acme, not customers.)

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

Suggested time: 45 minutes

Page 103: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 7

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 241 All Rights Reserved

Summary

• The fundamental issues of security are authorization and authentication.

• The Internet makes code, much of it untrusted, available from many sources, motivating the need for code access security in .NET.

• .NET uses the same security architecture based on permissions for both code access security and role-based security.

• The common language runtime uses permissions to enforce access to managed code. Permissions can be used in both code access security and role-based security.

• You can use the simple sandboxing API to host assemblies with restricted permissions.

• Role-based security supports authorization by making information about the current principal available to the current thread.

Page 104: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 7

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 242 All Rights Reserved

Lab 7

A Security System for Acme

Introduction In this lab you will implement a simple security system for the Acme Customer Management system. There will be one role, CustomerAdmin. A login dialog will be used for login prior to displaying the main form. Any authenticated user may see the list of customers and may register a new customer and change the email. Only a CustomerAdmin may unregister a customer. (Note that the users of the system are employees of Acme, not customers.) Suggested Time: 45 minutes Directories: Labs\Lab7\SecureCustomer (do your work here) Chap02\CustomerMonolithic (backup of starter code) Chap07\SecureCustomer (answer) Step 1. Create the Login Form In this first step you will add a login form to the application that will be brought up as a dialog prior to showing the main form. You will provide test code that will authenticate Amy as a valid user and nobody else. 1. Build and run the starter code, which is the same as the CustomerMonolithic

application from Chapter 2.

2. Add a new form LoginForm.cs with controls as shown.

3. Adjust the properties of the form to make it a modal dialog.

a. Set FormBorderStyle to FixedDialog.

Page 105: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 7

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 243 All Rights Reserved

b. Set ControlBox, MaximizeBox and MinimizeBox to False.

4. Adjust the properties of the controls.

a. Name of the edit controls should be txtName and txtPassword.

b. PasswordChar of txtPassword should be *.

c. Name of the buttons should be cmdLogin and cmdCancel.

d. DialogResult of the Cancel button should be Cancel.

5. Add a public member variable UserName of type string, initialized to be the empty string.

6. Add a handler for the Login button. As test code, check if the name is “Amy”. If yes, set the DialogResult to DialogResult.OK and UserName to “Amy”. Otherwise set the DialogResult to be DialogResult.Cancel.

7. In Form1.cs add code at the beginning of the handler of the Load event to do the following.

a. Instantiate a new LoginForm.

b. Call ShowDialog, getting back a status code.

c. If the status code is DialogBox.Cancel, print a login failure message and close the application.

d. Otherwise append the user name to the title of the form, and continue with the rest of the code.

8. Build and test.

Step 2. Perform Authentication Using the Basic Security System In the second step you will add code from the RoleDemo sample to incorporate the basic security system, along with the same users Amy, Bob, Carol, David and Ellen (with passwords 11, 22, 33, 44, 55). Bob, Carol and Ellen are all in the CustomerAdmin role. 1. Copy the file BasicIdentity.cs, BasicSecurity.cs, Roles.cs, and Users.cs from the

RoleDemo example to your working directory, and add these files to your project

2. In Form1.cs add declarations of the following variables:

private Users m_users; private Roles m_roles; private string CurrentUser = ""; public static BasicSecurity m_bs;

Page 106: .NET Framework Essentials Using C# · .NET Framework Essentials Using C# Rev. 4.0.1 Student Guide Information in this document is subject to change without notice. Companies, names

NetCs Chapter 7

Rev. 4.0.1 Copyright © 2011 Object Innovations Enterprises, LLC 244 All Rights Reserved

3. Add a private helper method InitializeSecurity that does the same initialization of the

security system as was done in the RoleDemo example.

4. Call this initialization method at the beginning of the handler of the Load event.

5. If the login was successful, assign CurrentUser to be the UserName acquired by the login dialog.

6. Modify the login code in LoginForm.cs to use the logic of the basic security system (as done in the RoleDemo example) in place of the stub code.

7. Build and test. You should now have a basic authentication system working. You should be able to login in Amy, Bob, Carol, etc. with their proper passwords and nobody else.

Step 3. Protect the Unregister Command In the last step you will add code from the RoleDemo sample to protect the Unregister command, so that only a user in the CustomerAdmin group is allowed access. 1. In Form1.cs add a using for System.Security.Permissions.

2. In the handler for the Unregister button add code to create a new PrincipalPermission object based on the current user and the CustomerAdmin role.

3. Inside a try block call Demand on the permission object.

4. In the catch handler display a message box showing the message in the exception, and then return.

5. Build and test. Your security system should now be fully operational!