Top Banner
.NET Framework 2.0 y .NET Framework 2.0 y Introducci Introducci ó ó n al n al Visual C# .NET 2005 Visual C# .NET 2005 Renato Haddad Renato Haddad Microsoft Microsoft Most Most Valuable Valuable Professional Professional Brasil Brasil
73

.NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

Sep 30, 2018

Download

Documents

lamliem
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

.NET Framework 2.0 y .NET Framework 2.0 y IntroducciIntroduccióón aln al

Visual C# .NET 2005Visual C# .NET 2005

Renato HaddadRenato HaddadMicrosoft Microsoft MostMost ValuableValuable ProfessionalProfessional

BrasilBrasil

Page 2: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

ObjetivoObjetivo

Mostrar o .NET Mostrar o .NET Framework 2.0 y el Framework 2.0 y el lenguaje Visual C# lenguaje Visual C#

.NET 2005.NET 2005

Page 3: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

Framework, Framework, Lenguajes y HerramientasLenguajes y Herramientas

Base Class Library

Common Language Specification

Common Language Runtime

Data and XML

VB C++ C#Visual Studio.N

ET

WebServices

JScript …

UserInterface

Page 4: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

Common Language RuntimeCommon Language Runtime

VBVBSource Source codecode

C++C++C#C#

AssemblyAssemblyIL IL CodeCode

AssemblyAssemblyIL IL CodeCode

Operating System ServicesOperating System Services

Native CodeNative Code

ManagedManagedcodecode

Modelo de Modelo de EjecuciEjecucióónn

AssemblyAssemblyIL IL CodeCode

UnmanagedUnmanagedComponentComponent

JIT JIT CompilerCompiler

CompilerCompiler CompilerCompilerCompilerCompiler

ExecutExecutáável (.EXE), Pvel (.EXE), Páágina (.ASPX), gina (.ASPX), LocalServiceLocalService (.DLL) ou (.DLL) ou WebServiceWebService (.ASMX)(.ASMX)

Page 5: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

Base Class LibraryBase Class Library

Novedades 2005Novedades 2005

Page 6: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

GenericsGenerics

¿¿Por quPor quéé generics?generics?Type checking, Type checking, sin boxingsin boxing, , sinsin downcastsdowncastsImpide proliferaciImpide proliferacióón de copiasn de copias

// // Lista de enterosLista de enterosList<List<intint>> intListintList = new List<= new List<intint>();>();

intListintList.Add(1); .Add(1); // // SinSin boxingboxingintListintList.Add(2);.Add(2);

intListintList.Add("Three"); .Add("Three"); // // error en tiempo de compilacierror en tiempo de compilacióónn

intint i =i = intListintList[0]; [0]; // // Cast no requeridoCast no requerido

Page 7: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

Generics Generics ee BCLBCL 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>

ColecciColeccióón de clasesn de clases

ColecciColeccióón n dede interfacesinterfaces

ColecciColeccióón n dede clases baseclases base

ColecciColeccióón n utilitariasutilitarias

ReflectionReflection

Page 8: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

DiferenciasDiferenciasNueva claseNueva clase LinkedListLinkedListUsaUsa List<T> List<T> en lugar deen lugar de ArrayListArrayListIComparerIComparer<T> enhanced<T> enhancedIEnumerableIEnumerable<T> <T> simplificadosimplificadoOperaciones expandidas enOperaciones expandidas en lists lists yy arraysarrays

Page 9: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

ClasesClases GenericGenericNullableNullable

Permite tipos para soporte valores nullPermite tipos para soporte valores null

EventHandlerEventHandlerDefine tratamiento de eventosDefine tratamiento de eventos

NullableNullable<<intint>> i = 3;i = 3;bool bool b = i.b = i.HasValueHasValue();();int int j = i.Value();j = i.Value();

delegate voiddelegate void EventHandlerEventHandler<T><T>(Object sender, T e) (Object sender, T e) where T :where T : EventArgsEventArgs;;

Page 10: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

GenericsGenericsCCóódigos digos pueden ser parametrizados con detallespueden ser parametrizados con detalles do tipodo tipo

Habilitar la creaciHabilitar la creacióónn de modelos de cde modelos de cóódigosdigosTipo especTipo especíífico apropiado fico apropiado cuando el modelo es usadocuando el modelo es usadoComo EiffelComo Eiffel yy Ada generics Ada generics y modelos dely modelos del C++C++

Puede crear variosPuede crear varios tipos de genericstipos de genericsClasses, structs, interfaces, methods Classes, structs, interfaces, methods yy delegatesdelegates

Considerables beneficiosConsiderables beneficios para cpara cóódigos gendigos genééricosricosChequea el tipo en tiempo de compilaciChequea el tipo en tiempo de compilacióónnReduce el chequeo en tiempo de ejecuciReduce el chequeo en tiempo de ejecucióónn, boxing, boxing yyunboxingunboxingReduce la necesidad de conversiones explReduce la necesidad de conversiones explíícitascitasResulta en un tipo de cResulta en un tipo de cóódigo seguro limpio y rdigo seguro limpio y ráápidopido

Page 11: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

EjemplosEjemplos//// usingusing

// System.Collections.Generic;// System.Collections.Generic;

Stack< Employee > employees =Stack< Employee > employees =

new Stack< Employee >();new Stack< Employee >();

// // UsaUsa mméétodotodo PushPush

// // ParParáámetros tipo Employeemetros tipo Employee

// // No requiere conversionesNo requiere conversiones

employees.Push(employees.Push(

new Employee() );new Employee() );

// // Usa mUsa méétodo Poptodo Pop

// Devoluci// Devolucióón es tipo Employeen es tipo Employee

// // No requiere conversionesNo requiere conversiones

EmployeeEmployee employee =employee =

employees.Pop();employees.Pop();

StackStack< int > sizes =< int > sizes =

new Stack< int >();new Stack< int >();

// // SinSin boxingboxing

sizes.Push( 42 );sizes.Push( 42 );

// // SinSin unboxingunboxing

int size1 = sizes.Pop();int size1 = sizes.Pop();

sizes.Push( 77 );sizes.Push( 77 );

// Error!// Error!

// // Error en tiempo de compilaciError en tiempo de compilacióónn

sizes.Push( new Employee() );sizes.Push( new Employee() );

// // CCóódigo OKdigo OK

int size2 = sizes.Pop();int size2 = sizes.Pop();

Page 12: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

Stacks Stacks Con y SinCon y Sin GenericsGenerics

object int

object int

object int

object int

BoxBox

int

PushPush

SinSinGenericsGenerics

object int

UnboxUnbox

int

PopPop

int

int

int

int

PushPush

ConConGenericsGenerics

int

PopPop

Page 13: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

GenericsGenerics//// Generic MyStack classGeneric MyStack class

publicpublic class MyStack< T >class MyStack< T >

{{

private T[] frames;private T[] frames;

private int pointer = 0;private int pointer = 0;

public MyStack( int size )public MyStack( int size )

{{

frames = new T[ size ];frames = new T[ size ];

}}

public void Push( T frame public void Push( T frame ))

{{

frames[ pointer++ ] =frames[ pointer++ ] =

frame;frame;

}}

public T Pop()public T Pop()

{{

returnreturn

frames[ frames[ ----pointer ];pointer ];

}}

}}

MyStack< int > s =MyStack< int > s =

new MyStack< int >( 7 );new MyStack< int >( 7 );

for ( int f = 0; f < 7; ++f )for ( int f = 0; f < 7; ++f )

s.Push( f );s.Push( f );

// Prints '6 5 4 3 2 1 0 '// Prints '6 5 4 3 2 1 0 '

for ( int f = 0; f < 7; ++f )for ( int f = 0; f < 7; ++f )

Console.Write(Console.Write(

s.Pop() + " " );s.Pop() + " " );

Page 14: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

EjemplosEjemplosclassclass MyList< K, V >MyList< K, V >

where K : IComparable,where K : IComparable,

IFormattableIFormattable

where V : ValueBase, new()where V : ValueBase, new()

{{

// ...// ...

}}

class ValueBase {}class ValueBase {}

class Widget : ValueBase {}class Widget : ValueBase {}

class Thing : ValueBaseclass Thing : ValueBase

{{

public Thing( int i ) {}public Thing( int i ) {}

}}

//// 1 1 -- OKOK

MyList<int, Widget> list1 =MyList<int, Widget> list1 =

new MyList<int, new MyList<int, Widget>();Widget>();

// // 2 2 -- ErrorError!!

MyList<int, string> list2 =MyList<int, string> list2 =

new MyList<int, new MyList<int, string>();string>();

// // 3 3 -- ErrorError!!

MyList<int, Thing> list3 =MyList<int, Thing> list3 =

new MyList<int, Thing>();new MyList<int, Thing>();

// // 4 4 -- ErrorError!!

MyList<Point, Widget> list4 MyList<Point, Widget> list4 = new = new MyList<Point, MyList<Point, WidgetWidget>();>();

Page 15: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

PerformancePerformanceAlgunos puntosAlgunos puntos

Boxing Boxing de tiposde tiposCasting Casting en todos los tiposen todos los tiposOptimizaciones Optimizaciones StaticsStatics yy JITJIT

Use colecciones genUse colecciones genééricas en tipos de ricas en tipos de referenciareferenciaNo cree colecciones customizadas para No cree colecciones customizadas para tipos de valorestipos de valores

Page 16: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

Tracing EnhancementsTracing Enhancements

TraceTrace

CorrelationCorrelationManagerManager

TraceSourceTraceSource

SourceSwitchSourceSwitch

DebugDebug

TraceListenerCollectionTraceListenerCollection

TraceListenerTraceListener

TraceFilterTraceFilter TraceOptionsTraceOptions

NovasNovas nono 2.02.0

Page 17: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

TraceSource TraceSource yy SourceSwitchSourceSwitchTraceSourceTraceSource

Nuevas funcionalidadesNuevas funcionalidadesMMúúltiples fuentes identificadas por el nombreltiples fuentes identificadas por el nombrePropiedades FilterPropiedades Filter yy SwitchSwitch

SourceSwitchSourceSwitchControla el filtroControla el filtro

TraceSource ts TraceSource ts = new = new TraceSourceTraceSource("Source1");("Source1");tsts.Switch.Levels = .Switch.Levels = SourceLevelsSourceLevels.Information;.Information;

Page 18: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

NuevosNuevos ListenersListenersConsoleTraceListenerConsoleTraceListener

Logs para la consolaLogs para la consolaDelimitedListTraceListenerDelimitedListTraceListener

Logs para archivos Logs para archivos CSVCSV

XmlWriterTraceListenerXmlWriterTraceListenerLogs para archivos Logs para archivos XMLXML

MySourceMySource;Error;13;Wrong key;;;;;;318361290184;;Error;13;Wrong key;;;;;;318361290184;

Page 19: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

IntegraciIntegracióónn concon ASP.NET TracingASP.NET Tracing

WebPageTraceListenerWebPageTraceListenerRastrear ruta de salida para Rastrear ruta de salida para TraceContextTraceContextAdicionar vAdicionar víía web.xml o ca web.xml o cóódigodigo

<system.diagnostics> <system.diagnostics> <trace><trace>

<listeners><listeners><add name="<add name="WebPageTraceListenerWebPageTraceListener""

type="System.Web.type="System.Web.WebPageTraceListenerWebPageTraceListener, ... /> , ... /> </listeners></listeners>

</trace></trace></system.diagnostics></system.diagnostics>

Page 20: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

Opciones de ConfiguraciOpciones de ConfiguracióónnListener.Listener.TraceOutputOptionsTraceOutputOptions

Controles extras de informacionesControles extras de informacionesTrace.Trace.CorrelationManagerCorrelationManager

ActivityIdActivityId, , operaciones loperaciones lóógicasgicas

Archivo XML para configurar el Archivo XML para configurar el TraceSourceTraceSource

<source name="<source name="MySourceMySource"" switchValueswitchValue="Information" >="Information" ><listeners><listeners>

<add name="Console" <add name="Console" type="System.Diagnostics.type="System.Diagnostics.ConsoleTraceListenerConsoleTraceListener" />" />

</listeners></listeners></source></source>

Page 21: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

Performance BCLPerformance BCLPerformance del CLR similar para cPerformance del CLR similar para cóódigo digo nativonativo

Bajo costo para procesos administradosBajo costo para procesos administradosReduce tiempo de Reduce tiempo de StartupStartup

NGenNGenComparte cComparte cóódigos entre procesosdigos entre procesosOSOS code code NGen'dNGen'd

Page 22: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

PerformancePerformanceNuevas APIsNuevas APIs

APIs APIs para recursos de bpara recursos de búúsquedasquedaLightweight Lightweight CodeGenCodeGen

Mejoras en las Mejoras en las APIsAPIsCross Cross AppDomainAppDomain RemotingRemotingPerformance Performance para llamar para llamar DelegateDelegateAppDomainAppDomain FootprintsFootprintsUTF8EncodingUTF8Encoding

Page 23: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

SemSemááforosforosSystem.Threading.SemaphoreSystem.Threading.Semaphore

Un contador asociadoUn contador asociadoLimita las threads para acceder a recursosLimita las threads para acceder a recursosAcceso al proceso por nombreAcceso al proceso por nombre

Sem

apho

reC

ount

=3Thread

Thread

Thread

Thread

Thread

Thread

Thread

Thread Res

ourc

e

Page 24: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

SemSemááforoforo// // Crea un semCrea un semááforo con un contador de 3foro con un contador de 3SemaphoreSemaphore semsem = new Semaphore(3);= new Semaphore(3);

// // Bloquea hasta un contador disponibleBloquea hasta un contador disponiblesemsem..WaitOneWaitOne();();

// // Usa el recurso protegidoUsa el recurso protegido

// // LiberaciLiberacióón del semn del semááforoforosemsem.Release();.Release();

Page 25: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

CompresiCompresióónn de Streamde StreamSystem.IO.CompressionSystem.IO.Compression

Dos nuevas clasesDos nuevas clasesGZipStreamGZipStream

PadrPadróón de la industria n de la industria GZipGZip (RFC 1952)(RFC 1952)

DeflateStreamDeflateStreamLZW77 (RFC 1951)LZW77 (RFC 1951)

StreamWriter GZipStream

Page 26: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

CompresiCompresióónn// // Leer datos compactados de un archivoLeer datos compactados de un archivostring string decomp decomp = String.Empty;= String.Empty;

FileStream fsFileStream fs = new= new FileStreamFileStream((@"c:@"c:\\temptemp\\compress.compress.datdat", ", FileModeFileMode.Open,.Open, FileAccessFileAccess.Read,.Read, FileShareFileShare.Read);.Read);

GZipStreamGZipStream zipStrmzipStrm = new= new GZipStreamGZipStream((fsfs, , CompressionModeCompressionMode.Decompress);.Decompress);

using (using (StreamReader srStreamReader sr = new= new StreamReaderStreamReader((zipStrmzipStrm)))){{

decompdecomp = sr.= sr.ReadToEndReadToEnd();();}}Console.Console.WriteLineWriteLine((decompdecomp););

Page 27: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

Novedades para ConsoleNovedades para ConsoleCaptura y atribuye el tamaCaptura y atribuye el tamañño del Console, o del Console, buffer de pantalla y cursorbuffer de pantalla y cursorCambia la posiciCambia la posicióón de la ventana de la n de la ventana de la consola y el cursorconsola y el cursorCambia el color y el tCambia el color y el tíítulo de la ventanatulo de la ventanaCaptura teclas presionadasCaptura teclas presionadas

Page 28: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

SeguridadSeguridad dede StringsStringsProblemas en System.StringProblemas en System.String

No chequeadoNo chequeadoNo encriptadoNo encriptadoNo mutableNo mutableNo permite limpiarNo permite limpiar

Page 29: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

System.Security.System.Security.SecureStringSecureStringUsado para textos confidencialesUsado para textos confidenciales

Contenido es encriptadoContenido es encriptadoBorrado cuando no necesario (usar Borrado cuando no necesario (usar IDisposable IDisposable para remocipara remocióón)n)Clase no visible para COMClase no visible para COM

MMéétodos soportadostodos soportadosInsert, Append, Remove Insert, Append, Remove yy ClearClearMakeReadOnly MakeReadOnly parapara lockdownlockdownSin mSin méétodos para inspeccionar, comparar o todos para inspeccionar, comparar o convertir el contenidoconvertir el contenido

Page 30: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

SecureStringSecureString// // Crea unaCrea una SecureStringSecureStringSecureString ssSecureString ss = new = new SecureStringSecureString();();

// // Adiciona Adiciona caracteres y traba lacaracteres y traba la stringstringssss..AppendCharacterAppendCharacter('a');('a');ssss..AppendCharacterAppendCharacter('b');('b');ssss..MakeReadOnlyMakeReadOnly();();

// // Recupera contenidoRecupera contenidoIntPtr uniStringIntPtr uniString = =

Marshal.Marshal.SecureStringToGlobalAllocUniSecureStringToGlobalAllocUni((ssss););String s = Marshal.String s = Marshal.PtrToStringUniPtrToStringUni((uniStringuniString););Console.Console.WriteLineWriteLine("String is '{0}'", s);("String is '{0}'", s);

// // CeroCero yy freefreeMarshal.Marshal.ZeroFreeGlobalAllocUniZeroFreeGlobalAllocUni((uniStringuniString););

Page 31: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

HttpListenerHttpListenerEndpoint Endpoint para solicitudes para solicitudes HTTPHTTP

No requiere el No requiere el IISIISÚÚnico prefijo nico prefijo URIURIUseUse HTTP.SYS (2003HTTP.SYS (2003 Server, XP Server, XP SP2)SP2)Acceso Request/ResponseAcceso Request/Response

HTTP.SYSHTTP.SYShttp://http://localhostlocalhost/app1/xyz/app1/xyz

http://http://localhostlocalhost/app2//app2/abcabc

Process 1

Process 2

Prefix = app1Prefix = app1

Prefix = app2Prefix = app2

Page 32: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

HttpListenerHttpListener// // Crea unCrea un HttpListenerHttpListenerHttpListenerHttpListener lstlst = new= new HttpListenerHttpListener();();

// // Adiciona un prefijo para el listenerAdiciona un prefijo para el listenerlstlst.Prefixes.Add(.Prefixes.Add(

string.Format(" http://string.Format(" http://localhostlocalhost/{0}/ ",/{0}/ ", argsargs[0]));[0]));

// // Inicia el listeningInicia el listeninglstlst.Start();.Start();

while (true) {while (true) {// // Bloquea aguardando conexiBloquea aguardando conexióónnHttpListenerContext ctxHttpListenerContext ctx = = lstlst..GetContextGetContext();();

// // Haga algoHaga algo......}}

Page 33: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

Puerta SerialPuerta Serialnamespace System.IO.Portsnamespace System.IO.PortsClase SerialPortClase SerialPort soporta serialsoporta serial commscomms

AsyncAsync y eventos de I/Oy eventos de I/OAceso vAceso víía streama stream

using System.IO.Ports;using System.IO.Ports;......SerialPortSerialPort sp = new sp = new SerialPortSerialPort("COM1", 19200);("COM1", 19200);sp.sp.ReadTimeout ReadTimeout = 3000;= 3000;sp.sp.WriteTimeoutWriteTimeout = 3000;= 3000;sp.Open();sp.Open();......sp.Read(sp.Read(byteBuffbyteBuff, 0, , 0, nBytesToReadnBytesToRead);c);c

Page 34: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

Debugger ImprovementsDebugger ImprovementsDataTipsDataTipsTipos deTipos de VisionesVisiones

DebuggerDisplayAttributeDebuggerDisplayAttributeDebuggerBrowsableAttributeDebuggerBrowsableAttributeDebuggerTypeProxyAttributeDebuggerTypeProxyAttribute

Tipos de VisualizadoresTipos de Visualizadores

Page 35: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

LocalizacLocalizacííononWindows FormsWindows Forms

Controles TreeView, ListViewControles TreeView, ListViewMejorMejoríía en la compartimentacia en la compartimentacióón de recursosn de recursos

ClickOnceClickOnceDeploy en mDeploy en múúltiples lenguajes para el mismo ltiples lenguajes para el mismo proyectoproyecto

ASP.NETASP.NETNuevo modelo de localizaciNuevo modelo de localizacióónnArchivo Archivo resx en tempo de Designresx en tempo de DesignAutoAuto--deteccideteccióón de la cultura del browsern de la cultura del browser

Page 36: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

Recursos Recursos FuertementeFuertemente TipadosTipadosClasesClases representan recursosrepresentan recursos

Accesos fuertemente tipados para archivosAccesos fuertemente tipados para archivos ..resxresx

this.pictureBox1.Image = this.pictureBox1.Image = MyProjectMyProject.Properties.Resources.the_image;.Properties.Resources.the_image;

public static System.Drawing.Bitmap the_image {public static System.Drawing.Bitmap the_image {get {get {

return ((System.Drawing.Bitmap)return ((System.Drawing.Bitmap)((ResourceManagerResourceManager..GetObjectGetObject("the_image", ("the_image", __resCultureresCulture)));)));

}}}}

InitializeComponent()

Local.Properties.Resources

Page 37: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

CustomizaciCustomizacióónn dede CulturasCulturasCrear novas culturasCrear novas culturas

Completamente nuevaCompletamente nueva (Fiji)(Fiji)CombinaciCombinacióón Pan Paíís/Lengua (Ballenass/Lengua (Ballenas ))Customizar existentesCustomizar existentes (formato fecha/n(formato fecha/núúmeromero))CustomizarCustomizar sufijossufijos ((enen--USUS--MyCompanyMyCompany))

CultureAndRegionInfoBuilderCultureAndRegionInfoBuilderBuild, Build, registro,registro, salvar asalvar a XMLXMLCrossCross--machine machine e appdomaine appdomain

enen--USUS--MicrosoftMicrosoftfjfj--FJFJ

spsp--USUScycy--UKUK

Page 38: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

CustomizaciCustomizacióónn de Culturasde Culturas// // Crea un nuevo objetoCrea un nuevo objeto CultureAndRegionInfoBuilderCultureAndRegionInfoBuilder

// // basado enbasado en cultureculture enen--USUSCultureAndRegionInfoBuilder caribCultureAndRegionInfoBuilder carib = new = new

CultureAndRegionInfoBuilderCultureAndRegionInfoBuilder((new new CultureInfoCultureInfo("en("en--US"),US"),new new RegionInfoRegionInfo("US"),("US"),"en", "US", ""en", "US", "microsoftmicrosoft");");

// // Registra esta mRegistra esta mááquina en elquina en el deploydeploycaribcarib.Register();.Register();

// // Salva enSalva en XMLXMLcaribcarib.Save("c:.Save("c:\\temptemp\\myculturemyculture.xml");.xml");

// // Hace referencia al nuevoHace referencia al nuevo objetoobjeto CultureInfoCultureInfoCultureInfo ciCultureInfo ci = new= new CultureInfoCultureInfo("en("en--USUS--microsoftmicrosoft););

Page 39: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

CCóódigos Independientesdigos IndependientesBiblioteca de cBiblioteca de cóódigos para cambiar frecuentemente un tipodigos para cambiar frecuentemente un tipoobjectobject

Permite que el cPermite que el cóódigo trabaje con datos de cualquier tipodigo trabaje con datos de cualquier tipoUsado para campos, tipos de parUsado para campos, tipos de paráámetros y devolucionesmetros y devoluciones

Esta tEsta téécnica posee una desventajacnica posee una desventaja (drawbacks)(drawbacks)Chequea el tipo en tiempo de compilaciChequea el tipo en tiempo de compilacióónn

Puede usar tipos inapropiados e incompatiblesPuede usar tipos inapropiados e incompatiblesExime el uso de overhead cuando usa tipos de valoresExime el uso de overhead cuando usa tipos de valores

Chequea el tipo en tiempo de ejecuciChequea el tipo en tiempo de ejecucióónn (boxing(boxing, , unboxing)unboxing)

Potencial overhead cuando usa tipos por referenciaPotencial overhead cuando usa tipos por referenciaChequea y convierte el tipo en tiempo de ejecuciChequea y convierte el tipo en tiempo de ejecucióónn

Page 40: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

EjemplosEjemplos//// using System.Collections;using System.Collections;

//// EmployeesEmployees

Stack employees = new Stack();Stack employees = new Stack();

// // UsaUsa mméétodo Pushtodo Push

// // ParParáámetro es un objetometro es un objeto

// // Usa conversiones implUsa conversiones implíícitacita

employees.Pushemployees.Push((

new Employee() );new Employee() );

// // Usa mUsa méétodo Poptodo Pop

// // DevoluciDevolucióón un objeton un objeto

// // Precisa converterPrecisa converter

Employee employee =Employee employee =

(Employee) employees.Pop();(Employee) employees.Pop();

//// IntegersIntegers

Stack sizes = new Stack();Stack sizes = new Stack();

// Box// Box

sizes.Push( 42 );sizes.Push( 42 );

// Unbox// Unbox

int size1 = (int) sizes.Pop();int size1 = (int) sizes.Pop();

// // Equivocado pero compilaEquivocado pero compila OKOK

sizes.Push( 77 );sizes.Push( 77 );

sizes.Push( new Employee() );sizes.Push( new Employee() );

// // CompilaCompila OK OK pero generapero genera

// InvalidCastException// InvalidCastException

int size2 = (int) sizes.Pop();int size2 = (int) sizes.Pop();

Page 41: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

Tipos PartialTipos PartialPermite Permite implementaciimplementacióón a mn a múúltiples archivosltiples archivos

VVáálido para lido para clases y estructurasclases y estructuras (e(e interfaces C#)interfaces C#)Declarado con el nuevo tipo Declarado con el nuevo tipo partialpartial

Soporta los siguientes beneficiosSoporta los siguientes beneficiosGrandes implementaciones pueden ser divididasGrandes implementaciones pueden ser divididasCCóódigo del usuario puede ser separado del cdigo del usuario puede ser separado del cóódigo digo generadogenerado

Previene reescritura de los cambiosPreviene reescritura de los cambiosUsado porUsado por WinForms WinForms yy DataSets tipadosDataSets tipados

Varios devs pueden trabajar al mismo tiempoVarios devs pueden trabajar al mismo tiempoHabilitaHabilita codecode--besidebeside en lugaren lugar dede codecode--behind, behind, usado usado en elen el ASP.NET 2.0ASP.NET 2.0FFáácil mantenimiento y control del ccil mantenimiento y control del cóódigo fuentedigo fuente

Page 42: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

EjemplosEjemplos// Demo.Part1.cs// Demo.Part1.cs

using System;using System;

public partial class Demopublic partial class Demo

{{

public Demo()public Demo()

{{

Console.Write( "P1" );Console.Write( "P1" );

}}

}}

// Demo.Part2.cs// Demo.Part2.cs

public partial class Demopublic partial class Demo

{{

private int i;private int i;

}}

//// Demo.Part3.csDemo.Part3.cs

// // Erro 1Erro 1

public class Demopublic class Demo

{{

// // Erro 2Erro 2

private int i;private int i;

// OK// OK

private int j;private int j;

public void Test()public void Test()

{{

// // Erro 3Erro 3

Console.Write( "P3" );Console.Write( "P3" );

}}

}}

Page 43: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

UsandoUsando Partial TypesPartial TypesSeparar un tipo no afecta el cSeparar un tipo no afecta el cóódigo compiladodigo compilado

Todas las partes se mezclarTodas las partes se mezclaráán en tiempo de compilacin en tiempo de compilacióónnNo puede extender un tipo ya compiladoNo puede extender un tipo ya compilado

CCóódigo es o no acumulativodigo es o no acumulativoElementos acumulativos son combinados (incluye Elementos acumulativos son combinados (incluye mméétodo, campos e interfacestodo, campos e interfaces))Elementos noElementos no--acumulativos deben buscar en todas las acumulativos deben buscar en todas las partes (incluye tipos, visibilidad y clase basepartes (incluye tipos, visibilidad y clase base ))

Ayuda a aceptar convenciAyuda a aceptar convencióón de nombresn de nombresEx.:Ex.: MyCls.Part1.cs MyCls.Part1.cs e MyCls.Part2.cse MyCls.Part2.cs

Class View Class View y barra de navegaciy barra de navegacióón reflejan el tipo completon reflejan el tipo completo

Page 44: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

ModifiersModifiersEspecificar diferentes elementos de acceso para el Especificar diferentes elementos de acceso para el getgety el y el setset de las propiedades e de las propiedades e ííndicesndices

ComComúún para public n para public getget pero el pero el setset es protectedes protectedPuede solamente modificar uno de los dos elementos Puede solamente modificar uno de los dos elementos de acceso a travde acceso a travéés de la propiedad o s de la propiedad o ííndicendicePuede especificar mPuede especificar máás restriccioness restricciones

publicpublic int this[ int i ]int this[ int i ]

{{

getget

{{

return this.a[ i ];return this.a[ i ];

}}

protected setprotected set

{{

this.a[ i ] = value;this.a[ i ] = value;

}}

}}

Page 45: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

MMéétodos Anonymoustodos AnonymousAlgAlgúún cn cóódigo es llamado solamente por eldigo es llamado solamente por el delegatedelegate

Ex.: eventEx.: event handlers handlers yy callbackscallbacksMMéétodos anonymoustodos anonymous ofrecen soluciones elegantesofrecen soluciones elegantes

Permite que cPermite que cóódigos para un delegate sean escritos digos para un delegate sean escritos ‘‘inin--lineline’’Un delegate puede ser usado en cualquier lugarUn delegate puede ser usado en cualquier lugarSe crea usando la palabra claveSe crea usando la palabra clave delegatedelegate

Similar a las funciones del Lisp y delSimilar a las funciones del Lisp y del PythonPython

Conversiones implConversiones implíícitas para el tipo decitas para el tipo de delegatedelegate

Requiere compatibilidad de parRequiere compatibilidad de paráámetros y tipos de metros y tipos de retornoretorno

Page 46: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

EjemplosEjemplos//// C# 1.0C# 1.0

this.saveButton.Click +=this.saveButton.Click +=

new EventHandler(new EventHandler(

this.SaveClick );this.SaveClick );

private void SaveClick(private void SaveClick(

object sender,object sender,

EventArgs e )EventArgs e )

{{

this.Save();this.Save();

}}

//// C# 2.0C# 2.0

this.saveButton.Click +=this.saveButton.Click +=

delegate { this.Save(); };delegate { this.Save(); };

//// using System.Threading;using System.Threading;

//// C# 1.0C# 1.0

Thread task = new Thread(Thread task = new Thread(

new ThreadStart(new ThreadStart(

this.Background ) );this.Background ) );

private void Background()private void Background()

{{

Trace.Write( "1.0" );Trace.Write( "1.0" );

}}

// C# 2.0// C# 2.0

Thread task = new Thread(Thread task = new Thread(

delegate(){delegate(){

Trace.Write( "2.0" ); } );Trace.Write( "2.0" ); } );

Page 47: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

IteratorsIteratorsBloques de cBloques de cóódigos que ordena una secuenciadigos que ordena una secuencia

Distinguido por uno o mDistinguido por uno o máás s statementsstatements yieldyield

yield returnyield return produce el prproduce el próóximo valor de la ximo valor de la interacciinteraccióónnyield breakyield break indica que la interacciindica que la interaccióón estn estáá completacompleta

Puede ser el cuerpo del mPuede ser el cuerpo del méétodo si devuelve una interfacetodo si devuelve una interfaceIEnumerator[< T >] IEnumerator[< T >] oo IEnumerable[< T >]IEnumerable[< T >]

Es una implementaciEs una implementacióón en un tipo de miembron en un tipo de miembroCompilador genera valor del cCompilador genera valor del cóódigodigo

ImplementaciImplementacióón n EnumeratorEnumeratorClase para mantener el estado de la interacciClase para mantener el estado de la interaccióónn

Cada uno que interactCada uno que interactúúa tiene su propio estadoa tiene su propio estadoEvita problemas causados por la interacciEvita problemas causados por la interaccióónn

Page 48: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

EjemplosEjemplospublicpublic class Payrollclass Payroll

: IEnumerable< Emp >: IEnumerable< Emp >

{{

private Emp[] pay;private Emp[] pay;

public IEnumerator< Emp >public IEnumerator< Emp >

GetEnumerator()GetEnumerator()

{{

foreach ( Emp e in pay )foreach ( Emp e in pay )

yield return e;yield return e;

}}

public IEnumerable< Emp >public IEnumerable< Emp >

ForwardForward

{{

get { return this; }get { return this; }

}}

public IEnumerable< Emp >public IEnumerable< Emp >

ReverseReverse

{{

getget

{{

// for ( int e = ...// for ( int e = ...

yield returnyield return

pay[ e ];pay[ e ];

}}

}}

}}

PayrollPayroll p = new Payroll();p = new Payroll();

foreach ( Emp e in p )foreach ( Emp e in p )

Console.WriteLine( e.Net );Console.WriteLine( e.Net );

foreach ( Emp e in p.Reverse )foreach ( Emp e in p.Reverse )

Console.WriteLine( e.Net );Console.WriteLine( e.Net );

Page 49: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

Delegate InferenceDelegate InferenceCompilar puede inferir en la referencia del Compilar puede inferir en la referencia del delegatedelegate

Usa el mismo mecanismo de mUsa el mismo mecanismo de méétodos anonymoustodos anonymous

Habilita mHabilita méétodos que sertodos que seráán atribuidos directamente aln atribuidos directamente aldelegatedelegate

Conversiones implConversiones implíícitas al tipo compatible del citas al tipo compatible del delegatedelegatePuede omitir instancias explPuede omitir instancias explíícitas en muchos casoscitas en muchos casos

Suministra una sintaxis eleganteSuministra una sintaxis elegante

//// C# 1.0C# 1.0

this.Loadthis.Load += new += new EventHandler(EventHandler(

this.FormLoad );this.FormLoad );

this.Update( new CallBack( this.Update( new CallBack( this.MyMethod ) );this.MyMethod ) );

//// C# 2.0C# 2.0

this.Loadthis.Load += this.FormLoad;+= this.FormLoad;

this.Updatethis.Update( this.MyMethod );( this.MyMethod );

Page 50: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

CalificadorCalificador AliasAliasCalificador global del Calificador global del namespacenamespace

Nuevo operadorNuevo operador ‘‘::::’’Se aplica a aliases y Se aplica a aliases y namespacesnamespaces

Alias Alias globalglobal hacehacereferenciareferencia alal rootrootnamespacenamespaceResuelve varios problemas Resuelve varios problemas de nomenclaturade nomenclatura

//// C# 2.0C# 2.0

using System;using System;

namespacenamespace ImagingImaging

{{

public class Console {}public class Console {}

public class Systempublic class System

{{

public void Demo()public void Demo()

{{

// // Erro!Erro!

Console.Write("6x9");Console.Write("6x9");

// OK// OK

global::System.Consoleglobal::System.Console

.Write("42");.Write("42");

}}

}}

}}

Page 51: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

Otras caracterOtras caracteríísticassticasSintaxis especial para tipos nulosSintaxis especial para tipos nulos

Variables que contienen un estado indefinidoVariables que contienen un estado indefinidoT?T? short short parapara System.Nullable<T>System.Nullable<T>, , intint? i;? i;

Assemblies Assemblies amigablesamigablesAcceso para tipos noAcceso para tipos no--ppúúblicos a otras assembliesblicos a otras assemblies

Fijar el tamaFijar el tamañño delo del bufferbuffer

Permite fijar el tamaPermite fijar el tamaññoo structstruct dede arrays arrays Otras funcionalidades Otras funcionalidades externextern

Hace referencia a diferentes versiones del mismo Hace referencia a diferentes versiones del mismo componentecomponente

Page 52: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

Novedades no Novedades no System.DataSystem.Data

Page 53: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

JerarquJerarquíía de clasesa de clasesIDbIDb* interfaces * interfaces (ex(ex IDbConnectionIDbConnection))

Db* abstract base classes Db* abstract base classes (ex(ex DbConnectionDbConnection))

Implementa la claseImplementa la clase Db*BaseDb*Base

SqlSql OleDbOleDb ODBCODBC OracleOracle 33rdrd

Party 1Party 133rdrd

Party 2Party 2

Provider-Independiente del código de la app en esta capa

Provider-específico en el código de la app en esta capa

Page 54: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

Clases Comunes de ProvidersClases Comunes de Providersnamespace System.Data.Commonnamespace System.Data.Common

DbExceptionDbExceptionDbProviderFactoriesDbProviderFactoriesDbProviderFactoryDbProviderFactory

DbTransactionDbTransactionDbParameterCollectionDbParameterCollectionDbParameterDbParameter

DbDataReaderDbDataReaderDbDataAdapterDbDataAdapterDataAdapterDataAdapter

DbConnectionDbConnectionDbCommandBuilderDbCommandBuilderDbCommandDbCommand

Page 55: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

Usando un ProviderUsando un ProviderImporte el NamespaceImporte el Namespace::usingusing System.Data.CommonSystem.Data.Common

Cree una referenciaCree una referencia::static DbProviderFactory factory = static DbProviderFactory factory =

DbProviderFactories.GetFactory("providerDbProviderFactories.GetFactory("provider--name")name")

Cree una referencia del objetoCree una referencia del objeto::DbConnection con = factory.CreateConnection()DbConnection con = factory.CreateConnection()

DbCommand cmd = con.CreateCommand()DbCommand cmd = con.CreateCommand()

Page 56: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

Provider EnumerationProvider EnumerationCada provider tiene un nombreCada provider tiene un nombre

System.Data.SqlClient,System.Data.SqlClient, System.Data.OracleClientSystem.Data.OracleClient

Recibe la lista de Providers instaladosRecibe la lista de Providers instaladosDataTable dt = DbProviderFactories.GetFactoryClasses()DataTable dt = DbProviderFactories.GetFactoryClasses()

DbProviderFactory factory = DbProviderFactory factory = DbProviderFactories.GetFactory(dt.Rows[x])DbProviderFactories.GetFactory(dt.Rows[x])

-- o o --DbProviderFactory factory = DbProviderFactory factory =

DbProviderFactories.GetFactory( DbProviderFactories.GetFactory( dt.Select("InvariantName='System.Data.SqlClient'") dt.Select("InvariantName='System.Data.SqlClient'") [0]["InvariantName"].ToString());[0]["InvariantName"].ToString());

Page 57: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

Schema Discovery APISchema Discovery API

Recibe una lista de los SchemasRecibe una lista de los Schemas::DataTable dt = conn.GetSchema("MetaDataCollections")DataTable dt = conn.GetSchema("MetaDataCollections")

Recibe un Schema especRecibe un Schema especííficofico::DataTable dt = conn.GetSchema("DataTable dt = conn.GetSchema("collectioncollection--namename")")

Recibe detalles del Recibe detalles del SchemaSchema::DataTable dt = conn.GetSchema("DataTable dt = conn.GetSchema("collectioncollection--namename", ",

restrictionrestriction--arrayarray))

Page 58: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

Schema Schema SelectionSelection

UserDefinedTypesUserDefinedTypesIndexesIndexesIndexColumnsIndexColumnsForeignKeysForeignKeysProcedureColumnsProcedureColumnsProceduresProceduresParametersParametersViewColumnsViewColumnsViewsViewsCollectionNameCollectionName

1144ColumnsColumns4444TablesTables5511DatabasesDatabases4411UsersUsers44n/an/aReservedWordsReservedWords44n/an/aRestrictionsRestrictions44n/an/aDataTypesDataTypes44n/an/aDataSourceInformationDataSourceInformation33n/an/aMetaDataCollectionsMetaDataCollections

RestrictionsRestrictionsRestrictionsRestrictionsCollectionNameCollectionName

GetSchema("GetSchema("collectioncollection--namename",", restrictions[restrictions[xx])])

Page 59: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

MejorMejoríía en ela en elDataSetDataSet

Page 60: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

Aumentando la PerformanceAumentando la PerformanceÍÍndices internos de las lndices internos de las lííneas neas (Rows)(Rows)

Inserts y deletes son logInserts y deletes son log--nnUpdates Updates mmáás rs ráápidospidos

SerializaciSerializacióón binaria del contenidon binaria del contenidoElEl DataSet 1.xDataSet 1.x es siempre serializado para es siempre serializado para XMLXML

Bueno para integrar datos, malo en performanceBueno para integrar datos, malo en performance

SerializaciSerializacióón binaria en el n binaria en el 2.02.0RRáápido y compacto, especialmente con el aumento pido y compacto, especialmente con el aumento del contador de ldel contador de lííneasneasDataSet.RemotingFormatDataSet.RemotingFormat = = SerializationFormat.BinarySerializationFormat.Binary

Page 61: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

Cargando unCargando un DataSetDataSetDataAdapter.Fill(DataSet,"tableDataAdapter.Fill(DataSet,"table--name")name")

DataAdapter.FillLoadOptionDataAdapter.FillLoadOption y la propiedad y la propiedad AcceptChangesDuringUpdateAcceptChangesDuringUpdate

MMéétodo DataSet.Loadtodo DataSet.LoadLoad(DataReaderLoad(DataReader [, load[, load--option] [, tablesoption] [, tables--array])array])

Puede Puede usar FillErrorEventHandlerusar FillErrorEventHandler para tratar errorespara tratar errores

LoadOptionLoadOption enumerationenumerationPreserveCurrentValuesPreserveCurrentValues | | UpdateCurrentValuesUpdateCurrentValues | | OverwriteRowOverwriteRow

Page 62: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

Enum LoadOptionEnum LoadOption

Current = IncomingCurrent = IncomingOriginal = ExistingOriginal = ExistingRowStateRowState = Added= Added

Current = IncomingCurrent = IncomingOriginal = ExistingOriginal = Existing* if new value = existing * if new value = existing value: value:

RowStateRowState = Unchanged = Unchanged * else:* else:

RowStateRowState = Modified= Modified

* Undo Delete * Undo Delete Current = IncomingCurrent = IncomingOriginal = ExistingOriginal = ExistingRowStateRowState = Modified= Modified

Current = IncomingCurrent = IncomingOriginal = ExistingOriginal = ExistingRowStateRowState = Modified= Modified

Current = IncomingCurrent = IncomingOriginal = ExistingOriginal = ExistingRowStateRowState = Added= Added

UpdateCurrentValuesUpdateCurrentValues

Current = IncomingCurrent = IncomingOriginal = IncomingOriginal = IncomingRowStateRowState = Unchanged= Unchanged

Current = IncomingCurrent = IncomingOriginal = IncomingOriginal = IncomingRowStateRowState = Unchanged= Unchanged

No matching No matching existing row in existing row in the tablethe table

Current = IncomingCurrent = IncomingOriginal = IncomingOriginal = IncomingRowStateRowState = Unchanged= Unchanged

Current = IncomingCurrent = IncomingOriginal = IncomingOriginal = IncomingRowStateRowState = Unchanged= Unchanged

UnchangedUnchanged

* Undo Delete * Undo Delete Current = IncomingCurrent = IncomingOriginal = IncomingOriginal = IncomingRowStateRowState = Unchanged= Unchanged

Current = ExistingCurrent = ExistingOriginal = IncomingOriginal = IncomingRowStateRowState = Deleted= Deleted

DeletedDeleted

Current = IncomingCurrent = IncomingOriginal = IncomingOriginal = IncomingRowStateRowState = Unchanged= Unchanged

Current = ExistingCurrent = ExistingOriginal = IncomingOriginal = IncomingRowStateRowState = Modified= Modified

ModifiedModified

Current = IncomingCurrent = IncomingOriginal = IncomingOriginal = IncomingRowStateRowState = Unchanged= Unchanged

Current = ExistingCurrent = ExistingOriginal = IncomingOriginal = IncomingRowStateRowState = Modified= Modified

AddedAdded

OverwriteRowOverwriteRowPreserveCurrentValuesPreserveCurrentValues(the default value)(the default value)

RowStateRowState of of Existing RowExisting Row

Page 63: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

+ Novedades+ NovedadesValores RowStateValores RowState son actualizablesson actualizables

Nuevos mNuevos méétodostodos:: DataRow.SetAddedDataRow.SetAdded eeDataRow.SetModifiedDataRow.SetModified

MMéétodo DataSet.GetDataReadertodo DataSet.GetDataReader

Retorna un Retorna un DataTableReaderDataTableReader

Usted puede definir quUsted puede definir quéé tablas se incluirtablas se incluiráánn

Page 64: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

Instancias DataTable StandInstancias DataTable Stand--alonealoneOperaciones comunes del Operaciones comunes del DataSet DataSet tambitambiéén n disponibles en el disponibles en el DataTable:DataTable:

ReadXmlReadXml, , ReadXmlSchemaReadXmlSchema, , WriteXmlWriteXml, , WriteXmlSchemaWriteXmlSchema, Clear, Clone, Copy, Merge, , Clear, Clone, Copy, Merge, GetChangesGetChanges

DataTable DataTable autoauto--serializableserializable::Retorna un Retorna un DataTableDataTable de un Webde un Web Service Service ooRemotingRemoting

Page 65: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

Actualizaciones en BatchActualizaciones en BatchActualizaciones en el DataSet son Actualizaciones en el DataSet son procesadas una a unaprocesadas una a unaReduz Reduz Reduce trReduce tráánsito en la rednsito en la redDataAdapter.UpdateBatchSizeDataAdapter.UpdateBatchSize = = batch_sizebatch_sizeTrabaja con transaccionesTrabaja con transaccionesTrabaja con Trabaja con SQLSQL Server Server 7,7, 2000, 2000, 2005 y 2005 y clases OracleClientclases OracleClient

Page 66: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

Tipo de datos XMLTipo de datos XML en el DataSeten el DataSetOO DataTable DataTable acepta columna tipo acepta columna tipo xmlxml

System.Data.SqlTypes.SqlXmlSystem.Data.SqlTypes.SqlXmlExpuesto como una referencia Expuesto como una referencia XPathDocumentXPathDocumentPuede accederse a Puede accederse a éél vl víía a XmlReaderXmlReaderFacilidad de trabajar con documentos XML Facilidad de trabajar con documentos XML como un conjunto de valorescomo un conjunto de valoresFiel Fiel al contenido al contenido XMLXML

Page 67: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

Nuevos Nuevos ControlesControles

Page 68: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

WebBrowserWebBrowser GridViewGridView

SoundPlayerSoundPlayer

Page 69: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

ToolStripToolStrip

SplitContainerSplitContainer MaskEditMaskEdit

Page 70: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

NuevoNuevoDesignerDesigner

Page 71: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

ToolStripToolStrip

Smart TagsSmart Tags SnapLinesSnapLines

Document OutLineDocument OutLine

Page 72: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

Novedades Novedades en el Runtimeen el Runtime

Page 73: .NET Framework 2.0 y Introducción al Visual C# .NET … · .NET Framework 2.0 y Introducción al Visual C# .NET 2005 Renato Haddad Microsoft Most Valuable Professional Brasil

Data SupportData Support

ClickOnceClickOnce WinXP Visual StyleWinXP Visual Style

Client ConfigurationClient Configuration