Archive for March, 2007

Answers.com Releases Free AnswerTips Tool for Websites and Blogs

5.jpgHTMLPrimer.com

Answers Corporation, creator of Answers.com, began offering its latest webmaster tool, AnswerTips, to websites and blogs. AnswerTips allow sites to provide visitors with instant access to Answers.com’s comprehensive information on four million topics, without having them leave the site or blog.

AnswerTips are a unique site feature and provide instant background information when a site’s visitor double-clicks a word on an “AnswerTips-enabled” site. Activate an AnswerTip, and without leaving the page, a small information bubble opens, providing definitions, explanations, biographies, historical background and countless other types of relevant information. Unlike other offerings, the AnswerTip provides content on the spot, rather than a number of related search links to follow.

The free content in an AnswerTip comes from Answers.com’s extensive database of information consisting of four million topics that are licensed from over 120 authoritative reference publications and other resources.

“It’s about immediate gratification for anyone reading your blog,” said Gil Reich, Vice President of Product Management for Answers Corporation. “Readers get the information they want while remaining engaged in reading your content. Fewer distractions create a better experience on a website, and they save the writer time providing background information on subjects and terminology that his or her audience might be unfamiliar with.”

The technology behind AnswerTips yields a more productive user experience than a simple dictionary site or program. The tool has the ability to crack acronyms, quote stock prices and retrieve biographical information on everyone from rock musicians to political figures. Using patented technology, AnswerTips scans the text surrounding a word to retrieve the most appropriate information. For instance, it can differentiate between ‘Paris Hilton’ and ‘plaster of Paris’ when only the word “Paris” is double-clicked.

Currently, AnswerTips technology has been implemented on Answers.com, WikiAnswers (wiki.answers.com) and CBSNews.com, and was beta tested on a few select blogs and websites, including:

A VC (http://avc.blogs.com/a_vc/2007/02/this_blog_is_an.html) CleverClogs (http://www.cleverclogs.org/2006/12/instant_onsite_.html)

California Polytechnic State University Library ( http://www.library.calpoly.edu)

Write Technology (http://www.writetech.net/2007/02/answer_tips.html)

In addition to being available directly from Answers.com at: (http://www.answers.com/main/answertip_landing.jsp)

AnswerTips are also available within the widget gallery of TypePad at: http://www.sixapart.com/typepad/widgets/publishing-tools/answertips.html.

Other free tools from Answers.com include 1-Click AnswersTM (Windows, Mac OS X), which enables AnswerTips within all of your desktop applications, and the Firefox extension (Windows, Mac OS X and Linux). For more about Answers.com webmaster tools, visit http://www.answers.com/main/webmasters.jsp.

About Answers Corporation

Answers Corporation (NASDAQ: ANSW) operates the award-winning Answers.com(TM) information portal, delivering comprehensive content on four million topics spanning health, finance, entertainment, business and more. Content includes over 120 licensed titles from leading publishers such as Houghton Mifflin Riverdeep Group PLC, Barron’s, Encyclopedia Britannica, All Media Guide and others; original articles written by Answers.com’s editorial team; community-contributed articles from Wikipedia; and user-generated questions & answers from Answers.com’s industry-leading WikiAnswersTM (wiki.answers.com). Founded in 1999 by CEO Bob Rosenschein, Answers.com can be launched directly from within Internet Explorer 7, Firefox and Opera browsers, and its service is integrated into sites like Amazon.com’s A9.com, The New York Public Libraries’ homeworkNYC.org, The New York Times, CBSNews.com and others. Answers.com is also available for mobile devices at mobile.answers.com. For investment information, visit ir.answers.com.

Leave a Comment

Big Business Web Design Disasters

When you think of the world’s most successful businesses, what names come to mind? Most likely, consumer-oriented giants such as Coca-Cola, McDonald’s, Sheraton, Disney, IBM, and General Electric. Not only have they spent billions on advertising to buy their way into your head. They offer convenient products and services that have made them a part of your life.

But when you think of the most successful web sites, what names come to mind? Names like Google, Yahoo! Amazon, AOL, Kazaa (for better or worse), and Hotmail.

The late-1990s mantra about the web being a disruptive technology that would destroy traditional companies may have been overstated. But a decade and a half into the web’s existence, it is clear that the world’s leading corporations have been sidelined on the web.

The biggest shopping site is not walmart.com but amazon.com. The biggest map site is not randmcnally.com but mapquest.com.

Established companies have usually only been able to buy their way into this market through acquisitions (as with Microsoft’s purchase of Hotmail, which it used as a base for creating MSN).

Why, with few exceptions, were the world’s most successful web sites not launched by the world’s most successful corporations?

Many Big Name Companies’ Web Sites a Vast Waste of Time for Visitors

The McDonald’s web site talks about food, but has no real menu. The Coca-Cola USA web site has no clear ingredients list or nutritional information, no recipes for floats or mixed drinks, no company history, and nothing else useful to people who like Coke. All that information has been inexplicably located on the “company” page, which on every other web site is used for investor relations. The Johnson and Johnson web site has useful information if you can access it—when the author attempted to open it, it crashed two different web browsers (Internet Explorer and Mozilla) before finally yielding (to the Opera browser).

Many big-name companies’ web sites offer lessons in what not to do in web design. The biggest lesson by far is not to sacrifice usability in an attempt to look cool, and never forget why your users came to your site in the first place. McDonald’s may be the world’s largest restaurant chain, but it didn’t get that way because of its web site.

Why Big-Budget Websites Are More Often Bombs than Blockbusters

The web sites of many successful corporations (both B2C and B2B) are like big-budget Hollywood movies that spend millions on stars and special effects, and a quarter of a percent of the budget on the script. Worse, the special effects of blockbuster web sites are far more annoying than impressive.

Special Effect that Bombs Number 1: Flash!

When web sites don’t offer any content—any useful information to read—what do they put up there instead? Spinning Coke bottles. Chicken McNuggets and French fries that zoom out toward you when you position your cursor over them. Changing pictures of generic-looking office buildings and men in suits (on the web site of real estate giant CB Richard Ellis—but that essentially describes the generic look of many corporate web sites).

Of course, Flash can be used as a way to present content—words, both printed and recorded, and pictures that actually illustrate something. But more often, it is used to impress. And most often, it ends up annoying. Who wants to spend the better part of a minute waiting for a rotation of generic pictures of smiling models?

Special Effect that Bombs Number 2: Splash Screens

You type in duracell.com expecting information on batteries—which you will find, if you have the patience not to hit the “back” button while the site shows a picture of a battery revolving painfully slowly.

On http://www.mcdonalds.com you’re met with pictures of happy children playing with Ronald McDonald and a menu to select what country you’re from.

Johnson’s and Johnson’s web site shows a logo before automatically redirecting you to the main page—that is if it doesn’t crash your browser first (which happened when the author tried to access the page on May 2, 2004 ).

Another way big consumer corporations’ web sites from Schick to Mercedes-Benz to Thomas Cooke waste your time with splash pages is by making you choose what country you’re visiting from. This could have been detected automatically, or at least, useful worldwide content could have been placed on the homepage, with an option to choose a country prominently displayed.

Splash pages are the internet equivalent of making patrons wait in line out front before letting them inside. Unless a site belongs to a night club or a professional services firm with too much business, keeping people outside can’t be a good idea.

Special Effect that Bombs Number 3: Overbuilt or Badly Built “Dynamic” Functionality

Every web surfer has a story about a shopping cart that malfunctioned just when they were about to click “purchase” on something they really wanted. Or a detailed form that lost all the information after the “submit” button was pressed.

Sometimes, malfunctioning dynamic content can distort the way an entire site presents itself. If the dynamic content is so complex that it presents problems for many users, it is unlikely the dynamic content is worth it. When I visited disney.com in May 2004, my first greeting was a message that your computer is sufficiently up-to-date (or not) to handle the site.

In short, you may want your small or medium-sized business to get as big as Coca Cola or Disney, but you’ll never get there if your website looks like theirs do.

Leave a Comment

The Power OF HTML Email Advertising And When To Use Text Email

The issue of HTML email versus text email usually raises heated debate amongst those involved in email advertising. For some people, feelings about HTML-formatted email have changed over time. However there are a number of issues that one should take into consideration before making a decision either for or against sending HTML email in their advertising campaign.

It may show to be successful way of advertising, but then on the other hand it could be a pain to the ones on the receiving end. To start with, not everybody has the ability to receive HTML Email, which is a very important factor for anybody involved in email advertising to take note of. It is estimated that over 30 per cent of email users are not able to receive HTML Email. HTML may show up unreadable or in non-standard fonts, clashing colours, badly formatted images and sometimes there is no quick or easy way to adjust appearance to be read.

However it is also a fact that this figure is reducing by the day. Still there is no denying the fact that HTML email will always get twice the response rate that text email would usually get, according to Email Marketing research. It is easy to see why this is so. With HTML email, full color graphics and even moving images and graphics can easily be created. These are usually much more attractive and can be powerful in drawing attention to a message.

Also, according to research, it’s mentioned that text just can’t do some of the things that HTML email marketing can, such as the ability to embed links into the email form itself. Yet despite this powerful statistic in support of HTML email, it is also true to say that most times, email users expect most of the HTML email messages they have received to be spam. Many notorious spammers have actually perfected the art of creating flashy HTML graphics to sell whatever it is they are trying to sell in their intrusive and illegal way. There are plenty of other reasons to favor plain text over HTML, such as band width waste and security exploits, but what it really comes down to is that like all other forms of information junk, there is more effort put into the font styling, rather than the actual email content.

Choosing the right Marketing Company is often one of the biggest reasons a campaign fails or succeeds. It is also significant to note that there are some very successful marketers who use nothing else but text email in all their campaigns. They place all their focus on powerful words and directing people to their web sites and blog sites, where color and full HTML can be fully utilized to elaborate further on their advertising messages. The obvious advantage they enjoy is the fact that they do not need to worry about some recipients having turned off all HTML in incoming email messages, which many people often do to deal with the rising volumes of spam.

Leave a Comment

Security Enhancements and Fixes in PHP 5.2.1 and PHP 4.4.5:

  • Fixed possible safe_mode & open_basedir bypasses inside the session extension.
  • Fixed unserialize() abuse on 64 bit systems with certain input strings.
  • Fixed possible overflows and stack corruptions in the session extension.
  • Fixed an underflow inside the internal sapi_header_op() function.
  • Fixed non-validated resource destruction inside the shmop extension.
  • Fixed a possible overflow in the str_replace() function.
  • Fixed possible clobbering of super-globals in several code paths.
  • Fixed a possible information disclosure inside the wddx extension.
  • Fixed a possible string format vulnerability in *print() functions on 64 bit systems.
  • Fixed a possible buffer overflow inside ibase_{delete,add,modify}_user() functions.
  • Fixed a string format vulnerability inside the odbc_result_all() function.

Security Enhancements and Fixes in PHP 5.2.1 only:

  • Prevent search engines from indexing the phpinfo() page.
  • Fixed a number of input processing bugs inside the filter extension.
  • Fixed allocation bugs caused by attempts to allocate negative values in some code paths.
  • Fixed possible stack/buffer overflows inside zip, imap & sqlite extensions.
  • Fixed several possible buffer overflows inside the stream filters.
  • Memory limit is now enabled by default.
  • Added internal heap protection.
  • Extended filter extension support for $_SERVER in CGI and apache2 SAPIs.

Security Enhancements and Fixes in PHP 4.4.5 only:

  • Fixed possible overflows inside zip & imap extensions.
  • Fixed a possible buffer overflow inside mail() function on Windows.
  • Unbundled the ovrimos extension.

The majority of the security vulnerabilities discovered and resolved can in most cases be only abused by local users and cannot be triggered remotely. However, some of the above issues can be triggered remotely in certain situations, or exploited by malicious local users on shared hosting setups utilizing PHP as an Apache module. Therefore, we strongly advise all users of PHP, regardless of the version to upgrade to the 5.2.1 or 4.4.5 releases as soon as possible.

For users upgrading to PHP 5.2 from PHP 5.0 and PHP 5.1, an upgrade guide is available here, detailing the changes between those releases and PHP 5.2.1.

Update: Feb 14th; Added release information for PHP 4.4.5.

Update: Feb 12th; The Windows install package had problems with upgrading from previous PHP versions. That has now been fixed and new file posted in the download section.

Leave a Comment

Open Source Organizations and Affiliations

Google is proud to take part in the following technical and advocacy organizations:

The Eclipse Foundation

Eclipse is an open source community whose projects are focused on providing a vendor-neutral open development platform and application frameworks for building software. The Eclipse Foundation is a not-for-profit corporation formed to advance the creation, evolution, promotion, and support of the Eclipse Platform and to cultivate both an open source community and an ecosystem of complementary products, capabilities, and services.

The Free Software Foundation

The Free Software Foundation (FSF), established in 1985, is dedicated to promoting computer users’ rights to use, study, copy, modify, and redistribute computer programs. The FSF promotes the development and use of Free Software, particularly the GNU operating system, used widely in its GNU/Linux variant. The FSF also helps to spread awareness of the ethical and political issues surrounding freedom in the use of software.

The Java Community Process

Since its introduction in 1998 as the open, participative process to develop and revise the Java technology specifications, reference implementations, and test suites, the Java Community Process (JCP) program has fostered the evolution of the Java platform in cooperation with the international Java developer community.

The Mozilla Foundation

Established in July, 2003, with start-up funds from the Netscape division of AOL, the Mozilla Foundation exists to provide organizational, legal, and financial support for the Mozilla open-source software project. The Foundation has been incorporated as a California not-for-profit corporation to ensure that the Mozilla project continues to exist beyond the participation of individual volunteers, to enable contributions of intellectual property and funds and to provide a vehicle for limiting legal exposure while participating in open-source software projects.

OASIS

OASIS (Organization for the Advancement of Structured Information Standards) is a not-for-profit, international consortium that drives the development, convergence, and adoption of e-business standards. The consortium produces more Web services standards than any other organization, along with standards for security, e-business, and standardization efforts in the public sector and for application-specific markets.

ODF Alliance

The ODF alliance works globally to educate policymakers, IT administrators, and the public on the benefits and opportunities of the OpenDocument Format, to help ensure that government information, records, and documents are fully and natively accessible across platforms and applications, even as technologies change.

OSDL

OSDL – home to Linus Torvalds, the creator of Linux – is dedicated to accelerating the growth and adoption of Linux in the enterprise. Founded in 2000 and supported by a global consortium of IT industry leaders, OSDL is a non-profit organization that provides state-of the-art computing and test facilities in the United States and Japan available to developers around the world. OSDL’s founding members were IBM, HP, CA, Intel, and NEC.

Python Software Foundation

The Python Software Foundation (PSF) is a non-profit membership organization devoted to advancing open source technology related to the Python programming language. It qualifies under the US Internal Revenue Code as a tax-exempt 501(c)(3) scientific and educational public charity, and conducts its business according to the rules for such organizations.

Leave a Comment

5. Consultas de Acción

Las consultas de acción son aquellas que no devuelven ningún registro, son las encargadas de acciones como añadir y borrar y modificar registros.

5.1    DELETE

Crea una consulta de eliminación que elimina los registros de una o más de las tablas listadas en la cláusula FROM que satisfagan la cláusula WHERE. Esta consulta elimina los registros completos, no es posible eliminar el contenido de algún campo en concreto. Su sintaxis es:

    DELETE Tabla.* FROM Tabla WHERE criterio

DELETE es especialmente útil cuando se desea eliminar varios registros. En una instrucción DELETE con múltiples tablas, debe incluir el nombre de tabla (Tabla.*). Si especifica más de una tabla desde la que eliminar registros, todas deben ser tablas de muchos a uno. Si desea eliminar todos los registros de una tabla, eliminar la propia tabla es más eficiente que ejecutar una consulta de borrado.

Se puede utilizar DELETE para eliminar registros de una única tabla o desde varios lados de una relación uno a muchos. Las operaciones de eliminación en cascada en una consulta únicamente eliminan desde varios lados de una relación. Por ejemplo, en la relación entre las tablas Clientes y Pedidos, la tabla Pedidos es la parte de muchos por lo que las operaciones en cascada solo afectaran a la tabla Pedidos. Una consulta de borrado elimina los registros completos, no únicamente los datos en campos específicos. Si desea eliminar valores en un campo especificado, crear una consulta de actualización que cambie los valores a Null.

Una vez que se han eliminado los registros utilizando una consulta de borrado, no puede deshacer la operación. Si desea saber qué registros se eliminarán, primero examine los resultados de una consulta de selección que utilice el mismo criterio y después ejecute la consulta de borrado. Mantenga copias de seguridad de sus datos en todo momento. Si elimina los registros equivocados podrá recuperarlos desde las copias de seguridad.

    DELETE * FROM Empleados WHERE Cargo = ‘Vendedor’;

5.2    INSERT INTO

Agrega un registro en una tabla. Se la conoce como una consulta de datos añadidos. Esta consulta puede ser de dos tipo: Insertar un único registro ó Insertar en una tabla los registros contenidos en otra tabla.

5.2.1    Para insertar un único Registro:

En este caso la sintaxis es la siguiente:

    INSERT INTO Tabla (campo1, campo2, .., campoN)
    VALUES (valor1, valor2, …, valorN)

Esta consulta graba en el campo1 el valor1, en el campo2 y valor2 y así sucesivamente. Hay que prestar especial atención a acotar entre comillas simples (‘) los valores literales (cadenas de caracteres) y las fechas indicarlas en formato mm-dd-aa y entre caracteres de almohadillas (#).

5.2.2    Para insertar Registros de otra Tabla:

En este caso la sintaxis es:

    INSERT INTO Tabla [IN base_externa] (campo1, campo2, …, campoN)
    SELECT TablaOrigen.campo1, TablaOrigen.campo2, …, TablaOrigen.campoN
    FROM TablaOrigen

En este caso se seleccionarán los campos 1,2, …, n dela tabla origen y se grabarán en los campos 1,2,.., n de la Tabla. La condición SELECT puede incluir la cláusula WHERE para filtrar los registros a copiar. Si Tabla y TablaOrigen poseen la misma estrucutra podemos simplificar la sintaxis a:

    INSERT INTO Tabla  SELECT TablaOrigen.* FROM TablaOrigen

De esta forma los campos de TablaOrigen se grabarán en Tabla, para realizar esta operación es necesario que todos los campos de TablaOrigen estén contenidos con igual nombre en Tabla. Con otras palabras que Tabla posea todos los campos de TablaOrigen (igual nombre e igual tipo).

En este tipo de consulta hay que tener especial atención con los campos contadores o autonuméricos puesto que al insertar un valor en un campo de este tipo se escribe el valor que contenga su campo homólogo en la tabla origen, no incrementandose como le corresponde.

Se puede utilizar la instrucción INSERT INTO para agregar un registro único a una tabla, utilizando la sintaxis de la consulta de adición de registro único tal y como se mostró anteriormente. En este caso, su código específica el nombre y el valor de cada campo del registro. Debe especificar cada uno de los campos del registro al que se le va a asignar un valor así como el valor para dicho campo. Cuando no se especifica dicho campo, se inserta el valor predeterminado o Null. Los registros se agregan al final de la tabla.

También se puede utilizar INSERT INTO para agregar un conjunto de registros pertenecientes a otra tabla o consulta utilizando la cláusula SELECT … FROM como se mostró anteriormente en la sintaxis de la consulta de adición de múltiples registros. En este caso la cláusula SELECT especifica los campos que se van a agregar en la tabla destino especificada.

La tabla destino u origen puede especificar una tabla o una consulta.

Si la tabla destino contiene una clave principal, hay que segurarse que es única, y con valores no-Null ; si no es así, no se agregarán los registros. Si se agregan registros a una tabla con un campo Contador , no se debe incluir el campo Contador en la consulta. Se puede emplear la cláusula IN para agregar registros a una tabla en otra base de datos.

Se pueden averiguar los registros que se agregarán en la consulta ejecutando primero una consulta de selección que utilice el mismo criterio de selección y ver el resultado. Una consulta de adición copia los registros de una o más tablas en otra. Las tablas que contienen los registros que se van a agregar no se verán afectadas por la consulta de adición. En lugar de agregar registros existentes en otra tabla, se puede especificar los valores de cada campo en un nuevo registro utilizando la cláusula VALUES. Si se omite la lista de campos, la cláusula VALUES debe incluir un valor para cada campo de la tabla, de otra forma fallará INSERT.

    INSERT INTO Clientes SELECT Clientes_Viejos.* FROM Clientes_Nuevos;
    INSERT INTO Empleados (Nombre, Apellido, Cargo)
    VALUES (‘Luis’, ‘Sánchez’, ‘Becario’);

    INSERT INTO Empleados SELECT Vendedores.* FROM Vendedores
    WHERE Fecha_Contratacion < Now() – 30;
 
5.3    UPDATE

Crea una consulta de actualización que cambia los valores de los campos de una tabla especificada basándose en un criterio específico. Su sintaxis es:

    UPDATE Tabla SET Campo1=Valor1, Campo2=Valor2, … CampoN=ValorN
    WHERE Criterio;

UPDATE es especialmente útil cuando se desea cambiar un gran número de registros o cuando éstos se encuentran en múltiples tablas. Puede cambiar varios campos a la vez. El ejemplo siguiente incrementa los valores Cantidad pedidos en un 10 por ciento y los valores Transporte en un 3 por ciento para aquellos que se hayan enviado al Reino Unido.:

    UPDATE Pedidos SET Pedido = Pedidos * 1.1, Transporte = Transporte * 1.03
    WHERE PaisEnvío = ‘ES’;

UPDATE no genera ningún resultado. Para saber qué registros se van a cambiar, hay que examinar primero el resultado de una consulta de selección que utilice el mismo criterio y después ejecutar la consulta de actualización.

    UPDATE Empleados SET Grado = 5 WHERE Grado = 2;
    UPDATE Productos SET Precio = Precio  * 1.1 WHERE Proveedor = 8 AND Familia = 3;

Si en una consulta de actualización suprimimos la cláusula WHERE todos los registros de la tabla señalada serán actualizados.

    UPDATE Empleados SET Salario = Salario * 1.1

6. Tipos de DatosLos tipos de datos SQL se clasifican en 13 tipos de datos primarios y de varios sinónimos válidos reconocidos por dichos tipos de datos.

Tipos de datos primarios:
 

Tipo de Datos Longitud Descripción
BINARY 1 byte Para consultas sobre tabla adjunta de productos de bases de datos que definen un tipo de datos Binario. 
BIT 1 byte Valores Si/No ó True/False 
BYTE 1 byte Un valor entero entre 0 y 255.
COUNTER 4 bytes Un número incrementado automáticamente (de tipo Long)
CURRENCY 8 bytes Un entero escalable entre 922.337.203.685.477,5808 y 922.337.203.685.477,5807.
DATETIME 8 bytes Un valor de fecha u hora entre los años 100 y 9999.
SINGLE 4 bytes Un valor en punto flotante de precisión simple con un rango de -3.402823*1038 a -1.401298*10-45 para valores negativos, 1.401298*10-45 a 3.402823*1038 para valores positivos, y 0.
DOUBLE 8 bytes Un valor en punto flotante de doble precisión con un rango de -1.79769313486232*10308 a -4.94065645841247*10-324 para valores negativos, 4.94065645841247*10-324 a 1.79769313486232*10308 para valores positivos, y 0.
SHORT 2 bytes Un entero corto entre -32,768 y 32,767.
LONG 4 bytes Un entero largo entre -2,147,483,648 y 2,147,483,647.
LONGTEXT 1 byte por carácter De cero a un máximo de 1.2 gigabytes.
LONGBINARY Según se necesite De cero 1 gigabyte.  Utilizado para objetos OLE.
TEXT 1 byte por caracter De cero a 255 caracteres. 

La siguiente tabla recoge los sinonimos de los tipos de datos definidos:
 
 

Tipo de Dato Sinónimos
BINARY VARBINARY
BIT BOOLEAN 
LOGICAL 
LOGICAL1 
YESNO
BYTE INTEGER1
COUNTER AUTOINCREMENT
CURRENCY MONEY
DATETIME DATE 
TIME 
TIMESTAMP
SINGLE FLOAT4 
IEEESINGLE 
REAL
DOUBLE FLOAT 
FLOAT8 
IEEEDOUBLE 
NUMBER 
NUMERIC
SHORT INTEGER2 
SMALLINT
LONG INT 
INTEGER 
INTEGER4
LONGBINARY GENERAL 
OLEOBJECT
LONGTEXT LONGCHAR 
MEMO 
NOTE
TEXT ALPHANUMERIC 
CHAR 
CHARACTER 
STRING 
VARCHAR
VARIANT (No Admitido) VALUE

Leave a Comment

3. Criterios de Selección

 En el capítulo anterior se vio la forma de recuperar los registros de las tablas, las formas empleadas devolvían todos los registros de la mencionada tabla. A lo largo de este capítulo se estudiarán las posibilidades de filtrar los registros con el fin de recuperar solamente aquellos que cumplan una condiciones preestablecidas.

Antes de comenzar el desarrollo de este capítulo hay que recalcar tres detalles de vital importancia. El primero de ellos es que cada vez que se desee establecer una condición referida a un campo de texto la condición de búsqueda debe ir encerrada entre comillas simples; la segunda es que no se posible establecer condiciones de búsqueda en los campos memo y; la tercera y última hace referencia a las fechas. Las fechas se deben escribir siempre en formato mm-dd-aa en donde mm representa el mes, dd el día y aa el año, hay que prestar atención a los separadores -no sirve la separación habitual de la barra (/), hay que utilizar el guión (-) y además la fecha debe ir encerrada entre almohadillas (#). Por ejemplo si deseamos referirnos al día 3 de Septiembre de 1995 deberemos hacerlo de la siguente forma; #09-03-95# ó #9-3-95#.

3.1 Operadores Lógicos

Los operadores lógicos soportados por SQL son: AND, OR, XOR, Eqv, Imp, Is y Not. A excepción de los dos últimos todos poseen la siguiente sintaxis:

    <expresión1>    operador    <expresión2>

En donde expresión1 y expresión2 son las condiciones a evaluar, el resultado de la operación varía en función del operador lógico. La tabla adjunta muestra los diferentes posibles resultados:
   

<expresión1> Operador <expresión2> Resultado

Verdad

AND

Falso

Falso

Verdad

AND

Verdad

Verdad

Falso AND Verdad Falso
Falso AND Falso Falso
Verdad OR Falso Verdad
Verdad OR Verdad Verdad
Falso OR Verdad Verdad
Falso OR Falso Falso
Verdad XOR Verdad Falso
Verdad XOR Falso Verdad
Falso XOR Verdad Verdad
Falso XOR Falso Falso
Verdad Eqv Verdad Verdad
Verdad Eqv Falso Falso
Falso Eqv Verdad Falso
Falso Eqv Falso Verdad
Verdad Imp Verdad Verdad
Verdad Imp Falso Falso
Verdad Imp Null Null
Falso Imp Verdad Verdad
Falso Imp Falso Verdad
Falso Imp Null Verdad
Null Imp Verdad Verdad
Null Imp Falso Null
Null Imp Null Null

Si a cualquiera de las anteriores condiciones le anteponemos el operador NOT el resultado de la operación será el contrario al devuelto sin el operador NOT.

El último operador denominado Is se emplea para comparar dos variables de tipo objeto <Objeto1> Is <Objeto2>. este operador devuelve verdad si los dos objetos son iguales

    SELECT * FROM Empleados WHERE Edad > 25 AND Edad < 50;
    SELECT * FROM Empleados WHERE (Edad > 25 AND Edad < 50) OR Sueldo = 100;
    SELECT * FROM Empleados WHERE NOT Estado = ‘Soltero’;
    SELECT * FROM Empleados WHERE (Sueldo > 100 AND Sueldo < 500) OR
    (Provincia = ‘Madrid’ AND Estado = ‘Casado’);

3.2 Intervalos de Valores

Para indicar que deseamos recuperar los registros según el intervalo de valores de un campo emplearemos el operador Between cuya sintaxis es:

    campo [Not] Between valor1 And valor2 (la condición Not es opcional)

En este caso la consulta devolvería los registros que contengan en “campo” un valor incluido en el intervalo valor1, valor2 (ambos inclusive). Si anteponemos la condición Not devolverá aquellos valores no incluidos en el intervalo.

    SELECT * FROM Pedidos WHERE CodPostal Between 28000 And 28999;
    (Devuelve los pedidos realizados en la provincia de Madrid)

    SELECT IIf(CodPostal Between 28000 And 28999, ‘Provincial’, ‘Nacional’)
    FROM Editores;
    (Devuelve el valor ‘Provincial’ si el código postal se encuentra en el intervalo,
    ‘Nacional’ en caso contrario)

3.3 El Operador Like

Se utiliza para comparar una expresión de cadena con un modelo en una expresión SQL. Su sintaxis es:

    expresión Like modelo

En donde expresión es una cadena modelo o campo contra el que se compara expresión. Se puede utilizar el operador Like para encontrar valores en los campos que coincidan con el modelo especificado. Por modelo puede especificar un valor completo (Ana María), o se pueden utilizar caracteres comodín como los reconocidos por el sistema operativo para encontrar un rango de valores (Like An*).

El operador Like se puede utilizar en una expresión para comparar un valor de un campo con una expresión de cadena. Por ejemplo, si introduce Like C* en una consulta SQL, la consulta devuelve todos los valores de campo que comiencen por la letra C. En una consulta con parámetros, puede hacer que el usuario escriba el modelo que se va a utilizar.

El ejemplo siguiente devuelve los datos que comienzan con la letra P seguido de cualquier letra entre A y F y de tres dígitos:

    Like ‘P[A-F]###’

Este ejemplo devuelve los campos cuyo contenido empiece con una letra de la A a la D seguidas de cualquier cadena.

    Like ‘[A-D]*’

En la tabla siguiente se muestra cómo utilizar el operador Like para comprobar
expresiones con diferentes modelos.
 
 

Tipo de coincidencia Modelo Planteado Coincide No coincide
Varios caracteres ‘a*a’ ‘aa’, ‘aBa’, ‘aBBBa’ ‘aBC’
Carácter especial  ’a[*]a’ ‘a*a’ ‘aaa’
Varios caracteres ‘ab*’ ‘abcdefg’, ‘abc’ ‘cab’, ‘aab’
Un solo carácter ‘a?a’ ‘aaa’, ‘a3a’, ‘aBa’ ‘aBBBa’
Un solo dígito ‘a#a’ ‘a0a’, ‘a1a’, ‘a2a’ ‘aaa’, ‘a10a’
Rango de caracteres ‘[a-z]‘ ‘f’, ‘p’, ‘j’ ‘2′, ‘&’
Fuera de un rango ‘[!a-z]‘ ‘9′, ‘&’, ‘%’ ‘b’, ‘a’
Distinto de un dígito ‘[!0-9]‘ ‘A’, ‘a’, ‘&’, ‘~’ ‘0′, ‘1′, ‘9′
Combinada ‘a[!b-m]#’ ‘An9′, ‘az0′, ‘a99′ ‘abc’, ‘aj0′

3.4 El Operador In

Este operador devuelve aquellos registros cuyo campo indicado coincide con alguno de los en una lista. Su sintaxis es:

    expresión [Not] In(valor1, valor2, . . .)

    SELECT * FROM Pedidos WHERE Provincia In (‘Madrid’, ‘Barcelona’, ‘Sevilla’);
 

3.5 La cláusula WHERE
 
La cláusula WHERE puede usarse para determinar qué registros de las tablas enumeradas en la cláusula FROM aparecerán en los resultados de la instrucción SELECT. Depués de escribir esta cláusula se deben especificar las condiciones expuestas en los partados 3.1 y 3.2. Si no se emplea esta cláusula, la consulta devolverá todas las filas de la tabla. WHERE es opcional, pero cuando aparece debe ir a continuación de FROM.

    SELECT Apellidos, Salario FROM Empleados WHERE Salario > 21000;

    SELECT Id_Producto, Existencias FROM Productos
    WHERE Existencias <= Nuevo_Pedido;

    SELECT * FROM Pedidos WHERE Fecha_Envio = #5/10/94#;

    SELECT Apellidos, Nombre FROM Empleados WHERE Apellidos = ‘King’;

    SELECT Apellidos, Nombre FROM Empleados WHERE Apellidos Like ‘S*’;

    SELECT Apellidos, Salario FROM Empleados WHERE Salario Between 200 And 300;

    SELECT Apellidos, Salario FROM Empl WHERE Apellidos Between ‘Lon’ And ‘Tol’;

    SELECT Id_Pedido, Fecha_Pedido FROM Pedidos WHERE Fecha_Pedido
    Between #1-1-94# And  #30-6-94#;

    SELECT Apellidos, Nombre, Ciudad FROM Empleados WHERE Ciudad
    In (‘Sevilla’, ‘Los Angeles’, ‘Barcelona’);
 

4.    Agrupamiento de Registros

4.1    GROUP BY Combina los registros con valores idénticos, en la lista de campos especificados, en un único registro. Para cada registro se crea un valor sumario si se incluye una función SQL agregada, como por ejemplo Sum o Count, en la instrucción SELECT. Su sintaxis es:

    SELECT campos FROM tabla WHERE criterio GROUP BY campos del grupo

GROUP BY es opcional.  Los valores de resumen se omiten si no existe una función SQL agregada en la instrucción SELECT. Los valores Null en los campos GROUP BY se agrupan y no se omiten. No obstante, los valores Null no se evalúan en ninguna de las funciones SQL agregadas.

Se utiliza la cláusula WHERE para excluir aquellas filas que no desea agrupar, y la cláusula HAVING para filtrar los registros una vez agrupados.

A menos que contenga un dato Memo u Objeto OLE , un campo de la lista de campos GROUP BY puede referirse a cualquier campo de las tablas que aparecen en la cláusula FROM, incluso si el campo no esta incluido en la instrucción SELECT, siempre y cuando la instrucción SELECT incluya al menos una función SQL agregada.

Todos los campos de la lista de campos de SELECT deben o bien incluirse en la cláusula GROUP BY o como argumentos de una función SQL agregada.

    SELECT Id_Familia, Sum(Stock) FROM Productos GROUP BY Id_Familia;

Una vez que GROUP BY ha combinado los registros, HAVING muestra cualquier registro agrupado por la cláusula GROUP BY que satisfaga las condiciones de la cláusula HAVING.

HAVING es similar a WHERE, determina qué registros se seleccionan. Una vez que los registros se han agrupado utilizando GROUP BY, HAVING determina cuales de ellos se van a mostrar.

    SELECT Id_Familia Sum(Stock) FROM Productos GROUP BY Id_Familia
    HAVING Sum(Stock) > 100 AND NombreProducto Like BOS*;

4.2    AVG

Calcula la media aritmética de un conjunto de valores contenidos en un campo especificado de una consulta. Su sintaxis es la siguiente

    Avg(expr)

En donde expr representa  el campo que contiene los datos numéricos para los que se desea calcular la media o una expresión que realiza un cálculo utilizando los datos de dicho campo. La media calculada por Avg es la media aritmética (la suma de los valores dividido por el número de valores). La función Avg no incluye ningún campo Null en el cálculo.

    SELECT Avg(Gastos) AS Promedio FROM Pedidos WHERE Gastos > 100;

4.3    Count

Calcula el número de registros devueltos por una consulta. Su sintaxis es la siguiente

    Count(expr)

En donde expr contiene el nombre del campo que desea contar. Los operandos de expr pueden incluir el nombre de un campo de una tabla, una constante o una función (la cual puede ser intrínseca o definida por el usuario pero no otras de las funciones agregadas de SQL). Puede contar cualquier tipo de datos incluso texto.

Aunque expr puede realizar un cálculo sobre un campo, Count simplemente cuenta el número de registros sin tener en cuenta qué valores se almacenan en los registros. La función Count no cuenta los registros que tienen campos null a menos que expr sea el carácter comodín asterisco (*). Si utiliza un asterisco, Count calcula el número total de registros, incluyendo aquellos que contienen campos null. Count(*) es considerablemente más rápida que Count(Campo). No se debe poner el asterisco entre dobles comillas (‘*’).

    SELECT Count(*) AS Total  FROM Pedidos;

Si expr identifica a múltiples campos, la función Count cuenta un registro sólo si al menos uno de los campos no es Null. Si todos los campos especificados son Null, no se cuenta el registro. Hay que separar los nombres de los campos con ampersand (&).

    SELECT Count(FechaEnvío & Transporte) AS Total FROM Pedidos;

4.4    Max, Min

Devuelven el mínimo o el máximo de un conjunto de valores contenidos en un campo especifico de una consulta. Su sintaxis es:

    Min(expr)
    Max(expr)

En donde expr es el campo sobre el que se desea realizar el cálculo. Expr pueden incluir el nombre de un campo de una tabla, una constante o una función (la cual puede ser intrínseca o definida por el usuario pero no otras de las funciones agregadas de SQL).

    SELECT Min(Gastos) AS ElMin FROM Pedidos WHERE Pais = ‘España’;
    SELECT Max(Gastos) AS ElMax FROM Pedidos WHERE Pais  = ‘España’;

4.5    StDev, StDevP

Devuelve estimaciones de la desviación estándar para la población (el total de los registros de la tabla) o una muestra de la población representada (muestra aleatoria) . Su sintaxis es:

    StDev(expr)
    StDevP(expr)

En donde expr representa el nombre del campo que contiene los datos que desean evaluarse o una expresión que realiza un cálculo utilizando los datos de dichos campos. Los operandos de expr pueden incluir el nombre de un campo de una tabla, una constante o una función (la cual puede ser intrínseca o definida por el usuario pero no otras de las funciones agregadas de SQL)

StDevP evalúa una población, y StDev evalúa una muestra de la población. Si la consulta contiene menos de dos registros (o ningún registro para StDevP), estas funciones devuelven un valor Null (el cual indica que la desviación estándar no puede calcularse).

    SELECT StDev(Gastos) AS Desviacion FROM Pedidos WHERE Pais = ‘España’;
    SELECT StDevP(Gastos) AS Desviacion FROM Pedidos WHERE Pais= ‘España’;

4.6    Sum

Devuelve la suma del conjunto de valores contenido en un campo especifico de una consulta. Su sintaxis es:

    Sum(expr)

En donde expr respresenta el nombre del campo que contiene los datos que desean sumarse o una expresión que realiza un cálculo utilizando los datos de dichos campos. Los operandos de expr pueden incluir el nombre de un campo de una tabla, una constante o una función (la cual puede ser intrínseca o definida por el usuario pero no otras de las funciones agregadas de SQL).

    SELECT Sum(PrecioUnidad * Cantidad) AS Total FROM DetallePedido;

4.7    Var, VarP
 
Devuelve una estimación de la varianza de una población (sobre el total de los registros) o una muestra de la población (muestra aleatoria de registros) sobre los valores de un campo. Su sintaxis es:

    Var(expr)
    VarP(expr)

VarP evalúa una población, y Var evalúa una muestra de la población. Expr el nombre del campo que contiene los datos que desean evaluarse o una expresión que realiza un cálculo utilizando los datos de dichos campos. Los operandos de expr pueden incluir el nombre de un campo de una tabla, una constante o una función (la cual puede ser intrínseca o definida por el usuario pero no otras de las funciones agregadas de SQL)

Si la consulta contiene menos de dos registros, Var y VarP devuelven Null (esto indica que la varianza no puede calcularse). Puede utilizar Var y VarP en una expresión de consulta o en una Instrucción SQL.

    SELECT Var(Gastos) AS Varianza FROM Pedidos WHERE Pais = ‘España’;
    SELECT VarP(Gastos) AS Varianza FROM Pedidos WHERE Pais = ‘España’;
 

Leave a Comment

Tutorial de SQL

1.- INTRODUCCION

El lenguaje de consulta estructurado (SQL) es un lenguaje de base de datos normalizado, utilizado por el motor de base de datos de Microsoft Jet. SQL se utiliza para crear objetos QueryDef, como el argumento de origen del método OpenRecordSet y como la propiedad RecordSource del control de datos. También se puede utilizar con el método Execute para crear y manipular directamente las bases de datos Jet y crear consultas SQL de paso a través para manipular bases de datos remotas cliente – servidor. 1.1. Componentes del SQL

El lenguaje SQL está compuesto por comandos, cláusulas, operadores y funciones de agregado. Estos elementos se combinan en las instrucciones para crear, actualizar y manipular las bases de datos. 1.2 Comandos

Existen dos tipos de comandos SQL:
 

  • los DLL que permiten crear y definir nuevas bases de datos, campos e índices.
  • los DML que permiten generar consultas para ordenar, filtrar y extraer datos de la base de datos.

 

Comando

Descripción

CREATE Utilizado para crear nuevas tablas, campos e índices
DROP Empleado para eliminar tablas e índices
ALTER Utilizado para modificar las tablas agregando campos o cambiando la definición de los campos.


 

Comando

Descripción

SELECT Utilizado para consultar registros de la base de datos que satisfagan un criterio determinado
INSERT Utilizado para cargar lotes de datos en la base de datos en una única operación.
UPDATE Utilizado para modificar los valores de los campos y registros especificados
DELETE Utilizado para eliminar registros de una tabla de una base de datos

1.3 Cláusulas Las cláusulas son condiciones de modificación utilizadas para definir los datos que desea seleccionar o manipular.
 

Cláusula

Descripción

FROM Utilizada para especificar la tabla de la cual se van a seleccionar los registros
WHERE Utilizada para especificar las condiciones que deben reunir los registros que se van a seleccionar
GROUP BY Utilizada para separar los registros seleccionados en grupos específicos
HAVING Utilizada para expresar la condición que debe satisfacer cada grupo
ORDER BY Utilizada para ordenar los registros seleccionados de acuerdo con un orden específico

1.4 Operadores Lógicos
 

Operador

Uso

AND Es el “y” lógico. Evalua dos condiciones y devuelve un valor de verdad sólo si ambas son ciertas.
OR Es el “o” lógico. Evalúa dos condiciones y devuelve un valor de verdar si alguna de las dos es cierta.
NOT Negación lógica. Devuelve el valor contrario de la expresión.

1.5 Operadores de Comparación
 

Operador

Uso

< Menor que
> Mayor que
<> Distinto de
<= Menor ó Igual que
>= Mayor ó Igual que
= Igual que
BETWEEN Utilizado para especificar un intervalo de valores.
LIKE Utilizado en la comparación de un modelo
In Utilizado para especificar registros de una base de datos 
 

1.6 Funciones de Agregado Las funciones de agregado se usan dentro de una cláusula SELECT en grupos de registros para devolver un único valor que se aplica a un grupo de registros.
 
 

Función

Descripción

AVG Utilizada para calcular el promedio de los valores de un campo determinado 
COUNT Utilizada para devolver el número de registros de la selección 
SUM Utilizada para devolver la suma de todos los valores de un campo determinado 
MAX Utilizada para devolver el valor más alto de un campo especificado 
MIN Utilizada para devolver el valor más bajo de un campo especificado 

 2. Consultas de SelecciónLas consultas de selección se utilizan para indicar al motor de datos que devuelva información de las bases de datos, esta información es devuelta en forma de conjunto de registros que se pueden almacenar en un objeto recordset. Este conjunto de registros es modificable.

2.1 Consultas básicas

La sintaxis básica de una consulta de selección es la siguiente:

        SELECT Campos FROM Tabla;

En donde campos es la lista de campos que se deseen recuperar y tabla es el origen de los mismos, por ejemplo:

        SELECT Nombre, Telefono FROM Clientes;

Esta consulta devuelve un recordset con el campo nombre y teléfono de la tabla clientes.

2.2 Ordenar los registros

Adicionalmente se puede especificar el orden en que se desean recuperar los registros de las tablas mediante la claúsula ORDER BY Lista de Campos. En donde Lista de campos representa los campos a ordenar. Ejemplo:

        SELECT CodigoPostal, Nombre, Telefono FROM Clientes ORDER BY Nombre;

Esta consulta devuelve los campos CodigoPostal, Nombre, Telefono de la tabla Clientes ordenados por el campo Nombre.

Se pueden ordenar los registros por mas de un campo, como por ejemplo:

        SELECT CodigoPostal, Nombre, Telefono FROM Clientes ORDER BY
        CodigoPostal, Nombre;

Incluso se puede especificar el orden de los registros: ascendente mediante la claúsula (ASC -se toma este valor por defecto) ó descendente (DESC)

        SELECT CodigoPostal, Nombre, Telefono FROM Clientes ORDER BY
        CodigoPostal DESC , Nombre ASC;

2.3 Consultas con Predicado

El predicado se incluye entre la claúsula y el primer nombre del campo a recuperar, los posibles predicados son:
 
 

Predicado Descripción
ALL Devuelve todos los campos de la tabla
TOP Devuelve un determinado número de registros de la tabla
DISTINCT Omite los registros cuyos campos seleccionados coincidan totalmente
DISTINCTROW Omite los registros duplicados basandose en la totalidad del registro y no sólo en los campos seleccionados.

ALL

Si no se incluye ninguno de los predicados se asume ALL. El Motor de base de datos  selecciona todos los registros que cumplen las condiciones de la instrucción SQL. No se conveniente abusar de este predicado ya que obligamos al motor de la base de datos a analizar la estructura de la tabla para averiguar los campos que contiene, es mucho más rápido indicar el listado de campos deseados.

    SELECT ALL FROM Empleados;
    SELECT * FROM Empleados;
 
TOP

Devuelve un cierto número de registros que entran entre al principio o al final de un rango especificado por una cláusula ORDER BY. Supongamos que queremos recuperar los nombres de los 25 primeros estudiantes del curso 1994:

    SELECT TOP 25 Nombre, Apellido FROM Estudiantes
    ORDER BY Nota DESC;

Si no se incluye la cláusula ORDER BY, la consulta devolverá un conjunto arbitrario de 25 registros de la tabla Estudiantes .El predicado TOP no elige entre valores iguales. En el ejemplo anterior, si la nota media número 25 y la 26 son iguales, la consulta devolverá 26 registros. Se puede utilizar la palabra reservada PERCENT para devolver un cierto porcentaje de registros que caen al principio o al final de un rango especificado por la cláusula ORDER BY. Supongamos que en lugar de los 25 primeros estudiantes deseamos el 10 por ciento del curso:

    SELECT TOP 10 PERCENT Nombre, Apellido FROM Estudiantes
    ORDER BY Nota DESC;

El valor que va a continuación de TOP debe ser un Integer sin signo.TOP no afecta a la posible actualización de la consulta.

DISTINCT

Omite los registros que contienen datos duplicados en los campos seleccionados. Para que los valores de cada campo listado en la instrucción SELECT se incluyan en la consulta deben ser únicos.

Por ejemplo, varios empleados listados en la tabla Empleados pueden tener el mismo apellido. Si dos registros contienen López en el campo Apellido, la siguiente instrucción SQL devuelve un único registro:

    SELECT DISTINCT Apellido FROM Empleados;

Con otras palabras el predicado DISTINCT devuelve aquellos registros cuyos campos indicados en la cláusula SELECT posean un contenido diferente. El resultado de una consulta que utiliza DISTINCT no es actualizable y no refleja los cambios subsiguientes realizados por otros usuarios.

DISTINCTROW

Devuelve los registros diferentes de una tabla; a diferencia del predicado anterior que sólo se fijaba en el contenido de los campos seleccionados, éste lo hace en el contenido del registro completo independientemente de los campo indicados en la cláusula SELECT.
 

    SELECT DISTINCTROW Apellido FROM Empleados;

Si la tabla empleados contiene dos registros: Antonio López y Marta López el ejemplo del predicado DISTINCT devuleve un único registro con el valor López en el campo Apellido ya que busca no duplicados en dicho campo. Este último ejemplo devuelve dos registros con el valor López en el apellido ya que se buscan no duplicados en el registro completo.
 
2.4 Alias

En determinadas circunstancias es necesario asignar un nombre a alguna columna determinada de un conjunto devuelto, otras veces por simple capricho o por otras circunstancias. Para resolver todas ellas tenemos la palabra reservada AS que se encarga de asignar el nombre que deseamos a la columna deseada. Tomado como referencia el ejemplo anterior podemos hacer que la columna devuelta por la consulta, en lugar de llamarse apellido (igual que el campo devuelto) se llame Empleado. En este caso procederíamos de la siguiente forma:

    SELECT DISTINCTROW Apellido AS Empleado FROM Empleados;

2.5 Recuperar Información de una base de Datos Externa

Para concluir este capítulo se debe hacer referencia a la recuperación de registros de bases de datos externa. Es ocasiones es necesario la recuperación de información que se encuentra contenida en una tabla que no se encuentra en la base de datos que ejecutará la consulta o que en ese momento no se encuentra abierta, esta situación la podemos salvar con la palabra reservada IN de la siguiente forma:

    SELECT DISTINCTROW Apellido AS Empleado FROM Empleados
    IN ‘c:\databases\gestion.mdb’;

En donde c:\databases\gestion.mdb es la base de datos que contiene la tabla Empleados.
 

 

 

Leave a Comment

The .NET Framework Architecture Part 2

Just-In-Time (JIT) compilation

As stated above, the Just in time compiler is a facility that is invoked by the CLR to convert the IL into machine code. The .NET framework assemblies (*.dll or *.exe) files cannot be executed by the target processor unless it is converted into native code. When the Assembly is loaded the method calls are invoked for compilation into native code. Since this is done just when the method needs to execute, it is called Just in time compilation. When the JIT is invoked for the first time there is an overhead or performance penalty, since the assembly is converted into its Native code or image using the Native Image Generator (Ngen.exe). All subsequent calls will load faster as the Native image alone is invoked thereafter from the Native image cache.

Significantly, the IL can coexist with the machine code in the application. This feature also enables the developer modify the code or add to the code even when the application is actively deployed. This functionality provided by JIT makes the .NET framework an efficient, agile and powerful means of application development.

Assemblies, native assemblies, and the Global Assembly Cache (GAC)

The primary unit of deployment is the assembly. The assembly is used by the .NET CLR as the smallest unit of deployment; version control; security; type grouping and code reuse. An assembly will consist of a manifest and one or more modules or files. It can be defined as a logical DLL that contains a manifest, type metadata, MSIL and resources. Assemblies can be application private or shared. Private assemblies are restricted to use in a single application whereas shared assemblies can be used across applications. Private applications also reside within the application folder while shared assemblies reside in the common area– GAC(Global Assembly Cache). They must have a globally unique name.

The existence of the manifest within the assembly makes it self descriptive. It can be viewed by the IL Disassembler (Ildasm.exe) which is part of the .NET framework SDK.

The assembly is identified by the manifest. It defines security requirements, lists other interdependent assemblies and all the types and resources exposed by the assembly. Localized resources exposed by assemblies and targeted by the application contain a default culture (language, currency, date/time format etc).

The manifest contains several sections. Identity, Referenced Assemblies, file list and Custom Attributes are some of the important sections of the manifest. The Identity section as the name suggests, identifies the assembly. It contains a .assembly directive. The version directive specifies the version of the assembly, so that the CLR identifies the different versions of an application. The Identity section contains a strong name for shared assemblies and a public/private encryption key is used to distinguish between assemblies of the same name. The Identity section also optionally contains the Culture which defines the country and language of the assembly target. The .locale directive is used for this purpose and the Culture-Neutral assemblies can be used by any assembly.
The Referenced Assemblies section of the manifest provides a reference to all the assemblies used in an application.

Comparison of VB.NET, C#, and J#

The .NET framework architecture has made the language of coding immaterial to the final output. All languages also have equal access to all development capabilities and revolve around the .NET classes. The language syntax, operations etc look similar in all the languages of this group. Moreover, code can be shared by all .NET languages and so a class made in C# or J# can be used in VB.NET and vice versa.

In this context choice of language is no longer significant. Finally, all languages are transformed by the compiler into Microsoft Intermediate language. It is the programmer’s familiarity with the language that makes it material whether he is coding in VB.NET or C# or J#. However, the option settings in the compiler will have to be set to the language of coding before the compiler is used.

The speed of performance of the compiler will also vary with the language being compiled. For instance C# compiles faster than VB.NET. Subject to the above observation, the features of the languages will be dicussed in the next tutorial.

Leave a Comment

The .NET Framework Architecture Part 1

The .NET framework is a software technology that is directed towards connecting information, people, systems and devices seamlessly. The high level of software integration that has been attempted through use of XML web services enables the creation of small, discrete, building block types of applications. These applications are connected to other applications over the Internet.

Central to the .NET framework architecture is the effort to provide support to for the next generation solutions. The direction of change is to ensure that software deployment and versioning conflicts are avoided or minimized in the .NET Framework. User defined codes are released from the confines of the local storage systems and can be stored anywhere on a network and executed from any point in the network. Performance problems associated with scripted and interpreted environments are removed. Codes can be safely executed and the developer experience is consistent across widely varying types of applications, such as Windows based applications and web based applications. The thrust of design is towards creating a standard communication facility that is standardized so that .NET codes can be integrated with other codes easily and seamlessly.

At the core of the .NET infrastructure is the Common Language Runtime (CLR) and the .NET Framework class library.

The runtime functions, like an agent, managing code at execution time. It provides core services such as memory management, thread management and ‘remoting’. It enforces strict type safety and ensures code accuracy. This makes for security and robustness and provides a platform for running managed code.

The .NET Framework provides several runtime hosts. It also supports the development of third-party runtime hosts. For example, ASP.NET hosts the runtime to provide a scalable, server-side environment for managed code. ASP.NET works directly with the runtime to enable ASP.NET applications and XML Web services.

The .NET Framework can be hosted by unmanaged components such as the Internet Explorer. These load the common language runtime into their processes and initiate the execution of managed code. This creates a software environment that can exploit both managed and unmanaged features. This makes for mobility of the code.

Common Language Runtime (CLR)

The common language runtime (CLR) is the foundation upon which developers construct various kinds of applications. The benefits of the CLR are many. It makes for a vastly simplified development. It enables a seamless integration of code written in different languages. It provides evidence-based security with code identity. The assembly based deployment eliminates the problems of DLL. The versioning of reusable components makes for ease of usage. The implementation inheritance feature enables the reuse of code. The automatic object lifetime management makes the application- development comfortable. The self descriptive nature of objects makes for ease of programming and debugging.

CLR includes both private and shared components. It provides for incremental download of code and caching; native platform interoperability and seamless integration with COM. It offers dynamic inspection capabilities, administration and configuration options. The developer is not required to know all the runtime supported infrastructure. The tools and frameworks are designed to expose a subset of the functionality in accordance with the kind of application being built.

The common language runtime is a virtual execution system that provides important services such as memory management, security and also has a Just-in-Time compiler (JIT) which converts the intermediate language (IL) into native code that can be executed by the physical machine. The infrastructure provides a machine independent environment for application execution.

Tight security is maintained in implementing common language runtime. Managed components are awarded varying degrees of trust. Access rights are determined by factors such as origin of the component (Internet, enterprise network, or local computer). On the flip side this restricts access to file and registry operations, even if the file being operated upon is on within the same active application.

The managed environment of the runtime eliminates many common software issues. For example, the runtime automatically handles object layout and manages references to objects, releasing them when they are no longer being used. This automatic memory management resolves the two most common application errors–memory leaks and invalid memory references.

The futuristic design of the infrastructure is takes into consideration the need to integrate with the legacy applications that are still in operation.

Interoperability between managed and unmanaged code enables developers to continue to use necessary COM components and DLLs.

The use of ‘Common type’ system implements the features of the .NET infrastructure. The common data types shared by multiple languages such as VB.NET, C#, ASP.NET eases the import of a class created in one language into another. A common error handling facility makes for tighter integration between languages and allows developers the freedom of working in the language of their choice.

.NET Framework Class Library

The .NET framework class library, as the name suggests, is a library of classes, interfaces and value types. The applications, components and controls for applications are built on this framework and it provides the developer the access to the system functionality. In other words, the classes and structures can be leveraged as base building blocks for application development. These classes are often described as an API and form a boundary interface between the application and the operating system. Though the concept is not new to Visual basic Developers who have been using the ADO library, the Win 32 API and COM + services, it forms a massive code base on which the application can be built.

The .NET Framework class Library is organized into namespaces. The namespace is a container for functionality. Similar classes and constructs are grouped together in a namespace to define parent-child relationships. Namespaces can be nested into namespaces.

All namespaces stem from the root namespace called System Namespace. It contains all data types including the Object data type. Though all namespaces are subordinated to the System namespace, User defined libraries can also coexist with the System namespace. They can have their own root namespace which can be language focused namespaces such as Microsoft.Csharp, Microsoft.VisualBasic.

The most significant feature of the .NET framework is the class Library collection of reusable types can be integrated with CLR. The programmer can accomplish a range of common programming tasks, such as string management; data collection; data base connectivity and file access using the .NET framework class library. The developer can create console applications, Windows GUI applications, ASP.NET applications, XML Web services or Windows services.

Microsoft Intermediate Language (MSIL)

MSIL are simple binary structures that are similar to the instruction sets of the CPU. Like the instruction set, it encodes a wide spectrum of operations such as loading, storing, arithmetic and logical operations and control flow. The similarity to the machine code enables the code to be compiled quickly in the Just in time compiler. The type verification also becomes simpler because the DotNet binary contains tables of metadata. The metadata defines each type and its signatures and also the other data that the runtime locates and extracts from the file at the time of execution. The presence of the metadata makes the module self descriptive and eliminates the need for IDL files and header files. However, unlike the CPU instruction set, MSIL expresses object oriented concepts such as object creation, method invocation, property access and exception handling.

It is the Microsoft Intermediate Language (MSIL) which makes applications language independent. Applications may be created by programmers in any language of their choice—ASP.NET or VB.NET—in a machine on which the .NET framework has been installed. The compiler then, gives an output in the Microsoft Intermediate language. This language can be defined as a kind of assembly language at a higher level of abstraction. The language is designed in a manner that makes it possible to convert it into any kind of native machine code with ease. The CLR detects the Intermediate language and invokes the Just-in-time compiler to convert the language into machine code.

Leave a Comment

Older Posts »