lunes, 16 de junio de 2014

Obtener informacion sobre una tabla mysql: collation, numero de registros, valor de auto_increment ..

Para consultar la información sobre el estado de una tabla en mysql utilizaremos la sintaxis


SHOW TABLE STATUS like 'NOMBRE_DE_MI_TABLA'

Nos devolvera multitud de información muy util.



3.7.5.38 SHOW TABLE STATUS Syntax


SHOW TABLE STATUS [{FROM | IN} db_name]
    [LIKE 'pattern' | WHERE expr]
SHOW TABLE STATUS works likes SHOW TABLES, but provides a lot of information about each non-TEMPORARYtable. You can also get this list using the mysqlshow --status db_name command. The LIKE clause, if present, indicates which table names to match. The WHERE clause can be given to select rows using more general conditions, as discussed in Section 20.27, “Extensions to SHOW Statements”.
This statement also displays information about views.
SHOW TABLE STATUS output has the following columns:
  • Name
    The name of the table.
  • Engine
    The storage engine for the table. See Chapter 14, Storage Engines.
  • Version
    The version number of the table's .frm file.
  • Row_format
    The row-storage format (Fixed, Dynamic, Compressed, Redundant, Compact). For MyISAM tables, (Dynamiccorresponds to what myisamchk -dvv reports as Packed. The format of InnoDB tables is reported as Redundantor Compact. For the Barracuda file format of the InnoDB Plugin, the format may be Compressed or Dynamic.
  • Rows
    The number of rows. Some storage engines, such as MyISAM, store the exact count. For other storage engines, such as InnoDB, this value is an approximation, and may vary from the actual value by as much as 40 to 50%. In such cases, use SELECT COUNT(*) to obtain an accurate count.
    The Rows value is NULL for tables in the INFORMATION_SCHEMA database.
  • Avg_row_length
    The average row length.
  • Data_length
    The length of the data file.
  • Max_data_length
    The maximum length of the data file. This is the total number of bytes of data that can be stored in the table, given the data pointer size used.
  • Index_length
    The length of the index file.
  • Data_free
    The number of allocated but unused bytes.
    Beginning with MySQL 5.1.24, this information is also shown for InnoDB tables (previously, it was in the Commentvalue). InnoDB tables report the free space of the tablespace to which the table belongs. For a table located in the shared tablespace, this is the free space of the shared tablespace. If you are using multiple tablespaces and the table has its own tablespace, the free space is for only that table. Free space means the number of completely free 1MB extents minus a safety margin. Even if free space displays as 0, it may be possible to insert rows as long as new extents need not be allocated.
    For partitioned tables, this value is only an estimate and may not be absolutely correct. A more accurate method of obtaining this information in such cases is to query the INFORMATION_SCHEMA.PARTITIONS table, as shown in this example:
    SELECT    SUM(DATA_FREE)
        FROM  INFORMATION_SCHEMA.PARTITIONS
        WHERE TABLE_SCHEMA = 'mydb'
        AND   TABLE_NAME   = 'mytable';
    
  • Auto_increment
    The next AUTO_INCREMENT value.
  • Create_time
    When the table was created.
  • Update_time
    When the data file was last updated. For some storage engines, this value is NULL. For example, InnoDB stores multiple tables in its system tablespace and the data file timestamp does not apply. Even with file-per-table mode with each InnoDB table in a separate .ibd file, change buffering can delay the write to the data file, so the file modification time is different from the time of the last insert, update, or delete. For MyISAM, the data file timestamp is used; however, on Windows the timestamp is not updated by updates so the value is inaccurate.
  • Check_time
    When the table was last checked. Not all storage engines update this time, in which case the value is always NULL.
  • Collation
    The table's character set and collation.
  • Checksum
    The live checksum value (if any).
  • Create_options
    Extra options used with CREATE TABLE. The original options supplied when CREATE TABLE is called are retained and the options reported here may differ from the active table settings and options.
  • Comment
    The comment used when creating the table (or information as to why MySQL could not access the table information).
    Before MySQL 5.1.24, free space for InnoDB tables is reported in the comment. As of 5.1.24, it is reported in theData_free column.
For MEMORY tables, the Data_length, Max_data_length, and Index_length values approximate the actual amount of allocated memory. The allocation algorithm reserves memory in large amounts to reduce the number of allocation operations.
For NDBCLUSTER tables, the output of this statement shows appropriate values for the Avg_row_length andData_length columns, with the exception that BLOB columns are not taken into account. Prior to MySQL 5.1.21, the number of MySQL Cluster replicas was shown in the Comment column as number_of_replicas (Bug #11379).
For views, all the fields displayed by SHOW TABLE STATUS are NULL except that Name indicates the view name andComment says view.

User Comments

Posted by H Y on March 23 2004 12:16pm[Delete] [Edit]
If you need to get hold of only one of these columns, there are sometimes another way. E.g. if you don't need row format, type, name, average row length and all the other stuff, but only want to see the total number of rows in a table, use COUNT(*).
Posted by Steven Szelei on June 28 2004 5:54pm[Delete] [Edit]
I was looking for a way to show the relationship of tables based on unique key, key, index, and foreign key constraints. I found that I can get some of the data using the admin statement SHOW INDEX FROM <<TBL>>. However this will give only the index name and the Column_name in the table that I am requesting from. I then did a SHOW CREATE TABLE <<TBL>> and this dumps the DDL script used to create the table. I would have to parse this information but could get everything I needed. I then found that SHOW TABLE STATUS LIKE <<TBL>> gave me The REFER information mapped to the column name. Unfortunatlly it did so in the Comments field as a string so uh! more parsing. This is what I have been able to discover so far and am still looking for a clean way to gather key, index, and constraint information to dynamically build table relationships. Also I noticed that the constraint names set in the DDL have not been preserved and mysql has given the constraints their own names. Names given keys are preserved. you can see this by running the show create table <<TBL>> on any table you have set constraints on.
Posted by Bahadir Malkoç on December 5 2005 3:42pm[Delete] [Edit]
Here is an example of using this command with php and get results...

<?php

mysql_connect
("localhost","root","");$result = mysql_query("SHOW TABLE STATUS FROM test;");
while(
$array = mysql_fetch_array($result)) {$total = $array[Data_length]+$array[Index_length];
echo 
'
Table: '
.$array[Name].'<br />
Data Size: '
.$array[Data_length].'<br />
Index Size: '
.$array[Index_length].'<br />
Total Size: '
.$total.'<br />
Total Rows: '
.$array[Rows].'<br />
Average Size Per Row: '
.$array[Avg_row_length].'<br /><br />
'
;
}
?> 
Posted by dan f on December 6 2005 7:47pm[Delete] [Edit]
Here is a perl script to add up free space per engine. Whether you are out of space depends on how you have configured MySQL. The InnoDB engine might be limited space, or it might be allowed to grow. The MyISAM space is probably in the file system, which has as much left as it has.

This script is a hack. Feel free to improve and post.

For some reason, I can't get it to format nicely, either.

#!/opt/gnu/bin/perl -w

use strict;

use Getopt::Long;
my @options;

# Get output immediately. It won't hurt performance.
use FileHandle;
autoflush STDERR;
autoflush STDOUT;

my $pw;
push(@options, "password=s", \$pw);

my $host = "localhost";
push(@options, "host=s", \$host);

die "Couldn't parse options" if !GetOptions(@options);

die "Must give -password\n" if !defined($pw);

my $cmd = mysql_cmd("show databases");
open(CMD, $cmd) or die "Couldn't $cmd: $!\n";
my @databases;
my $header = <CMD>;
while ( <CMD> ) {
s/[\r\n]$//g;
#print "$_\n";
push (@databases, $_);
}
close(CMD);

#print "@databases";

my %colmap = ( 'Data_length' => 6,
'Index_length' => 8,
'Engine' => 1,
'Comment' => 17 );

my %size;
my %total_size;
my %engine_map;

my $inno_db_free;
foreach my $db (@databases) {
print STDERR ".";
$cmd = mysql_cmd("use $db; show table status");

open(CMD, $cmd) or die "Couldn't $cmd: $!\n";
my $header = <CMD>;
my $total_size = 0;
if (defined($header)) {
$header =~ s/[\r\n]$//g;
my @head = split("\t", $header);

foreach my $col (keys %colmap) {
die "$db: Expected '$col', found '" . $head[$colmap{$col}] . "'"
if $head[$colmap{$col}] ne $col;
}

while (<CMD>) {
my @data = split("\t");
my ($data_length, $index_length) = @data[6,8];
my ($engine, $comment) = @data[1,17];
$engine_map{$engine}++;
$size{$db}{$engine} += $data_length + $index_length;
$total_size{$db} += $data_length + $index_length;

if ( $comment =~ /InnoDB free: (\d+) kB/ ) {
die "Found two different inno DB free sized.\n"
if defined($inno_db_free) && $inno_db_free != $1;
$inno_db_free = $1;
}
}
close(CMD);
}
}
print STDERR "\n";

print "NOTE: All numbers are in megabytes (M).\n";
printf("Inno DB free: %.1f\n", $inno_db_free / 1024)
if defined($inno_db_free);

printf("%-30s ", "database");
foreach my $engine (sort keys(%engine_map)) {
printf "%7s ", $engine;
}
printf "%8s", "total";
print "\n";

foreach my $db (sort {$total_size{$b} <=> $total_size{$a}} keys %total_size) {
printf("%-30s ", $db);
foreach my $engine (sort keys(%engine_map)) {
my $size= $size{$db}{$engine};
$size = 0 if !defined($size);
printf("%7.1f ", $size / 1024 / 1024);
}
printf("%8.1f\n", $total_size{$db} / 1024 / 1024);
}

sub mysql_cmd {
my $mysql_cmd = shift;

return "mysql -uroot -h$host -p$pw -e '$mysql_cmd'|";
}

Example output:

% ./db-space.pl -p ...
....................
NOTE: All numbers are in megabytes (M).
Inno DB free: 10755.0
database HEAP InnoDB MyISAM total
tldan 0.0 339.1 720.3 1059.4
ml3test7 0.0 1010.8 0.0 1010.8
ml3test6 0.0 930.4 0.0 930.4
test 0.0 655.4 0.0 655.4
blarg4 0.0 39.5 0.0 39.5
Posted by Marc Zizka on January 6 2006 4:18am[Delete] [Edit]
For InnoDB tables, the Comment field of SHOW TABLE STATUS is useful for extracting foreign key information for older versions of MySQL. For versions since 5.0.6, you can query INFORMATION_SCHEMA. (See http://dev.mysql.com/doc/refman/5.0/en/key-column-usage-table.html)

The way the foreign key info is stored in the Comment field can be a pain to parse. Here's a snippet of PHP code that shows how to do this.

<?php//DB connection already established$res = mysql_query("SHOW TABLE STATUS LIKE 'MY_TABLE'");$row = mysql_fetch_assoc($res);mysql_free_result($res);$commentArr = preg_split('/; */', $row['Comment']);$foreignKeyArr = array(); //<-- We want to fill this.foreach($commentArr as $comment) {
   
//Only work on InnoDB foreign key info.
   
if(preg_match(
         
'/\(`(.*)`\) REFER `(.*)\/(.*)`\(`(.*)`\)/',
         
$comment,
         
$matchArr)) {
   
$primaryKeyFieldArr = preg_split('/` `/', matchArr[1]);
   
$foreignKeyDatabase = $matchArr[2];
   
$foreignKeyTable = $matchArr[3];
   
$foreignKeyFieldArr = preg_split('/` `/', $matchArr[4]);

   for(
$i = 0; $i < count($primaryKeyFieldArr); $i++) {
      
$foreignKeyArr[ $primaryKeyFieldArr[$i] ] = array(
         
'db' => $foreignKeyDatabase,
         
'table' => $foreignKeyTable,
         
'field' => $foreignKeyFieldArr[$i]);
   }
}
?> 


Now $foreignKeyArr holds a list of fields from MY_TABLE
that have a foreign key constraint. If MY_FK is a foreign
key referencing YOUR_ID in YOUR_TABLE, you will get:

$foreignKeyArr['MY_FK']['db'] == 'THIS_DATABASE'
$foreignKeyArr['MY_FK']['table'] == 'YOUR_TABLE'
$foreignKeyArr['MY_FK']['field'] == 'YOUR_ID'
Posted by Brian Robinson on August 25 2006 10:27am[Delete] [Edit]
If you are REALLY desperate to get FK relationships you can always use a bit of JAVA code.
I know you Perl guys will balk at this - but the JDBC METADATA can give you this information quite easily.
maybe there is something similar for Perl DBI?
Yes!
http://search.cpan.org/src/TIMB/DBI_AdvancedTalk_2004/sld086.htm
Posted by Eric Brunson on February 5 2007 10:45pm[Delete] [Edit]
Or you can read the foreign key relationships out of the information_schema. Java's not magic, you know, all that info is in there to be used by anything that can read it. ;-)
Posted by andrew taylor on May 19 2007 9:25pm[Delete] [Edit]
A handy one liner to get the total table size...requires ruby

mysqlshow -u <user> --password=<password> --status <dbname> | ruby -e 'puts STDIN.readlines[4..-2].inject(0) {|s,e| s += e.split("|")[7].to_i}'
Posted by Scott Ripley on May 24 2007 7:39pm[Delete] [Edit]
I've amended the above PHP script to format the output for an HTML table.

<?phpprint('<table cols="6"><th>Table</th><th>Data Size</th><th>Index Size</th><th>Total size</th><th>Total Rows</th><th>Avg. Size per Row</th>');mysql_connect("localhost","my_user","password");$result = mysql_query("SHOW TABLE STATUS FROM test;");

while(
$array = mysql_fetch_array($result)) {$total = $array[Data_length]+$array[Index_length];

if ( 
$array[Data_length] > 0 ) {

    print(
'<tr><td align="center">');

    print(
' ' . $array[Name] . '<br /></td><td align="center">');

if ( 
$array[Data_length] < 1024 ) {
        echo 
' '.$array[Data_length].'</td><td align="center">';
        } elseif ( (
$array[Data_length] > 1024) && ($array[Data_length] < 1048576 ) ) {
        
printf('%.0fK',($array[Data_length] / 1024) );  
        print(
'</td><td align="center">');
        } elseif ( 
$array[Data_length] >= 1048576 ) {
        
printf('%.2fMB',($array[Data_length] / 1048576) );
        print(
'</td><td align="center">');

        }

if ( 
$array[Index_length] < 1024 ) {
        echo 
' '.$array[Index_length].'<br /></td><td align="center">';
        } elseif ( (
$array[Index_length] > 1024) && ($array[Index_length] < 1048576 ) ) {
        
printf('%.0fK',($array[Index_length] / 1024) );  
        print(
'<br /></td><td align="center">');
        } elseif ( 
$array[Index_length] >= 1048576 ) {
        
printf('%.2fMB',($array[Index_length] / 1048576) );
        print(
'<br /></td><td align="center">');

        }
if ( 
$total < 1024 ) {
        echo 
' '.$total.'<br /></td><td align="center">';
        } elseif ( (
$total > 1024) && ($total < 1048576 ) ) {
        
printf('%.0fK',($total / 1024) );  
        print(
'<br /></td><td align="center">');
        } elseif ( 
$total >= 1048576 ) {
        
printf('%.2fMB',($total / 1048576) );
        print(
'<br /></td><td align="center">');

        }  
              
echo 
'      
 '
.$array[Rows].'</td><td align="center">
 '
.$array[Avg_row_length].'</td></tr>
'
;
}

}
?> 
Posted by Vasil Dimov on December 11 2007 4:01pm[Delete] [Edit]
Since MySQL 5.1.23 the InnoDB free space that was present in INFORMATION_SCHEMA.TABLES.TABLE_COMMENT and in "SHOW ..." is moved to INFORMATION_SCHEMA.TABLES.DATA_FREE. The value is in kilobytes. Programs that parse TABLE_COMMENT need to be adjusted. See http://bugs.mysql.com/32440
Posted by Marcos Gil Fuertes on February 7 2008 4:17pm[Delete] [Edit]
To Marc Zizka:

I tried your script BUT got a problem with "SHOW TABLE STATUS". It only returns the first foreign key (in MySql 5.0.27).

Instead of it, I'm using "SHOW CREATE TABLE" and this regular expression:

'/FOREIGN KEY \(`(.*)`\) REFERENCES `(.*)` \(`(.*)`\)/'

I'm assuming that all the references are located in the same database.
Posted by Ivan Cachicatari on February 29 2012 4:41am[Delete] [Edit]
You can found a custom SHOW TABLE STATUS command based on INFORMATION_SCHEMA database at:
http://en.latindevelopers.com/ivancp/2012/a-better-show-table-status/
That stored procedure returns a result like this:
+----------------------------+--------+-------+---------+-----------------+
| Table Name                 | Engine | Rows  | Size    | Collation       |
+----------------------------+--------+-------+---------+-----------------+
| actor                      | InnoDB | 200   | 0.03 Mb | utf8_general_ci |
| actor_info                 | [VIEW] | -     | -       | -               |
| address                    | InnoDB | 589   | 0.09 Mb | utf8_general_ci |
| category                   | InnoDB | 16    | 0.02 Mb | utf8_general_ci |
| city                       | InnoDB | 427   | 0.06 Mb | utf8_general_ci |
| country                    | InnoDB | 109   | 0.02 Mb | utf8_general_ci |
| customer                   | InnoDB | 541   | 0.12 Mb | utf8_general_ci |
...


Fuente:

http://dev.mysql.com/doc/refman/5.1/en/show-table-status.html

jueves, 12 de junio de 2014

InvalidCastException La conversion espedificada no es válida leyendo un SQLDataReader Tipo Smallint c#

Estaba lanzando una consulta sencilla y al recuperar un campo de la consulta me devolvía el error mostrado ..

si miramos el detalle de la excepcion muestra la siguiente información.. 

El problema es que tenia el campo definido en al base de datos como Smallint y al realizar la lectura del siguiente modo ...

   SqlConnection conn = null;
            conn = new SqlConnection(cloudModel.Database.Connection.ConnectionString);
            conn.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandType = CommandType.Text;

            string vConsulta = "select miCampoSmallint from miTabla;

            cmd.CommandText = vConsulta;
            SqlDataReader rdr = cmd.ExecuteReader();

            int miVariable = (int) rdr["miCampoSmallint"] => al realizar la conversion a int del campo smallint tenia el error del que hablamos. 

            La solucion es tan simple como realizar el casting con un short

            short miVariable = (short) rdr["miCampoSmallint"]

Me ha dolido la cabeza hasta darme cuenta de este error tan tonto así que espero sea de ayuda para otros. Saludos  

jueves, 29 de mayo de 2014

SQLSERVER Conocer cuanto espacio ocupa una Base de datos

Ejecutando el siguiente comando sobre el monitor de comandos obtendremos la información de espacio de nuestra Base de datos

EXEC sp_spaceused N'NOMBRE_DE_LA_TABLA';

Obtendremos por pantalla el resultado como el de la imagen..
El valor viene expresado en KB para conocer el espacio que ocupa en MB Basta con divivir la cantidad indicada en el registro data entre 1024 de modo que en este ejemplo nuestra tabla de lineastickets ocupa unos 258 MB aproximadamente

viernes, 23 de mayo de 2014

Sumar o restar dias, años o meses a una fecha en TSQL con SQLSERVER

Tenemos almacenada en una tabla una columna fecha que consultaremos con una sentencia simple

select fecha from tabla

pero queremos calcular a partir de esta fecha .. 90 dias despues que fecha sería ...
pues para ello usaremos la funcion:

DATEADD (datepart , number , date )

Esta función tiene 3 parámetros:
- el primero "datepart" dice a que "parte de la fecha" (dias, meses o años) sumaremos/restaremos la cantidad que queremos añadir o sustraer a la fecha.

- el segundo "number" representa la cantidad que sumaremos o restaremos "10" dias, "10" mese, "10" años.. OJOO (menos 10, "-10" también puede ponerse)

- el ultimo es la fecha de partida

la sintaxis quedaría así...

select  fecha, dateADd(DD, 10, FECHA) FechaControl from tabla

en este ejemplo hemos devuelto la fecha de la tabla y la fecha 10 días despues

Para desginar el primer parametro hay que utilizar la siguiente tabla:

datepart
Abbreviations
year
yy , yyyy
quarter
qq , q
month
mm , m
dayofyear
dy , y
day
dd , d
week
wk , ww
weekday
dw , w
hour
hh
minute
mi , n
second
ss , s
millisecond
ms
microsecond
mcs
nanosecond
ns


fuente: http://msdn.microsoft.com/en-us/library/ms186819.aspx

miércoles, 21 de mayo de 2014

Etiquetar el eje X de un Chat en ASP C#

Esta es la sintaxis:
Chart1.Series["Default"].Points[0].AxisLabel = "First Point";
Chart1.Series["Default"].Points[1].AxisLabel = "Second Point";


Esto es un copiado de la información proporcionada por Microsoft. Creo que es muy facil de comprender y completa por eso he realizado simplemente un volcado del contenido.

Fuente: http://msdn.microsoft.com/es-es/library/dd456628.aspx

Etiquetas

Visual Studio 2013
Personas que lo han encontrado útil: 1 de 1 - Valorar este tema
En el control Chart, puede utilizar etiquetas para los ejes y etiquetas para los puntos de datos con el fin de hacer sus gráficos más informativos.

Utilizar etiquetas para los ejes

El control Chart etiqueta los ejes del área del gráfico de tres maneras diferentes, en orden de prioridad ascendente:
  • Etiquetar los ejes numéricamente
  • Etiquetar los ejes mediante texto
  • Etiquetar los ejes mediante etiquetas personalizadas
Estos métodos difieren principalmente en cómo se genera el texto de las etiquetas. Puede utilizar un método diferente para cada uno de los ejes. Por ejemplo, utilizar un conjunto de etiquetas personalizadas para el eje Y y etiquetas de texto para el eje X.

Dd456628.collapse_all(es-es,VS.120).gifEtiquetar los ejes numéricamente

Si un eje no contiene etiquetas personalizadas, y los datos trazados no tienen etiquetas de eje, el control Chart muestra automáticamente las etiquetas de eje en un intervalo especificado por la propiedad Axis.Interval. Para obtener más información sobre la propiedad, vea Eje

Dd456628.collapse_all(es-es,VS.120).gifEtiquetar los ejes mediante texto

Puede etiquetar el eje según el conjunto de datos particular utilizado mediante la propiedad DataPoint.AxisLabel. Una vez establecida esta propiedad con una cadena de etiqueta, el gráfico muestra la cadena de la etiqueta en el eje en la posición del punto de datos.
Nota Nota
Cuando el control Chart contiene un gran conjunto de datos, puede mostrar selectivamente las etiquetas de eje. Para asegurarse de que todas las etiquetas de eje están visibles, establezca la propiedad Axis.Interval en 1.
El siguiente ejemplo de código establece dos etiquetas en el eje para los dos puntos de datos.
Chart1.Series["Default"].Points[0].AxisLabel = "First Point";
Chart1.Series["Default"].Points[1].AxisLabel = "Second Point";

Dd456628.collapse_all(es-es,VS.120).gifEtiquetar los ejes mediante etiquetas personalizadas

Utilice las etiquetas personalizadas para proporcionar texto personalizado para los ejes. Las etiquetas personalizadas se implementan utilizando la propiedad de colecciónCustomLabels. Si utiliza etiquetas personalizadas, el área del gráfico no muestra etiquetas de eje en los puntos de datos.
Al utilizar objetos CustomLabel, deberá establecer las propiedades FromPosition y ToPosition de cada objeto CustomLabel, y estas propiedades deben especificar el ancho del área de texto de la etiqueta. No asigne el mismo valor a ambas propiedades, ya que representan un intervalo. Para colocar una etiqueta personalizada directamente bajo un punto de datos y su marca de graduación asociada, establezca la propiedad FromPosition en el valor del eje de ese punto de datos menos la mitad del intervalo de la marca de graduación y establezca la propiedad ToPosition en el valor del eje de ese punto de datos más la mitad del intervalo de la marca de graduación. Por ejemplo, si un eje tiene un intervalo de 1 (1, 2, 3…), y desea usar una etiqueta personalizada en X=2, entonces establezca las propiedades FromPosition y ToPosition en 1,5 y 2,5, respectivamente.
La propiedad RowIndex especifica en qué fila se mostrará la etiqueta personalizada. Si se utiliza una etiqueta personalizada en la primera fila de etiquetas, el área del gráfico no mostrará ninguna etiqueta de la escala del eje. Las únicas etiquetas permitidas en la segunda fila y siguientes serán las etiquetas personalizadas.

Dd456628.collapse_all(es-es,VS.120).gifFormatos y estilos de etiqueta de los ejes

Puede establecer los estilos de etiqueta de un eje mediante la propiedad LabelStyle del objeto Axis. Las propiedades de estilo de etiqueta que establezca en esta propiedad, comoLabelStyle.Font, se aplican a las etiquetas de un eje. Si las etiquetas del eje están demasiado cerca unas de otras, puede establecer propiedad LabelStyle.LabelsAutoFit oLabelStyle.Offset en True.
Al etiquetar los ejes numéricamente, también puede dar formato a los números utilizando la propiedad LabelStyle.Format.
El siguiente código muestra cómo establecer el eje Y principal con formato de divisa.
Chart1.ChartAreas["Default"].AxisY.LabelStyle.Format = "C";
El siguiente código muestra el día de semana en el eje X principal.Para obtener más información sobre cómo mostrar valores de fecha y hora como etiquetas de eje, vea Trabajar con valores de fecha y hora.
Chart1.ChartAreas["Default"].AxisX.LabelStyle.Format = "dddd";

Etiquetar puntos de datos

Puede mostrar etiquetas en los puntos de datos en el área de trazado. Para mostrar los valores de los puntos de datos como etiquetas, utilice la propiedad IsValueShownAsLabel en el objeto DataPoint o Series. Para mostrar otro texto como etiquetas de los puntos de datos, utilice la propiedad Series.Label.
Para utilizar datos en las etiquetas, utilice palabras clave en la propiedad Series.Label. En tiempo de ejecución, el gráfico reemplaza la palabra clave con los valores adecuados. Por ejemplo, el siguiente código muestra una etiqueta multilínea para cada punto de datos, con el valor Y en la primera línea y el valor X en la segunda línea.
Chart1.Series["Series1"].Label = "Y = #VALY\nX = #VALX";
Para obtener más información, vea Palabras clave.

Dd456628.collapse_all(es-es,VS.120).gifUtilizar etiquetas inteligentes

Dependiendo del tipo de gráfico, puede utilizar la propiedad Series.SmartLabelStyle para establecer etiquetas para puntos de datos que no entran en colisión.Esto resulta útil cuando se agrupan puntos de datos.
NotaNota
La propiedad Series.SmartLabelStyle no tiene ningún efecto sobre los tipos de gráficos de barras, barras de intervalo, circular, anillos, columnas de intervalo, áreas apiladas, áreas 100% apiladas, barras apiladas, barras 100% apiladas.
Para habilitar las etiquetas inteligentes, utilice el siguiente código.
Chart1.Series["Series1"].SmartLabelStyle.Enabled = true;
A continuación, puede utilizar propiedades de SmartLabelStyle tales como CalloutStyle y CalloutLineColor para controlar la apariencia de las etiquetas inteligentes.


martes, 20 de mayo de 2014

Separar una cadena en función de un delimitador Delphi

program Project28;

{$APPTYPE CONSOLE}

uses
  Classes,
  SysUtils;

procedure Split(Delimiter: Char; Str: string; ListOfStrings: TStrings) ;
begin
   ListOfStrings.Clear;
   ListOfStrings.Delimiter     := Delimiter;
   ListOfStrings.DelimitedText := Str;
end;


var
   OutPutList: TStringList;
begin
   OutPutList := TStringList.Create;
   try
     Split(':', 'word:doc,txt,docx', OutPutList) ;
     Writeln(OutPutList.Text);
     Readln;
   finally
     OutPutList.Free;
   end;
end.
Fuente: http://stackoverflow.com/questions/2625707/split-a-string-into-an-array-of-strings-based-on-a-delimiter

lunes, 19 de mayo de 2014

Mensajes de error en ficheros JPG

0  cstrJMSG_NOMESSAGE               'Bogus message code %d'; (* Must be first entry! *)
  1  cstrJERR_ARITH_NOTIMPL           'Sorry, there are legal restrictions on arithmetic coding'
  2  cstrJERR_BAD_ALIGN_TYPE          'ALIGN_TYPE is wrong, please fix'
  3  cstrJERR_BAD_ALLOC_CHUNK         'MAX_ALLOC_CHUNK is wrong, please fix'
  4  cstrJERR_BAD_BUFFER_MODE         'Bogus buffer control mode'
  5  cstrJERR_BAD_COMPONENT_ID        'Invalid component ID %d in SOS'
  6  cstrJERR_BAD_DCTSIZE             'IDCT output block size %d not supported'
  7  cstrJERR_BAD_IN_COLORSPACE       'Bogus input colorspace'
  8  cstrJERR_BAD_J_COLORSPACE        'Bogus JPEG colorspace'
  9  cstrJERR_BAD_LENGTH              'Bogus marker length'
 10  cstrJERR_BAD_LIB_VERSION         'Wrong JPEG library version: library is %d, caller expects %d'
 11  cstrJERR_BAD_MCU_SIZE            'Sampling factors too large for interleaved scan'
 12  cstrJERR_BAD_POOL_ID             'Invalid memory pool code %d'
 13  cstrJERR_BAD_PRECISION           'Unsupported JPEG data precision %d'
 14  cstrJERR_BAD_PROGRESSION         'Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d'
 15  cstrJERR_BAD_PROG_SCRIPT         'Invalid progressive parameters at scan script entry %d'
 16  cstrJERR_BAD_SAMPLING            'Bogus sampling factors'
 17  cstrJERR_BAD_SCAN_SCRIPT         'Invalid scan script at entry %d'
 18  cstrJERR_BAD_STATE               'Improper call to JPEG library in state %d'
 19  cstrJERR_BAD_STRUCT_SIZE         'JPEG parameter struct mismatch: library thinks size is %u, caller expects %u'
 20  cstrJERR_BAD_VIRTUAL_ACCESS      'Bogus virtual array access'
 21  cstrJERR_BUFFER_SIZE             'Buffer passed to JPEG library is too small'
 22  cstrJERR_CANT_SUSPEND            'Suspension not allowed here'
 23  cstrJERR_CCIR601_NOTIMPL         'CCIR601 sampling not implemented yet'
 24  cstrJERR_COMPONENT_COUNT         'Too many color components: %d, max %d'
 25  cstrJERR_CONVERSION_NOTIMPL      'Unsupported color conversion request'
 26  cstrJERR_DAC_INDEX               'Bogus DAC index %d'
 27  cstrJERR_DAC_VALUE               'Bogus DAC value 0x%x'
 28  cstrJERR_DHT_COUNTS              'Bogus DHT counts'
 29  cstrJERR_DHT_INDEX               'Bogus DHT index %d'
 30  cstrJERR_DQT_INDEX               'Bogus DQT index %d'
 31  cstrJERR_EMPTY_IMAGE             'Empty JPEG image (DNL not supported)'
 32  cstrJERR_EMS_READ                'Read from EMS failed'
 33  cstrJERR_EMS_WRITE               'Write to EMS failed'
 34  cstrJERR_EOI_EXPECTED            'Didn''t expect more than one scan'
 35  cstrJERR_FILE_READ               'Input file read error'
 36  cstrJERR_FILE_WRITE              'Output file write error --- out of disk space?'
 37  cstrJERR_FRACT_SAMPLE_NOTIMPL    'Fractional sampling not implemented yet'
 38  cstrJERR_HUFF_CLEN_OVERFLOW      'Huffman code size table overflow'
 39  cstrJERR_HUFF_MISSING_CODE       'Missing Huffman code table entry'
 40  cstrJERR_IMAGE_TOO_BIG           'Maximum supported image dimension is %u pixels'
 41  cstrJERR_INPUT_EMPTY             'Empty input file'
 42  cstrJERR_INPUT_EOF               'Premature end of input file'
 43  cstrJERR_MISMATCHED_QUANT_TABLE  'Cannot transcode due to multiple use of quantization table %d'
 44  cstrJERR_MISSING_DATA            'Scan script does not transmit all data'
 45  cstrJERR_MODE_CHANGE             'Invalid color quantization mode change'
 46  cstrJERR_NOTIMPL                 'Not implemented yet'
 47  cstrJERR_NOT_COMPILED            'Requested feature was omitted at compile time'
 48  cstrJERR_NO_BACKING_STORE        'Backing store not supported'
 49  cstrJERR_NO_HUFF_TABLE           'Huffman table 0x%02x was not defined'
 50  cstrJERR_NO_IMAGE                'JPEG datastream contains no image'
 51  cstrJERR_NO_QUANT_TABLE          'Quantization table 0x%02x was not defined'
 52  cstrJERR_NO_SOI                  'Not a JPEG file: starts with 0x%02x 0x%02x'
 53  cstrJERR_OUT_OF_MEMORY           'Insufficient memory (case %d)'
 54  cstrJERR_QUANT_COMPONENTS        'Cannot quantize more than %d color components'
 55  cstrJERR_QUANT_FEW_COLORS        'Cannot quantize to fewer than %d colors'
 56  cstrJERR_QUANT_MANY_COLORS       'Cannot quantize to more than %d colors'
 57  cstrJERR_SOF_DUPLICATE           'Invalid JPEG file structure: two SOF markers'
 58  cstrJERR_SOF_NO_SOS              'Invalid JPEG file structure: missing SOS marker'
 59  cstrJERR_SOF_UNSUPPORTED         'Unsupported JPEG process: SOF type 0x%02x'
 60  cstrJERR_SOI_DUPLICATE           'Invalid JPEG file structure: two SOI markers'
 61  cstrJERR_SOS_NO_SOF              'Invalid JPEG file structure: SOS before SOF'
 62  cstrJERR_TFILE_CREATE            'Failed to create temporary file %s'
 63  cstrJERR_TFILE_READ              'Read failed on temporary file'
 64  cstrJERR_TFILE_SEEK              'Seek failed on temporary file'
 65  cstrJERR_TFILE_WRITE             'Write failed on temporary file --- out of disk space?'
 66  cstrJERR_TOO_LITTLE_DATA         'Application transferred too few scanlines'
 67  cstrJERR_UNKNOWN_MARKER          'Unsupported marker type 0x%02x'
 68  cstrJERR_VIRTUAL_BUG             'Virtual array controller messed up'
 69  cstrJERR_WIDTH_OVERFLOW          'Image too wide for this implementation'
 70  cstrJERR_XMS_READ                'Read from XMS failed'
 71  cstrJERR_XMS_WRITE               'Write to XMS failed'
 72  cstrJMSG_COPYRIGHT               cstrJCOPYRIGHT
 73  cstrJMSG_VERSION                 cstrJVERSION
 74  cstrJTRC_16BIT_TABLES            'Caution: quantization tables are too coarse for baseline JPEG'
 75  cstrJTRC_ADOBE                   'Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d'
 76  cstrJTRC_APP0                    'Unknown APP0 marker (not JFIF), length %u'
 77  cstrJTRC_APP14                   'Unknown APP14 marker (not Adobe), length %u'
 78  cstrJTRC_DAC                     'Define Arithmetic Table 0x%02x: 0x%02x'
 79  cstrJTRC_DHT                     'Define Huffman Table 0x%02x'
 80  cstrJTRC_DQT                     'Define Quantization Table %d  precision %d'
 81  cstrJTRC_DRI                     'Define Restart Interval %u'
 82  cstrJTRC_EMS_CLOSE               'Freed EMS handle %u'
 83  cstrJTRC_EMS_OPEN                'Obtained EMS handle %u'
 84  cstrJTRC_EOI                     'End Of Image'
 85  cstrJTRC_HUFFBITS                '        %3d %3d %3d %3d %3d %3d %3d %3d'
 86  cstrJTRC_JFIF                    'JFIF APP0 marker, density %dx%d  %d'
 87  cstrJTRC_JFIF_BADTHUMBNAILSIZE   'Warning: thumbnail image size does not match data length %u'
 88  cstrJTRC_JFIF_MINOR              'Unknown JFIF minor revision number %d.%02d'
 89  cstrJTRC_JFIF_THUMBNAIL          '    with %d x %d thumbnail image'
 90  cstrJTRC_MISC_MARKER             'Skipping marker 0x%02x, length %u'
 91  cstrJTRC_PARMLESS_MARKER         'Unexpected marker 0x%02x'
 92  cstrJTRC_QUANTVALS               '        %4u %4u %4u %4u %4u %4u %4u %4u'
 93  cstrJTRC_QUANT_3_NCOLORS         'Quantizing to %d = %d*%d*%d colors'
 94  cstrJTRC_QUANT_NCOLORS           'Quantizing to %d colors'
 95  cstrJTRC_QUANT_SELECTED          'Selected %d colors for quantization'
 96  cstrJTRC_RECOVERY_ACTION         'At marker 0x%02x, recovery action %d'
 97  cstrJTRC_RST                     'RST%d'
 98  cstrJTRC_SMOOTH_NOTIMPL          'Smoothing not supported with nonstandard sampling ratios'
 99  cstrJTRC_SOF                     'Start Of Frame 0x%02x: width=%u, height=%u, components=%d'
100  cstrJTRC_SOF_COMPONENT           '    Component %d: %dhx%dv q=%d'
101  cstrJTRC_SOI                     'Start of Image'
102  cstrJTRC_SOS                     'Start Of Scan: %d components'
103  cstrJTRC_SOS_COMPONENT           '    Component %d: dc=%d ac=%d'
104  cstrJTRC_SOS_PARAMS              '  Ss=%d, Se=%d, Ah=%d, Al=%d'
105  cstrJTRC_TFILE_CLOSE             'Closed temporary file %s'
106  cstrJTRC_TFILE_OPEN              'Opened temporary file %s'
107  cstrJTRC_UNKNOWN_IDS             'Unrecognized component IDs %d %d %d, assuming YCbCr'
108  cstrJTRC_XMS_CLOSE               'Freed XMS handle %u'
109  cstrJTRC_XMS_OPEN                'Obtained XMS handle %u'
110  cstrJWRN_ADOBE_XFORM             'Unknown Adobe color transform code %d'
111  cstrJWRN_BOGUS_PROGRESSION       'Inconsistent progression sequence for component %d coefficient %d'
112  cstrJWRN_EXTRANEOUS_DATA         'Corrupt JPEG data: %u extraneous bytes before marker 0x%02x'
113  cstrJWRN_HIT_MARKER              'Corrupt JPEG data: premature end of data segment'
114  cstrJWRN_HUFF_BAD_CODE           'Corrupt JPEG data: bad Huffman code'
115  cstrJWRN_JFIF_MAJOR              'Warning: unknown JFIF revision number %d.%02d'
116  cstrJWRN_JPEG_EOF                'Premature end of JPEG file'
117  cstrJWRN_MUST_RESYNC             'Corrupt JPEG data: found marker 0x%02x instead of RST%d'
118  cstrJWRN_NOT_SEQUENTIAL          'Invalid SOS parameters for sequential JPEG'
119  cstrJWRN_TOO_MUCH_DATA           'Application transferred too many scanlines'


Source:  http://community.borland.com/article/0,1410,20433,00.html

Jesús Moreno - Ingeniero Ténico Informático - consultor Informático

Hola, soy Jesús Moreno Ingeniero Técnico Informático en sistemas por la US y propietario de éste blog. Mi trabajo en los ultimos años se ...