50
What’s New in Visual Studio What’s New in Visual Studio 2005: 2005: Security & .NET Security & .NET Framework 2.0 Framework 2.0 Mike Pelton Mike Pelton [email protected] [email protected] Developer & Platform Group Developer & Platform Group Microsoft Ltd. Microsoft Ltd.

What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton [email protected] Developer & Platform Group Microsoft Ltd

  • View
    224

  • Download
    2

Embed Size (px)

Citation preview

Page 1: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

What’s New in Visual Studio 2005:What’s New in Visual Studio 2005:

Security & .NET Framework 2.0Security & .NET Framework 2.0Mike PeltonMike Pelton

[email protected]@microsoft.com

Developer & Platform GroupDeveloper & Platform Group

Microsoft Ltd.Microsoft Ltd.

Page 2: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

Where Are We Going?Where Are We Going?

SecuritySecurity

Securing stringsSecuring strings

Security ContextSecurity Context

Access ControlAccess Control

EncryptionEncryption

Encrypting XMLEncrypting XML

Framework & Language EnhancementsFramework & Language Enhancements

GenericsGenerics

IteratorsIterators

Edit and ContinueEdit and Continue

Console enhancementsConsole enhancements

Page 3: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

Securing StringsSecuring Strings

The Problem:The Problem:

Managed strings can lurk in your address space:Managed strings can lurk in your address space:

Can’t be erasedCan’t be erased

Old memory isn’t zero’dOld memory isn’t zero’d

Garbage Collection…Garbage Collection…

Doesn’t guarantee to overwriteDoesn’t guarantee to overwrite

May move them around in the managed heapMay move them around in the managed heap

It could be a long time till heap compaction!It could be a long time till heap compaction!

System.SecuritySystem.Security

Page 4: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

Enter SecureStringEnter SecureString

Stores Data using the Data Protection APIStores Data using the Data Protection API

Data is always encryptedData is always encrypted

Encryption keyEncryption key

Local Security Authority Subsystem (LSASS.exe)Local Security Authority Subsystem (LSASS.exe)

Data can be decryptedData can be decrypted

Interprocess communication via DPAPIInterprocess communication via DPAPI

Marshalled by unmanaged codeMarshalled by unmanaged code

Can be zero’d!Can be zero’d!

System.SecuritySystem.Security

Page 5: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

SecureStringSecureString

DemoDemo

With thanks to Kit George and GotDotNet

Page 6: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

Impersonation Across ThreadsImpersonation Across ThreadsSecurityContextSecurityContext

The Problem:The Problem:It doesn’t happen today!It doesn’t happen today!

SecurityContext carries security context from one thread SecurityContext carries security context from one thread to another, automaticallyto another, automatically

Deals with managed calls…Deals with managed calls…

Thread.StartThread.Start

Worker thread via asynchronous delegateWorker thread via asynchronous delegate

QueueUserWorkItemQueueUserWorkItem

……but not unmanagedbut not unmanaged

Win32 CreateTheadWin32 CreateThead

Includes Code Access Security markersIncludes Code Access Security markers

E.g. Assert, PermitOnlyE.g. Assert, PermitOnly

System.SecuritySystem.Security

Page 7: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

Carrying Security ContextCarrying Security ContextBetween ThreadsBetween Threads

DemoDemo

Page 8: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

Security Identifiers (SID’s)Security Identifiers (SID’s)

Uniquely identify user and group accountsUniquely identify user and group accounts

Conceptually similar to a GUIDConceptually similar to a GUID

Unique in space and timeUnique in space and time

Machine ID + an increasing counterMachine ID + an increasing counter

But very differentBut very different

Predictable structurePredictable structure

““S” S”

Binary format revisionBinary format revision

48-bit Identifier authority (typically 5!)48-bit Identifier authority (typically 5!)

32-bit Sub-authorities32-bit Sub-authorities

E.g. BUILTIN domainE.g. BUILTIN domain

S-1-5-32-547 = “Power Users”S-1-5-32-547 = “Power Users”

Variable Length - challenging to programVariable Length - challenging to program

Page 9: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

Security IdentifiersSecurity IdentifiersProviding broad support for Windows security Providing broad support for Windows security programming interfaceprogramming interface

Concrete classes:Concrete classes:SecurityIdentifierSecurityIdentifier

……the machine readable SIDthe machine readable SID

NTAccountNTAccount

……the human readable equivalentthe human readable equivalent

Abstract class:Abstract class:IdentityReferenceIdentityReference

Binds the two togetherBinds the two together

New enumeration – WellKnownSidTypeNew enumeration – WellKnownSidTypeAvoids hard-coding “Administrators”Avoids hard-coding “Administrators”

System.Security.PrincipalSystem.Security.Principal

Page 10: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

Security IdentifiersSecurity Identifiers

DemoDemo

Page 11: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

Access ControlAccess ControlA very common requirementA very common requirement

Settings are manipulated via the Windows SDKSettings are manipulated via the Windows SDKAccess Control Entries, Lists, Security Descriptors…Access Control Entries, Lists, Security Descriptors…

Not the easiest dev taskNot the easiest dev taskDiscretionary Access Control List issue:Discretionary Access Control List issue:

Set NULL – everyone gets accessSet NULL – everyone gets access

Set empty – no-one gets accessSet empty – no-one gets access

Programming in .NET 1.1 required the use of platform Programming in .NET 1.1 required the use of platform invocationinvocation

Huge step forward for .NET 2.0Huge step forward for .NET 2.0System.Security.AccessControl namespaceSystem.Security.AccessControl namespace

Page 12: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

Access to an Existing FileAccess to an Existing File

See Mark Pustilnik’s MSDN Article

// Start by opening a fileusing (FileStream file = new FileStream (@ "M :\tem p\sam ple.txt", FileM ode.O pen, FileAccess.ReadW rite)){

// Retrieve the file's security settingsFileSecurity security = file.GetAccessControl();

// Create a new rule granting Alice read accessFileSystem AccessRule rule = new FileSystem AccessRule(

new NTAccount(@ "FABRIKAM \Alice"), FileSystem Rights.Read,AccessControlType.Allow );

// Add the rule to the existing rulessecurity.AddAccessRule(rule);

// Persist the changesfile.SetAccessControl(security);

}

Page 13: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

The HierarchyThe Hierarchy

Access rules are explicit or inheritedAccess rules are explicit or inherited

Explicit rules are added to an object… explicitlyExplicit rules are added to an object… explicitly

Inherited rules come from a parent containerInherited rules come from a parent container

Explicit rules for a container:Explicit rules for a container:

Two sets of flagsTwo sets of flags

InheritanceInheritance

Container inherit (i.e. apply to child containers)Container inherit (i.e. apply to child containers)

Object inherit (i.e. apply to leaf objects)Object inherit (i.e. apply to leaf objects)

PropagationPropagation

Inherit only (i.e. just the children, not the object)Inherit only (i.e. just the children, not the object)

No-propagate inherit (i.e. children but not grandchildren!)No-propagate inherit (i.e. children but not grandchildren!)

Page 14: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

System Access Control ListsSystem Access Control ListsSo much for DACL’s – what about SACL’s?So much for DACL’s – what about SACL’s?

These control what auditing the system will These control what auditing the system will perform on an objectperform on an object

Audits can only be generated by the Local Audits can only be generated by the Local Security AuthoritySecurity Authority

The only object allowed to write entries into the The only object allowed to write entries into the security event logsecurity event log

Audits are for use in computer forensicsAudits are for use in computer forensics

Who did what when?Who did what when?

Try asking for privilege to set them Try asking for privilege to set them

Page 15: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

Same Familiar Programming ModelSame Familiar Programming Model

// Start by opening a fileusing (FileStream file = new FileStream (@ "M :\tem p\sam ple.txt", FileM ode.O pen, FileAccess.ReadW rite)){

// Retrieve the file's security settingsFileSecurity security = file.GetAccessControl

(AccessControlSections.Audit);// Create a new rule to generate audits any tim e that a full-tim e// em ployee is denied w rite access to the fileFileSystem AuditRule rule = new FileSystem AuditRule(

new NTAccount(@ "FABRIKAM \Full_Tim e_Em ployees"),FileSystem Rights.W rite, AuditFlags.Failure);

// Add the rule to the existing rulessecurity.AddAuditRule(rule);

// Persist the changesfile.SetAccessControl(security);

}

Page 16: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

Persisting Security SettingsPersisting Security SettingsSecurity Descriptor Definition LanguageSecurity Descriptor Definition Language

Copying settings between objectsCopying settings between objects

Persisting to XMLPersisting to XML

Binary and textual formsBinary and textual forms

““Quasi Human readable”Quasi Human readable”

D:P(A;;GA;;;SY)(A;;GRGWGX;;;BA)(A;;GR;;;WD)(A;;GR;;;RC)D:P(A;;GA;;;SY)(A;;GRGWGX;;;BA)(A;;GR;;;WD)(A;;GR;;;RC)

// Retrieve ow ner and DACL portions as SDDLstring sddl = security.GetSecurityDescriptorSddlForm (

AccessControlSections.O w ner | AccessControlSections.Access);

Page 17: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

CryptographyCryptographyHash FunctionsHash Functions

One-way hash functions exhibit two properties:One-way hash functions exhibit two properties:

They’re one way:They’re one way:

Easy to take a message and compute the hash Easy to take a message and compute the hash valuevalue

Impossible to take a hash value and recreate the Impossible to take a hash value and recreate the original message. original message.

i.e. can't be done in any “reasonable” amount of timei.e. can't be done in any “reasonable” amount of time

They’re collision freeThey’re collision free

Impossible to find two messages that hash to the Impossible to find two messages that hash to the same hash value same hash value

Page 18: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

CryptographyCryptography“SHA-1 is Broken” - “SHA-1 is Broken” - Feb 28Feb 28thth 2005 2005

Three Chinese cryptographers have shown that SHA-1 isn’t collision-free:Three Chinese cryptographers have shown that SHA-1 isn’t collision-free:

With SHA-1 every message hashes down to a 160-bit numberWith SHA-1 every message hashes down to a 160-bit number

An infinite number of messages hash to each possible value, so there’s An infinite number of messages hash to each possible value, so there’s an infinite number of possible collisionsan infinite number of possible collisions

The number of possible hashes is huge - the odds of finding a collision The number of possible hashes is huge - the odds of finding a collision by chance is negligibly small (one in 2by chance is negligibly small (one in 28080))

Hash 2Hash 28080 random messages, and one pair will hash to the same value random messages, and one pair will hash to the same value

"Breaking" a hash function means being able to find collisions faster "Breaking" a hash function means being able to find collisions faster than the brute force approachthan the brute force approach

The Chinese team can find collisions in SHA-1 in 2The Chinese team can find collisions in SHA-1 in 26969 calculations - calculations - 2,000 times faster than brute force.2,000 times faster than brute force.

On the far edge of feasibility with current technologyOn the far edge of feasibility with current technology

Don’t panic!! There are alternative algorithms!Don’t panic!! There are alternative algorithms!

SHA-224, SHA-256, SHA-384, and SHA-512 SHA-224, SHA-256, SHA-384, and SHA-512

Page 19: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

PrefixesPrefixes

YottaYotta YY 10102424

ZettaZetta ZZ 10102121

ExaExa EE 10101818

PetaPeta PP 10101515

TeraTera TT 10101212

GigaGiga GG 101099

MegaMega MM 101066

KiloKilo kk 101033

Page 20: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

CryptographyCryptographyNew classes deriving from HMACNew classes deriving from HMAC

System.Security.Cryptography.HMAC System.Security.Cryptography.HMAC

““Keyed-hash message authentication code”Keyed-hash message authentication code”

Covers many Secure Hash Algorithm variantsCovers many Secure Hash Algorithm variants

Data Protection API is a first class citizenData Protection API is a first class citizen

ProtectedData & ProtectedMemoryProtectedData & ProtectedMemory

More help with “salting and stretching” passwordsMore help with “salting and stretching” passwords

Public Key Cryptography Standards #5Public Key Cryptography Standards #5

New Rfc2898DeriveBytes functionNew Rfc2898DeriveBytes function

Password-based key derivation functionality Password-based key derivation functionality

System.Security.CryptographySystem.Security.Cryptography

Page 21: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

““Stretching” PasswordsStretching” PasswordsPublic Key Cryptography Standards #5 Password-Based Key Derivation Function 2Public Key Cryptography Standards #5 Password-Based Key Derivation Function 2

Take the master password and a salt valueTake the master password and a salt value

Use that as the seed to a cryptographic random number Use that as the seed to a cryptographic random number generatorgenerator

E.g SHA-256E.g SHA-256

Repeat a few times (say 2Repeat a few times (say 21818!)!)

Why?Why?

94 characters, 12 letter password = 9494 characters, 12 letter password = 9412 12 optionsoptions

Each “guess” now requires 2Each “guess” now requires 21818 extra steps extra steps

The password is effectively stretched by 18 bitsThe password is effectively stretched by 18 bits

94941212 * 2 * 21818 is roughly 2 is roughly 29797

Page 22: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

Password MinderPassword Minder

Avoids using IE’s password storeAvoids using IE’s password store

Requires one strong passwordRequires one strong password

Automatically creates and remembers passwords for Automatically creates and remembers passwords for each site you register ateach site you register at

Generated passwords are long, unique, and randomGenerated passwords are long, unique, and random

Avoids deriving all the passwords from one master Avoids deriving all the passwords from one master stringstring

N.B. Full credit is due to Keith Brown’s MSDN Column!

Page 23: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

Password MinderPassword Minder

DemoDemo

With thanks to Keith Brown & his MSDN Column

Page 24: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

Encrypting XMLEncrypting XMLMSDN ArticleMSDN Article

““Exchange Data More Securely with XML Signatures Exchange Data More Securely with XML Signatures and Encryption”and Encryption”

Mike Downen, Shawn FarkasMike Downen, Shawn Farkas

W3C Standard “XML Encryption”W3C Standard “XML Encryption”

New EncryptedXML classNew EncryptedXML class

FlexibleFlexible

Different XML nodes can have different keysDifferent XML nodes can have different keys

““Super Encryption”Super Encryption”

The encrypted results can be encryptedThe encrypted results can be encrypted

System.Security.Cryptography.XMLSystem.Security.Cryptography.XML

Page 25: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

EncryptedData ClassEncryptedData ClassEncryptionMethodEncryptionMethod

Which algorithm was usedWhich algorithm was used

Specified by a URISpecified by a URI

Can be used for data or keys (see over)Can be used for data or keys (see over)

KeyInfoKeyInfoWhat key should I use to decrypt?What key should I use to decrypt?

Referenced by:Referenced by:NameName

An EncryptedData instanceAn EncryptedData instance

CipherData/CipherReferenceCipherData/CipherReferenceEither the encrypted data, orEither the encrypted data, or

A pointer to itA pointer to itIsn’t that dangerous?Isn’t that dangerous?

Page 26: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

Encrypting XMLEncrypting XML

DemoDemo

With thanks to Mike Downen & Shawn Farkas’ MSDNMike Downen & Shawn Farkas’ MSDN article

Page 27: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

Encrypting Config FilesEncrypting Config Files

Encode all or part of web.config easilyEncode all or part of web.config easily

Decryption is behind-the-scenesDecryption is behind-the-scenes

Two algorithms: Data Protection and RSATwo algorithms: Data Protection and RSA

For web farms:For web farms:

Use the RSA provider that relies on a CAPI container Use the RSA provider that relies on a CAPI container

DPAPI is machine-specificDPAPI is machine-specific

Allows the encryption key to be synchronised across Allows the encryption key to be synchronised across the entire farm – creates the same config file.the entire farm – creates the same config file.

System.WebSystem.Web

Page 28: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

Encrypting Sections of Web.ConfigEncrypting Sections of Web.Config

DemoDemo

Page 29: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

Securing Web.Config Securing Web.Config void ButtonEncryptClick(object sender, void ButtonEncryptClick(object sender, EventArgsEventArgs e) e)

{{

ConfigurationConfiguration config = config = WebWebConfigurationConfiguration.GetWebConfiguration(Request.ApplicationPath);.GetWebConfiguration(Request.ApplicationPath);

ConfigurationSectionConfigurationSection section = config.Sections[ section = config.Sections["connectionStrings""connectionStrings"];];

// Encryption// Encryption

section.ProtectSection(section.ProtectSection("DataProtectionConfigurationProvider""DataProtectionConfigurationProvider"););

config.Update();config.Update();

}}

void ButtonDecryptClick(object sender, void ButtonDecryptClick(object sender, EventArgsEventArgs e) e)

{{

ConfigurationConfiguration config = config = WebWebConfigurationConfiguration.GetWebConfiguration(Request.ApplicationPath);.GetWebConfiguration(Request.ApplicationPath);

ConfigurationSectionConfigurationSection section = config.Sections[ section = config.Sections["connectionStrings""connectionStrings"];];

// Decryption// Decryption

section.UnProtectSection();section.UnProtectSection();

config.Update();config.Update();

}}

Page 30: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

Security ReferencesSecurity References

Practical CryptographyPractical Cryptography

Niels Ferguson & Bruce SchneierNiels Ferguson & Bruce Schneier

Publisher:Publisher: John Wiley & Sons Inc John Wiley & Sons Inc

ISBN:ISBN: 0471223573 0471223573

The .NET Developer's Guide toThe .NET Developer's Guide to

Windows SecurityWindows Security

Keith BrownKeith Brown

• Publisher:Publisher: Addison WesleyAddison Wesley

• ISBN:ISBN: 03212283590321228359

Page 31: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

What’s New in Visual Studio 2005:What’s New in Visual Studio 2005:Framework & Language ChangesFramework & Language Changes

Page 32: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

An Introduction to GenericsAn Introduction to Generics

DemoDemo

Page 33: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

public class Listpublic class List{{ private object[] elements;private object[] elements; private int count;private int count;

public void Add(object element) {public void Add(object element) { if (count == elements.Length) Resize(count * 2);if (count == elements.Length) Resize(count * 2); elements[count++] = element;elements[count++] = element; }}

public object this[int index] {public object this[int index] { get { return elements[index]; }get { return elements[index]; } set { elements[index] = value; }set { elements[index] = value; } }}

public int Count {public int Count { get { return count; }get { return count; } }}}}

GenericsGenericspublic class Listpublic class List<<TT>>{{ private private TT[] elements;[] elements; private int count;private int count;

public void Add(public void Add(TT element) { element) { if (count == elements.Length) Resize(count * 2);if (count == elements.Length) Resize(count * 2); elements[count++] = element;elements[count++] = element; }}

public public TT this[int index] { this[int index] { get { return elements[index]; }get { return elements[index]; } set { elements[index] = value; }set { elements[index] = value; } }}

public int Count {public int Count { get { return count; }get { return count; } }}}}

List intList = new List();List intList = new List();

intList.Add(1);intList.Add(1);intList.Add(2);intList.Add(2);intList.Add("Three");intList.Add("Three");

int i = (int)intList[0];int i = (int)intList[0];

List intList = new List();List intList = new List();

intList.Add(1);intList.Add(1); // Argument is boxed // Argument is boxedintList.Add(2);intList.Add(2); // Argument is boxed // Argument is boxedintList.Add("Three");intList.Add("Three"); // Should be an error // Should be an error

int i = (int)intList[0]; // Cast requiredint i = (int)intList[0]; // Cast required

ListList<<intint>> intList = new List intList = new List<<intint>>();();

intList.Add(1);intList.Add(1); // No boxing // No boxingintList.Add(2);intList.Add(2); // No boxing // No boxingintList.Add("Three");intList.Add("Three"); // Compile-time error // Compile-time error

int i = intList[0];int i = intList[0]; // No cast required // No cast required

Page 34: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

Public Class ListPublic Class List Private elements() As ObjectPrivate elements() As Object Private mCount As IntegerPrivate mCount As Integer

Public Sub Add(element As Object) Public Sub Add(element As Object) If (mCount = elements.Length) Then _If (mCount = elements.Length) Then _ Resize(mCount * 2)Resize(mCount * 2) mCount += 1mCount += 1 elements(mCount) = elementelements(mCount) = element End SubEnd Sub

Default Public Property i(index As Integer) As ObjectDefault Public Property i(index As Integer) As Object Get Get Return elements(index) Return elements(index) End GetEnd Get Set Set elements(index) = value elements(index) = value End SetEnd Set End PropertyEnd Property

Public Property Count() As IntegerPublic Property Count() As Integer Get : Return mCount : End GetGet : Return mCount : End Get End PropertyEnd PropertyEnd ClassEnd Class

List intList = new List()List intList = new List()

intList.Add(1) intList.Add(1) ‘ Argument is boxed‘ Argument is boxedintList.Add(2) intList.Add(2) ‘ Argument is boxed‘ Argument is boxedintList.Add("Three") intList.Add("Three") ‘ Should be an error‘ Should be an error

int i = CInt(intList(0)) int i = CInt(intList(0)) ‘ Cast required‘ Cast required

GenericsGenericsPublic Class ListPublic Class List(Of ItemType)(Of ItemType) Private elements() As Private elements() As ItemTypeItemType Private count As IntegerPrivate count As Integer

Public Sub Add(element As Public Sub Add(element As ItemTypeItemType) ) If (count = elements.Length) Then _If (count = elements.Length) Then _ Resize(count * 2)Resize(count * 2) count += 1count += 1 elements(count) = elementelements(count) = element End SubEnd Sub

Public Property default(index As Integer) As Public Property default(index As Integer) As ItemTypeItemType Get : Return elements(index) : End GetGet : Return elements(index) : End Get Set : elements(index) = value : End SetSet : elements(index) = value : End Set End PropertyEnd Property

Public Property Count As IntegerPublic Property Count As Integer Get : Return count : End GetGet : Return count : End Get End PropertyEnd PropertyEnd ClassEnd Class

Dim intList As New ListDim intList As New List

intList.Add(1)intList.Add(1)intList.Add(2)intList.Add(2)intList.Add("Three")intList.Add("Three")

Dim i As Integer = intList(0)Dim i As Integer = intList(0)

Dim intList As New ListDim intList As New List(Of Integer)(Of Integer)

intList.Add(1) ‘ No boxingintList.Add(1) ‘ No boxingintList.Add(2) ‘ No boxingintList.Add(2) ‘ No boxingintList.Add("Three") ‘ Compile-time errorintList.Add("Three") ‘ Compile-time error

int i = intList(0) ‘ No cast requiredint i = intList(0) ‘ No cast required

Page 35: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

GenericsGenerics

Why generics?Why generics?

Type checking, no boxing, no downcastsType checking, no boxing, no downcasts

Reduced code bloat (typed collections)Reduced code bloat (typed collections)

How are C# generics implemented?How are C# generics implemented?

Instantiated at run-time, not compile-timeInstantiated at run-time, not compile-time

Checked at declaration, not instantiationChecked at declaration, not instantiation

Work for both reference and value typesWork for both reference and value types

Complete run-time type informationComplete run-time type information

Page 36: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

GenericsGenerics

Type parameters can be applied toType parameters can be applied to

Class, struct, interface, delegate typesClass, struct, interface, delegate types

class Dictionary<K,V> {...}class Dictionary<K,V> {...}

struct HashBucket<K,V> {...}struct HashBucket<K,V> {...}

interface IComparer<T> {...}interface IComparer<T> {...}

delegate R Function<A,R>(A arg);delegate R Function<A,R>(A arg);

Dictionary<string,Customer> customerLookupTable;Dictionary<string,Customer> customerLookupTable;

Dictionary<string,List<Order>> orderLookupTable;Dictionary<string,List<Order>> orderLookupTable;

Dictionary<string,int> wordCount;Dictionary<string,int> wordCount;

Page 37: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

GenericsGenerics

Type parameters can be applied toType parameters can be applied to

Class, struct, interface, delegate typesClass, struct, interface, delegate types

MethodsMethodsclass Utilsclass Utils{{ public static T[] CreateArray<T>(int size) {public static T[] CreateArray<T>(int size) { return new T[size];return new T[size]; }}

public static void SortArray<T>(T[] array) {public static void SortArray<T>(T[] array) { ...... }}}} string[] names = Utils.CreateArray<string>(10);string[] names = Utils.CreateArray<string>(10);

names[0] = "Jones";names[0] = "Jones";......Utils.SortArray(names);Utils.SortArray(names);

Page 38: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

GenericsGenerics

Type parameters can be applied toType parameters can be applied to

Class, struct, interface, delegate typesClass, struct, interface, delegate types

MethodsMethods

Type parameters can have constraintsType parameters can have constraintsclass Dictionary<K,V>class Dictionary<K,V>{{ public void Add(K key, V value) {public void Add(K key, V value) { ...... if (if (((IComparable)key).CompareTo(x) == 0((IComparable)key).CompareTo(x) == 0) {...}) {...} ...... }}}}

class Dictionary<K,V> class Dictionary<K,V> where K: IComparablewhere K: IComparable{{ public void Add(K key, V value) {public void Add(K key, V value) { ...... if (if (key.CompareTo(x) == 0key.CompareTo(x) == 0) {...}) {...} ...... }}}}

class Dictionary<K,V>: IDictionary<K,V>class Dictionary<K,V>: IDictionary<K,V> where K: IComparable<K>where K: IComparable<K> where V: IKeyProvider<K>, IPersistable, new()where V: IKeyProvider<K>, IPersistable, new(){{ public void Add(K key, V value) { public void Add(K key, V value) { ...... }}}}

Page 39: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

GenericsGenerics

Zero or one primary constraintZero or one primary constraint

Actual class, Actual class, classclass, or , or structstruct

Zero or more secondary constraintsZero or more secondary constraints

Interface or type parameterInterface or type parameter

Zero or one constructor constraintZero or one constructor constraintnew()new()

class Link<T> where T: class {...}class Link<T> where T: class {...}

class Nullable<T> where T: struct {...}class Nullable<T> where T: struct {...}

class Relation<T,U> where T: class where U: T {...}class Relation<T,U> where T: class where U: T {...}

Page 40: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

GenericsGenerics

Collection classesCollection classes

Collection interfacesCollection interfaces

Collection base classesCollection base classes

Utility classesUtility classes

ReflectionReflection

List<T>List<T>Dictionary<K,V>Dictionary<K,V>SortedDictionary<K,V>SortedDictionary<K,V>Stack<T>Stack<T>Queue<T>Queue<T>

IList<T>IList<T>IDictionary<K,V>IDictionary<K,V>ICollection<T>ICollection<T>IEnumerable<T>IEnumerable<T>IEnumerator<T>IEnumerator<T>IComparable<T>IComparable<T>IComparer<T>IComparer<T>

Collection<T>Collection<T>KeyedCollection<T>KeyedCollection<T>ReadOnlyCollection<T>ReadOnlyCollection<T>

Nullable<T>Nullable<T>EventHandler<T>EventHandler<T>Comparer<T>Comparer<T>

Page 41: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

Generics PerformanceGenerics Performance

DemoDemo

With thanks to Kit George and GotDotNet

Page 42: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

IteratorsIterators

foreach relies on “enumerator pattern”foreach relies on “enumerator pattern”

GetEnumerator() methodGetEnumerator() method

foreach makes enumerating easyforeach makes enumerating easy

But enumerators are hard to write!But enumerators are hard to write!

foreach (object obj in list) {foreach (object obj in list) { DoSomething(obj);DoSomething(obj);}}

Enumerator e = list.GetEnumerator();Enumerator e = list.GetEnumerator();while (e.MoveNext()) {while (e.MoveNext()) { object obj = e.Current;object obj = e.Current; DoSomething(obj);DoSomething(obj);}}

Page 43: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

IteratorsIterators

public class Listpublic class List{{ internal object[] elements;internal object[] elements; internal int count;internal int count;

public IEnumerator GetEnumerator() {public IEnumerator GetEnumerator() { return new ListEnumerator(this); return new ListEnumerator(this); }}}}

public class ListEnumerator : IEnumeratorpublic class ListEnumerator : IEnumerator{{ List list;List list; int index;int index;

internal ListEnumerator(List list) {internal ListEnumerator(List list) { this.list = list;this.list = list; index = -1;index = -1; }}

public bool MoveNext() {public bool MoveNext() { int i = index + 1;int i = index + 1; if (i >= list.count) return false;if (i >= list.count) return false; index = i;index = i; return true;return true; }}

public object Current {public object Current { get { return list.elements[index]; }get { return list.elements[index]; } }}}}

public class Listpublic class List{{ internal object[] elements;internal object[] elements; internal int count;internal int count;

public IEnumerator GetEnumerator() {public IEnumerator GetEnumerator() { for (int i = 0; i < count; i++) { for (int i = 0; i < count; i++) { yield return elements[i];yield return elements[i]; }} }}}}

Page 44: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

public class Testpublic class Test{{ public IEnumerator GetEnumerator() {public IEnumerator GetEnumerator() { yield return "Hello";yield return "Hello"; yield return "World"; yield return "World"; }}}}

IteratorsIterators

Method that incrementally computes and returns Method that incrementally computes and returns a sequence of valuesa sequence of values

yield return and yield breakyield return and yield break

Must return IEnumerator or IEnumerableMust return IEnumerator or IEnumerable

public IEnumerator GetEnumerator() {public IEnumerator GetEnumerator() { return new __Enumerator(this);return new __Enumerator(this);}}

private class __Enumerator : IEnumeratorprivate class __Enumerator : IEnumerator{{ object current;object current; int state;int state;

public bool MoveNext() {public bool MoveNext() { switch (state) {switch (state) { case 0:case 0: current = "Hello";current = "Hello"; state = 1;state = 1; return true;return true; case 1:case 1: current = "World";current = "World"; state = 2;state = 2; return true;return true; default: default: return false;return false; }} }}

public object Current {public object Current { get { return current; }get { return current; } }}}}

Page 45: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

public class List<T>public class List<T>{{ public IEnumerator<T> GetEnumerator() {public IEnumerator<T> GetEnumerator() { for (int i = 0; i < count; i++)for (int i = 0; i < count; i++) yield return elements[i];yield return elements[i]; }}

public IEnumerable<T> Descending() {public IEnumerable<T> Descending() { for (int i = count - 1; i >= 0; i--)for (int i = count - 1; i >= 0; i--) yield return elements[i];yield return elements[i]; }}

public IEnumerable<T> Subrange(int index, int n) {public IEnumerable<T> Subrange(int index, int n) { for (int i = 0; i < n; i++)for (int i = 0; i < n; i++) yield return elements[index + i];yield return elements[index + i]; }}}}

IteratorsIterators

List<Item> items = GetItemList();List<Item> items = GetItemList();foreach (Item x in items) {...}foreach (Item x in items) {...}foreach (Item x in items.Descending()) {...}foreach (Item x in items.Descending()) {...}foreach (Item x in Items.Subrange(10, 20)) {...}foreach (Item x in Items.Subrange(10, 20)) {...}

Page 46: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

IteratorsIterators

DemoDemo

Page 47: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

Edit & ContinueEdit & Continue

DemoDemo

Page 48: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

So Where Have We Been?So Where Have We Been?

SecuritySecurity

Securing stringsSecuring strings

Security ContextSecurity Context

Access ControlAccess Control

EncryptionEncryption

Encrypting XMLEncrypting XML

Framework & Language EnhancementsFramework & Language Enhancements

GenericsGenerics

IteratorsIterators

Edit and ContinueEdit and Continue

Console enhancementsConsole enhancements

Page 49: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

Changes to the ConsoleChanges to the Console

DemoDemo

With thanks to Kit George and GotDotNet

Page 50: What’s New in Visual Studio 2005: Security &.NET Framework 2.0 Mike Pelton mpelton@microsoft.com Developer & Platform Group Microsoft Ltd

© 2004 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only.© 2004 Microsoft Corporation. All rights reserved. This presentation is for informational purposes only.MICROSOFT MAKES NO WARRANTIES, EXPRESS OR IMPLIED, IN THIS SUMMARY.MICROSOFT MAKES NO WARRANTIES, EXPRESS OR IMPLIED, IN THIS SUMMARY.