Está en la página 1de 42

Framework Class Library (FCL)

Dr. Diego Lz. de Ipia Gz. de Artaza http://paginaspersonales.deusto.es/dipina

FCL (Framework Class Library)


Provee la API que las aplicaciones gestionadas en .NET invocan. Incluye ms de 7000 tipos y est particionada en ms de 100 espacios de nombres :
Desde Int32 y String a tipos como Regex o Form System es la raz de la mayora
Define tipos bsicos como Int32 y Byte y clases de utilidad como Math y TimeSpan o Collections

FCL (Framework Class Library)


En este apartado veremos algunas de los espacios de nombres ms importantes de la FCL:
System.IO System.Collections System.XML System.Reflection System.GC System.NET y System.Web

System.IO
Este espacio de nombres lo comprenden las clases que facilitan el acceso a ficheros. La construccin principal que usan es el stream Clases de tipo Stream, como FileStream, son bsicas
.NET tambin provee construcciones ms sofisticadas en forma de Readers y Writers

Permite acceder tanto a ficheros de texto (a travs de TextWriter y TextReader) como a binarios (BinaryWriter y BinaryReader).

System.IO
El procedimiento para leer o escribir un fichero es:
1. 2. Abrir el fichero usando el objeto FileStream Para lecturas o escrituras binarias, crear un BinaryReader y BinaryWriter alrededor de FileStream, y llamar a mtodos Read y Write Para lecturas o escrituras de texto, crear un StreamReader y StreamWriter alrededor de FileStream, y llamar a mtodos ReadLine y WriteLine Cerrar el FileStream

3.

4.

System.IO contiene tambin clases para manipular ficheros y directorios:


File y FileInfo, abre, crea, copia, mueve y borra ficheros Directory y DirectoryInfo hacen lo mismo para directorios

Ejemplo de I/O para texto: List.cs


// compilar: csc List.cs // ejecutar: List <fichero-a-ver> // descripcin: emulado comando TYPE de DOS using System; using System.IO; class List { static void Main (string[] args){ // Verificar que se ha recibido nombre fichero if (args.Length == 0) { Console.WriteLine ("Error: Fichero no encontrado"); return; } // Abre el fichero y visualiza contenido StreamReader reader = null;

Ejemplo de I/O para texto: List.cs


try { reader = new StreamReader (args[0]); for (string line = reader.ReadLine (); line != null; line = reader.ReadLine ()) Console.WriteLine (line); } catch (IOException e) { Console.WriteLine (e.Message); } finally { if (reader != null) reader.Close (); }

}
}

Ejemplo de I/O binario: Scramble.cs


// compilar: csc Scramble.cs // ejecutar: Scramble <nombre-fichero> <clave> // descripcin: encripta un fichero con la clave pasada, // para desencriptar ejecutar el comando de nuevo using System; using System.IO; using System.Text; class Scramble { const int bufsize = 1024; static void Main (string[] args) { // Make sure a file name and encryption key were entered if (args.Length < 2) { Console.WriteLine (Sintaxis: SCRAMBLE nombre-fichero clave"); return; }

Ejemplo de I/O binario: Scramble.cs


string filename = args[0]; string key = args[1]; FileStream stream = null; try { // Abre el fichero para escritura/lectura stream = File.Open (filename, FileMode.Open, FileAccess.ReadWrite); // Crea un FileStream alrededor del reader y writer BinaryReader reader = new BinaryReader (stream); BinaryWriter writer = new BinaryWriter (stream);

// Convierte la clave pasada en un array de bytes ASCIIEncoding enc = new ASCIIEncoding (); byte[] keybytes = enc.GetBytes (key);

Ejemplo de I/O binario: Scramble.cs


// Asignar un bufer de entrada y otro para la clave byte[] buffer = new byte[bufsize]; byte[] keybuf = new byte[bufsize + keybytes.Length - 1]; // Hacer que el tamao de la clave sea el del bufer I/O int count = (1024 + keybytes.Length - 1) / keybytes.Length; for (int i=0; i<count; i++) Array.Copy (keybytes, 0, keybuf, i * keybytes.Length, keybytes.Length); // Leer fichero en bloques de bufsize y aplicar XOR // y escribir el fichero de vuelta long lBytesRemaining = stream.Length; while (lBytesRemaining > 0) { long lPosition = stream.Position; int nBytesRequested = (int) System.Math.Min (bufsize, lBytesRemaining);

Ejemplo de I/O binario: Scramble.cs


int nBytesRead = reader.Read (buffer, 0, nBytesRequested); for (int i=0; i<nBytesRead; i++) buffer[i] ^= keybuf[i]; stream.Seek (lPosition, SeekOrigin.Begin); writer.Write (buffer, 0, nBytesRead); lBytesRemaining -= nBytesRead; } } catch (Exception e) { Console.WriteLine (e.Message); } finally { if (stream != null) stream.Close (); } } }

Colecciones
La plataforma .NET tiene un espacio de nombres dedicado a estructuras de datos como pilas, arrays dinmicos, colas... System.Collections dispone de una serie de interfaces que implementan todas estas colecciones.

Colecciones
Entre otras estructuras podemos encontrar:
ArrayList: Array dinmico. HashTable: Tablas de Hashing. Queue: Colas. SortedList: Listas ordenadas. Stack: Pilas. BitArray: array de bits (guardan booleanos)

Todas las colecciones menos BitArray guardan objetos de tipo System.Object

Ejemplo WordCount
// ejecutar: WordCount <fichero-en-que-contar-palabras> using System; using System.IO; using System.Collections; class WordCount { static void Main (string[] args){ // Validar si se ha introducido un nombre fichero if (args.Length == 0) { Console.WriteLine ("Error: Missing file name"); return; } StreamReader reader = null; Hashtable table = new Hashtable (); // crear mapa

Ejemplo WordCount
try { // Moverse palabra a palabra por el fichero // manteniendo un contador por cada palabra reader = new StreamReader (args[0]); for (string line = reader.ReadLine (); line != null; line = reader.ReadLine ()) { string[] words = GetWords (line); foreach (string word in words) { string iword = word.ToLower (); if (table.ContainsKey (iword)) table[iword] = (int) table[iword] + 1; else table[iword] = 1; // crear entrada } }

Ejemplo WordCount

// Ordenar entradas tabla con SortedList SortedList list = new SortedList (table); // Visualiza los resultados Console.WriteLine ("{0} palabras nicas en {1}", table.Count, args[0]);

foreach (DictionaryEntry entry in list) Console.WriteLine ("{0} ({1})", entry.Key, entry.Value); } catch (Exception e) { Console.WriteLine (e.Message); } finally { if (reader != null) reader.Close (); } }

Ejemplo WordCount
static string[] GetWords (string line) { // Crear un array para guardar resultados intermedios ArrayList al = new ArrayList (); // Aadir palabras desde line a al int i = 0; string word; char[] characters = line.ToCharArray (); while ((word = GetNextWord (line, characters, ref i)) != null) al.Add (word); // Return a static array that is equivalent to the ArrayList string[] words = new string[al.Count]; al.CopyTo (words); return words; }

Ejemplo WordCount
static string GetNextWord (string line, char[] characters, ref int i) { // Encontrar comienzo de palabra while (i < characters.Length && !Char.IsLetterOrDigit (characters[i])) i++; if (i == characters.Length) return null; int start = i; // Find the end of the word while (i < characters.Length && Char.IsLetterOrDigit (characters[i])) i++; // Return the word return line.Substring (start, i - start); }

System.XML
Este espacio de nombres comprende todas las clases necesarias para manejar documentos Xml. Permite leer o parsear un documento, as como escribir un documento Xml. Para ello necesitaremos conocer previamente la estructura de un documento Xml.

System.XML
Este espacio de nombres provee soporte para los
estndares de procesamiento XML:
XML 1.0 - http://www.w3.org/TR/1998/REC-xml-19980210 including DTD support. XML Namespaces - http://www.w3.org/TR/REC-xml-names/ both stream level and DOM. XSD Schemas - http://www.w3.org/2001/XMLSchema XPath expressions - http://www.w3.org/TR/xpath XSLT transformations - http://www.w3.org/TR/xslt DOM Level 1 Core - http://www.w3.org/TR/REC-DOM-Level-1/ DOM Level 2 Core - http://www.w3.org/TR/DOM-Level-2/

Un poco de XML

Lenguaje mundial de facto para intercambio de datos XML no tiene tanto xito porque es un gran lenguaje, sino porque las herramientas disponibles para leer, escribir y manipular XML son muy comunes Casi todos los parseadores de XML implementan una de dos APIs:
DOM: lee un documento en memoria y lo carga en un rbol SAX: API basada en eventos

Ejemplo DOM en .NET


<?xml version=1.0?> <Guitars> <Guitar Image=MySG.jpeg> <Make>Gibson</Make> <Model>SG</Model> <Year>1977</Year> <Color>Tobacco Sunburst</Color> <Neck>Rosewood</Neck> </Guitar> <Guitar Image=MyStrat.jpeg> <Make>Fender</Make> <Model>Stratocaster</Model> <Year>1990</Year> <Color>Black</Color> <Neck>Maple</Neck> </Guitar> </Guitars>

Ejemplo DOM en .NET


using System; using System.Xml;
class MyApp { static void Main () { XmlDocument doc = new XmlDocument (); doc.Load ("Guitars.xml"); XmlNodeList nodes = doc.GetElementsByTagName ("Guitar"); foreach (XmlNode node in nodes) { Console.WriteLine ("{0} {1}", node["Make"].InnerText, node["Model"].InnerText); } } }

XmlDocument
Interfaz programtica para XML documents que conforman con la especificacin DOM Mtodo Load(nombre-doc) procesa el documento y construye un rbol del mismo Una llamada exitosa es normalmente seguida de invocacin a propiedad DocumentElement
Para saber si tiene hijos usar propiedad HasChildNodes Propiedad ChildNodes devuelve los hijos de un nodo
Todo hijo es un XMLNode que puede ser del tipo Element, Text, Attribute, etc.

XmlTextReader
Frente al estndar SAX, .NET ofrece XmlTextReader Est basado en streams como SAX y es por tanto ms eficiente con el uso de memoria que DOM Usa un mecanismo pull para examinar Xml en vez de push como SAX

Ejemplo XmlTextReader I
Lee un fichero XML y visualiza todos sus nodos
<?xml version="1.0"?> <!-- This is a sample XML document --> <!DOCTYPE Items [<!ENTITY number "123">]> <Items> <Item>Test with an entity: &number;</Item> <Item>test with a child element <more/> stuff</Item> <Item>test with a CDATA section <![CDATA[<456>]]> def</Item> <Item>Test with an char entity: &#65;</Item> <!-- Fourteen chars in this element.--> <Item>1234567890ABCD</Item> </Items>

Ejemplo XmlTextReader II
public class Sample { private const String filename = "items.xml"; public static void Main() { XmlTextReader reader = null; try { // Cargar reader con fichero XML ignorando espacios. reader = new XmlTextReader(filename); reader.WhitespaceHandling = WhitespaceHandling.None; // Procesar fichero y visualizar cada nodo while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: Console.Write("<{0}>", reader.Name); break; case XmlNodeType.Text: Console.Write(reader.Value); break; case XmlNodeType.CDATA: Console.Write("<![CDATA[{0}]]>", reader.Value); break;

Ejemplo XmlTextReader III


case XmlNodeType.ProcessingInstruction: Console.Write("<?{0} {1}?>", reader.Name, reader.Value); break; case XmlNodeType.Comment: Console.Write("<!--{0}-->", reader.Value); break; case XmlNodeType.XmlDeclaration: Console.Write("<?xml version='1.0'?>"); break; case XmlNodeType.Document: break; case XmlNodeType.DocumentType: Console.Write("<!DOCTYPE {0} [{1}]", reader.Name, reader.Value); break;

Ejemplo XmlTextReader IV
case XmlNodeType.EntityReference: Console.Write(reader.Name); break; case XmlNodeType.EndElement: Console.Write("</{0}>", reader.Name); break; } } } finally { if (reader!=null) reader.Close(); } } } // Final clase

Transformaciones XSLT
XSLT (Extensible Stylesheet Language Transformations) es un lenguaje para convertir documentos XML de un formato en otro Tiene dos usos principales:
Convertir documentos XML en HTML Convertir documentos XML en otros documentos XML
Este tipo de conversiones son el ncleo de aplicaciones middleware como Microsoft BizTalk Server.

Ejemplo transformacin XSLT


using System; using System.Xml; using System.Xml.XPath; using System.Xml.Xsl; class MyApp { static void Main (string[] args) { if (args.Length < 2) { Console.WriteLine ("Syntax: TRANSFORM xmldoc xsldoc"); return; } try { XslTransform xsl = new XslTransform (); xsl.Load (args[1]);

Ejemplo transformacin XSLT


//Crear un nuevo XPathDocument y cargar el fichero XML a transformar XPathDocument doc = new XPathDocument (args[0]); //Crear un XmlTextWriter que escribe a consola. XmlWriter writer = new XmlTextWriter(Console.Out); xsl.Transform (doc, null, writer, null); } catch (Exception ex) { Console.WriteLine (ex.Message); } }
}

System.Reflection
Este espacio de nombres proporciona clases para:
Conseguir todos los tipos de datos que hay en un ensamblado (System.Reflection.Assembly). Listar los miembros de esos tipos de datos (System.Reflection.Module y System.Type). Invocar mtodos dinmicamente.

Ejemplo System.Reflection
// fichero : reflect.cs // compilar : csc reflect.cs
using System; using System.Reflection; using System.Text.RegularExpressions; public class Persona {

public Persona(string nombre, string apellido1) { Nombre = nombre; Apellido1 = apellido1; }

Ejemplo System.Reflection
public void VerNombre() { Console.WriteLine(Nombre={0}", Nombre); } public void VerApellido1() { Console.WriteLine(Apellido1={0}", Apellido1); } public void VerTodos() { Console.WriteLine("Persona..."); Console.WriteLine(Nombre={0}", Nombre); Console.WriteLine(Apellido1={0}", Apellido1); } public readonly string Nombre; public readonly string Apellido1; }

Ejemplo System.Reflection
public class Reflect { public static void Main() { // recuperar tipo Persona ... Type typ = Type.GetType(Persona"); // crear array con args constructor... object[] args = {Diego", Ipia"}; // crear una instancia de Persona ... Object obj = Activator.CreateInstance(typ, args); // conseguir lista mtodos Persona ... MethodInfo[] met = typ.GetMethods();

Ejemplo System.Reflection
// encontrar e invocar todos los mtodos ver... Regex r = new Regex("^ver", RegexOptions.IgnoreCase); foreach (MethodInfo m in met) if (r.IsMatch(m.Name)) m.Invoke(obj, null); // invocar mtodo ver
} }

System.GC
Esta clase representa al recolector de basura que maneja el CLR de la plataforma. Implementa una serie de mtodos que nos permiten:
Forzar la recoleccin de basura. Evitar que se ejecute el destructor de un objeto determinado.

System.Web y System.Net
System.Net provee clases para llevar a cabo tareas relacionadas con Internet System.Net.Sockets permite la comunicacin a travs de Sockets System.Web, System.Web.Mail y System.Web.Services, estn construidas encima de System.Net

Listando enlaces de pgina web


using System; using System.IO; using System.Net; using System.Text.RegularExpressions; class ListLink { static void Main (string[] args) { if (args.Length == 0) { Console.WriteLine ("Error: Indica URL para listar enlaces"); return; } StreamReader reader = null; try { WebRequest request = WebRequest.Create (args[0]); WebResponse response = request.GetResponse ();

Listando enlaces de pgina web


reader = new StreamReader (response.GetResponseStream ()); string content = reader.ReadToEnd (); Regex regex = new Regex ("href\\s*=\\s*\"([^\"]*)\"", RegexOptions.IgnoreCase); MatchCollection matches = regex.Matches (content); foreach (Match match in matches) Console.WriteLine (match.Groups[1]); } catch (Exception e) { Console.WriteLine (e.Message); } finally { if (reader != null) reader.Close (); } } }

Enviando un mail con .NET


using System.Web.Mail; MailMessage message = new MailMessage (); message.From = Sender.Text; message.To = Receiver.Text; message.Subject = Subject.Text; message.Body = Body.Text; SmtpMail.SmtpServer = "localhost"; SmtpMail.Send (message);

También podría gustarte