DataTable - Adding, Modifying, Deleting, Filtering, Sorting rows & Reading/Writing from/to Xml

Creating a DataTable
To create a DataTable, you need to use System.Data namespace, generally when you create a new class or page, it is included by default by the Visual Studio. Lets write following code to create a DataTable object. Here, I have pased a string as the DataTable name while creating DataTable object.
// instantiate DataTableDataTable dTable = new DataTable("Dynamically_Generated");
Creating Columns in the DataTable
To create column in the DataTable, you need to use DataColumn object. Instantiate the DataColumn object and pass column name and its data type as parameter. Then call add method of DataTable column and pass the DataColumn object as parameter.
// create columns for the DataTable
DataColumn auto = new DataColumn("AutoID", typeof(System.Int32));
dTable.Columns.Add(auto);
// create another column
DataColumn name = new DataColumn("Name", typeof(string));
dTable.Columns.Add(name);
// create one more column
DataColumn address = new DataColumn("Address", typeof(string));
dTable.Columns.Add(address);
Specifying AutoIncrement column in the DataTable
To specify a column as AutoIncrement (naturally it should be an integer type of field only), you need to set some properties of the column like AutoIncrement, AutoIncrementSeed. See the code below, here I am setting the first column "AutoID" as autoincrement field. Whenever a new row will be added its value will automatically increase by 1 as I am specified AutoIncrementSeed value as 1.
// specify it as auto increment field
auto.AutoIncrement = true;
auto.AutoIncrementSeed = 1;
auto.ReadOnly = true;
If you want a particular column to be a unique column ie. you don't want duplicate records into that column, then set its Unique property to true like below.
auto.Unique = true;
Specifying Primary Key column in the DataTable
To set the primary key column in the DataTable, you need to create arrays of column and store column you want as primary key for the DataTable and set its PrimaryKey property to the column arrays. See the code below.
// create primary key on this fieldDataColumn[] pK = new DataColumn[1];
pK[0] = auto;
dTable.PrimaryKey = pK;
Till now we have created the DataTable, now lets populate the DataTable with some data.
Populating data into DataTable
There are two ways to populate DataTable.
Using DataRow object
Look at the code below, I have created a DataRow object above the loop and I am assiging its value to the dTable.NewRow() inside the loop. After specifying columns value, I am adding that row to the DataTable using dTable.Rows.Add method.
// populate the DataTable using DataRow objectDataRow row = null;
for (int i = 0; i < 5; i++)
{
row = dTable.NewRow(); row["AutoID"] = i + 1; row["Name"] = i + " - Ram"; row["Address"] = "Ram Nagar, India - " + i; dTable.Rows.Add(row);
}
Instead of using the column name, you can use ColumnIndex too, however it is not suggested as you might want to add a column in the mid of the table then you will need to change your code wherever you have specified the index of the column. Same applies while reading or writing values into Database column.
Asiging the value of column using Arrays
In following code, I have specified the values of every column as the array separated by comma (,) in the Add method of the dTable.Rows.
// manually adding rows using array of valuesdTable.Rows.Add(6, "Manual Data - 1", "Manual Address - 1, USA");
dTable.Rows.Add(7, "Manual Data - 2", "Manual Address - 2, USA");
Modifying data into DataTable
Modifying Row Data
To edit the data of the row, sets its column value using row index or by specifying the column name. In below example, I am updating the 3rd row of the DataTable as I have specified the row index as 2 (dTable.Rows[2]).
// modify certain values into the DataTabledTable.Rows[2]["AutoID"] = 20;
dTable.Rows[2]["Name"] = "Modified";
dTable.Rows[2]["Address"] = "Modified Address";
dTable.AcceptChanges();
Deleting Row
To delete a row into DataTable, call the rows.Delete() method followed by AcceptChanges() method. AcceptChanges() method commits all the changes made by you to the DataTable. Here Row[1] is the index of the row, in this case 2nd row will be deleted as in collection (here rows collection) count start from 0.
// Delete rowdTable.Rows[1].Delete();
dTable.AcceptChanges();

Filtering data from DataTable
To filter records from the DataTable, use Select method and pass necessary filter expression. In below code, the 1st line will simply filter all rows whose AutoID value is greater than 5. The 2nd line of the code filters the DataTable whose AutoID value is greater than 5 after sorting it.
DataRow[] rows = dTable.Select(" AutoID > 5");
DataRow[] rows1 = dTable.Select(" AutoID > 5", "AuotID ASC");
Note that Select method of the DataTable returns the array of rows that matche the filter expression. If you want to loop through all the filtered rows, you can use foreach loop as shown below. In this code, I am adding all the filtered rows into another DataTable.
foreach (DataRow thisRow in rows)
{
// add values into the datatable dTable1.Rows.Add(thisRow.ItemArray);
}
Working with Aggregate functions (Updated on 18-Nov-08)
We can use almost all aggregate functions with DataTable, however the syntax is bit different than standard SQL.
Suppose we need to get the maximum value of a particular column, we can get it in the following way.
DataRow[] rows22 = dTable.Select("AutoID = max(AutoID)");
string str = "MaxAutoID: " + rows22[0]["AutoID"].ToString();
To get the sum of a particular column, we can use Compute method of the DataTable. Compute method of the DataTable takes two argument. The first argument is the expression to compute and second is the filter to limit the rows that evaluate in the expression. If we don't want any filteration (if we need only the sum of the AutoID column for all rows), we can leave the second parameter as blank ("").
object objSum = dTable.Compute("sum(AutoID)", "AutoID > 7");
string sum = "Sum: " + objSum.ToString();
// To get sum of AutoID for all rows of the DataTable
object objSum = dTable.Compute("sum(AutoID)", "");

Sorting data of DataTable
Oops !. There is no direct way of sorting DataTable rows like filtering (Select method to filter DataRows).
There are two ways you can do this.
Using DataView
See the code below. I have created a DataView object by passing my DataTable as parameter, so my DataView will have all the data of the DataTable. Now, simply call the Sort method of the DataView and pass the sort expression. Your DataView object have sorted records now, You can either directly specify the Source of the Data controls object like GridView, DataList to bind the data or if you need to loop through its data you can use ForEach loop as below.
// Sorting DataTableDataView dataView = new DataView(dTable);
dataView.Sort = " AutoID DESC, Name DESC";
foreach (DataRowView view in dataView)
{
Response.Write(view["Address"].ToString());
}
Using DataTable.Select() method
Yes, you can sort all the rows using Select method too provided you have not specified any filter expression. If you will specify the filter expression, ofcourse your rows will be sorted but filter will also be applied. A small drawback of this way of sorting is that it will return array of DataRows as descibed earlier so if you are planning to bind it to the Data controls like GridView or DataList you will have for form a DataTable by looping through because directly binding arrays of rows to the Data controls will not give desired results.
DataRow[] rows = dTable.Select("", "AutoID DESC");
Writing and Reading XmlSchema of the DataTable
If you need XmlSchema of the DataTabe, you can use WriteXmlSchema to write and ReadXmlSchema to read it. There are several overloads methods of both methods and you can pass filename, stream, TextReader, XmlReader etc. as the parameter. In this code, the schema will be written to the .xml file and will be read from there.
// creating schema definition of the DataTabledTable.WriteXmlSchema(Server.MapPath("~/DataTableSchema.xml"));
// Reading XmlSchema from the xml file we just created
DataTable dTableXmlSchema = new DataTable();
dTableXmlSchema.ReadXmlSchema(Server.MapPath("~/DataTableSchema.xml"));
Reading/Writing from/to Xml
If you have a scenario, where you need to write the data of the DataTable into xml format, you can use WriteXml method of the DataTable. Note that WriteXml method will not work if you will not specify the name of the DataTable object while creating it. Look at the first code block above, I have passed "Dynamically_Generated" string while creating the instance of the DataTable. If you will not specify the name of the DataTable then you will get error as WriteXml method will not be able to serialize the data without it.
// Note: In order to write the DataTable into XML, // you must define the name of the DataTable while creating it
// Also if you are planning to read back this XML into DataTable, you should define the XmlWriteMode.WriteSchema too 
// Otherwise ReadXml method will not understand simple xml file 
dTable.WriteXml(Server.MapPath("~/DataTable.xml"), XmlWriteMode.WriteSchema);
// Loading Data from XML into DataTable
DataTable dTableXml = new DataTable();
dTableXml.ReadXml(Server.MapPath("~/DataTable.xml"));
If you are planning to read the xml you have just created into the DataTable sometime later then you need to specify XmlWriteMode.WriteSchema too as the 2nd parameter while calling WriteXml method of the DataTable otherwise normally WriteXml method doesn't write schema of the DataTable. In the abscence of the schema, you will get error (DataTable does not support schema inference from Xml) while calling ReadXml method of the DataTable.

Fuente
lunes, febrero 13, 2012
Posted by Carlos
Tag :

SharePoint 2010 PDF Icon

Sharepoint no tiene por Default el Icono de los archivos .PDF que subimos a las bibliotecas o adjuntamos en elementos de Listas…

image

Asi que el camino mas logico es ver de que la modalidad de carga, no se modifique en 2010, como sabemos, la carpeta de SharePoint 2010 es ahora “14”

image 

Dentro de la carpeta TEMPLATE, tenemos la carpeta XML donde se encuentra el Archivo a Editar, DOCICON.XML

image

Adicionamos una linea haciendo referencia al icono de .PDF

image

Copiamos el archivo en la carpeta de Imagenes (Descargamos un icono en formato .GIF y de 16x16 pixeles para que concuerde con los demas iconos que tenemos en SharePoint)

image

Luego, reiniciamos el IIS para que tome los datos, y listo…
martes, enero 17, 2012
Posted by Carlos

Cuestion de amores

Bob Marley dijo: '' Puedes no ser su primero, su ultimo o su único. Ella amo antes y puede amar de nuevo. Pero si ella te ama ahora, Que otra cosa importa? Ella no es perfecta, tú tampoco lo eres, y ustedes dos nunca serán perfectos. Pero si ella puede hacerte reír al menos una vez, te hace pensar dos veces, si admite ser humana y cometer errores, no la dejes ir y dale lo mejor de ti. Ella no va a ... recitarte poesía, no está pensando en ti en todo momento, pero te dará una parte de ella que sabe que podrías romper, su corazón.. No la lastimes, no la cambies, y no esperes de ella más de lo que puede darte. No analices. Sonríe cuando te haga feliz, grita cuando te haga enojar y extráñala cuando no esté. Ama con todo tu ser cuando recibas su amor. Porque no existen las chicas perfectas, pero siempre habrá una chica que es perfecta para ti.. ''
martes, diciembre 06, 2011
Posted by Carlos
Tag :

Siempre es preciso saber

Siempre es preciso saber cuándo se acaba una etapa de la vida. Si insistes en permanecer en ella más allá del tiempo necesario, pierdes la alegría y el sentido del resto. Siempre es necesario cerrar ciertas puertas con una llave, que luego debes olvidar...
martes, noviembre 29, 2011
Posted by Carlos
Tag :

Ordering Interger values stored in Varchar column

I have seen many newbies asking "How do I sort the numbers stored in varchar columns?"
Here are some methods
declare @t table(data varchar(15))
insert into @tselect '6134' union allselect '144' union allselect '7345' union allselect '109812' union allselect '100074'union allselect '1290' union allselect '45764'
--Method 1
select data from @torder by cast(data as int)
--Method 2
select data from @torder by data+0
--Method 3
select data from @torder by len(data),data
--Method 4
select data from @torder by replace(str(data),' ','0')
--Method 5
select data from @tgroup by dataorder by replicate('0',len(data)),data
--Method 6

select data from @torder by replicate('0',(select max(len(data+0)) from @t)-len(data))+data
--Method 7 select data from @tcross join
(
        select len(max(data+0)) as ln from @t) as torder by replicate('0',ln-len(data))+data
jueves, octubre 13, 2011
Posted by Carlos

Validar cero SQL

IsNull( Nullif(valor,0), 1)
miércoles, octubre 05, 2011
Posted by Carlos

DDAY.UPDATE error creating bootstrap

************** Exception Text ************** System.TypeLoadException: Could not load type 'System.Runtime.Versioning.TargetFrameworkAttribute' from assembly 'mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.

Bueno en mi caso funciono, cambiando la clase Compiler.cs
de: foreach (object obj in assembly.GetCustomAttributes(true)){}
a: foreach (object obj in assembly.GetCustomAttributesData()){}

Aún mas fácil , solo se debe cambiar el proyecto para que utilice a Taget Framework 4
miércoles, agosto 31, 2011
Posted by Carlos

Solución – Error al Instalar SQL Server 2008 R2



Error: “SQL server setup media does not support the language of the OS or does not have ENU localized files. Use the matching language-specific SQL Server media or change the OS locale through Control Panel.”
Solución:
  1. Ir al Panel de Control
  2. Configuración regional y de idioma
  3. Formatos: Seleccionar Español( España)
  4. Aplicar Cambios
  5. clip_image002
  6. Ejecutamos la Instalación de SQL SERVER 2008 R2
  7. Una vez instalado SQL Server podemos regresar a nuestra configuración anterior
  8. Listo! , Todo solucionado
jueves, julio 28, 2011
Posted by Carlos

Obtener diccionario de datos SQL Server

SELECT SchemaName = left(S.name, 45),
       TableName = cast(T.name AS VARCHAR(140)),
       ColOrder = C.column_id, --cast(C.column_id as varchar(6)),
       PK = isnull(key_ordinal, ''),
       ColumnName = left(C.name, 100),
       TYPE = left(Y.Name, 10), TipoUsu = left(Y2.Name, 10),
       LENGTH = CASE WHEN max_length = -1 THEN 'Max' ELSE cast(max_length AS VARCHAR(10)) END,
       C.PRECISION, C.Scale, Identi = is_identity, Nulos = C.is_nullable,
       Defaulf = cast(D.DEFINITION AS VARCHAR(10)),
       Collation = cast(C.Collation_name AS VARCHAR(20)), --C.* --, Y.*
       ColumnDescription = cast(P.value AS VARCHAR(500)),
       TableDescription = cast(P2.value AS VARCHAR(500))
FROM (
   SELECT object_id, schema_id, name FROM sys.VIEWS
   UNION ALL
   SELECT object_id, schema_id, name FROM sys.TABLES) T
inner join sys.schemas S ON T.schema_id = S.schema_id
inner join sys.COLUMNS C ON T.object_id = C.object_id
left join sys.systypes Y ON Y.xtype = C.system_type_id AND Y.status = 0
left join sys.systypes Y2 ON Y2.xtype = C.system_type_id AND Y2.status = 1
left join sys.default_constraints D ON D.object_id = C.default_object_id
left join sys.extended_properties P ON P.major_id = T.object_id AND P.minor_id = C.column_Id
left join sys.extended_properties P2 ON P2.major_id = T.object_id AND P2.minor_id = 0
left join (
 SELECT I.object_id, column_id, key_ordinal
 FROM sys.INDEXES I
 inner join sys.index_columns L ON I.object_id = L.object_id AND I.index_id = L.index_id
 inner join sys.key_constraints C ON I.object_id = C.parent_object_id AND I.name = C.name
   WHERE C.TYPE = 'PK'
) I ON I.object_id = T.Object_id AND I.column_id = C.column_id
WHERE T.name <> 'sysdiagrams'
lunes, julio 25, 2011
Posted by Carlos

Obtener el nombre de método en Run time

/// /// Devuelve el nombre del metodo desde el que se invoca este metodo 
/// public static string MethodContext()
{
   System.Diagnostics.StackFrame stack = 
      new System.Diagnostics.StackFrame(1);
   return stack.GetMethod().Name;
}

jueves, julio 21, 2011
Posted by Carlos
Tag :

Invocando un Servicio WCF Asincrónicamente


En WCF existen varias formas para consumir un servicio de forma asincrónica. La más simple quizás es poner el asincronismo del lado del cliente, que es lo que vamos a hacer en este post.
Para iniciar vamos a crear un proyecto del tipo WCF ServiceLibrary y vamos a crear un servicio muy simple que tiene solamente un método que retorna el número de frutas – strings – que se lo soliciten vía parámetro a la operación. La interface – contrato – del servicio se ve a continuación:
[ServiceContract(Namespace="http://drojasm.net")]
public interface IServicioProductos{
    [OperationContract]
    List<string> ObtenerProductos(int pCantidad);
}

Seguidamente procedemos con el código para implementar la operación. Como podemos ver en el siguiente código, este simplemente lo que hace es hacer un for y agregar un string a la lista por cada iteración. Nótese además la línea en donde ponemos a dormir el thread del servicio, esto con el fin de que nos de tiempo de hacer algo diferente en el UI mientras el servicio se ejecuta.
public class ServicioProductos : IServicioProductos
    {
        public List<string> ObtenerProductos(int pCantidad)
        {
            List<string> _productos = new List<string>();

            for (int i = 0; i < pCantidad; i++)
            {
                _productos.Add("Fruta Número " + i.ToString());
            }

            System.Threading.Thread.Sleep(5000);
            return _productos;

        }
    }
}

Ahora vamos a proceder a crear el cliente que va a consumir el servicio. En este caso vamos a utilizar una aplicación WPF. Lo primero que vamos a hacer después de crear la aplicación es agregar una referencia al servicio como se hace tradicionalmente; es decir, botón derecho sobre el proyecto, seleccionar agregar referencia, y en la pantalla de configuración de la referencia del servicio, poner la dirección del servicio – en este caso hosteado en el wcfsvchost – y por último obtener el wsdl del mismo.

image

Sin embargo, esta vez vamos a seleccionar además el botón de “Advanced” para configurar la generación del proxy. Luego en esta pantalla vamos a configurar la generación del proxy, seleccionando en esta la opción para generar clientes asincrónicos. Esta opción nos va a generar además de los métodos tradicionales sincrónicos, los métodos necesarios para invocar el servicio utilizando asincronismo.

image

Luego seleccionamos Ok en las siguientes dos pantallas y se procede con la generación del proxy. Como podemos ver en la siguiente figura, el proxy genera los métodos para consumir asincrónicamente el servicio.

image

Ahora procedemos a crear la pantalla en WPF para invocar el servicio. Para esto, vamos a agregar un listbox en donde pintamos el resultado de cada servicio. Además vamos a poner un textbox para que el usuario – yo Sonrisa - digite cuantos elementos quiere en la lista. También vamos a poner dos botones, uno para invocar el servicio sincrónicamente y otro asincrónicamente. Por último, vamos a poner un botón que va a lanzar un MessageBox cuando se le da click; el objetivo de este es demostrar que cuando invocamos el servicio de forma asincrónica, podemos llevar a cabo otras tareas mientras que cuando lo hacemos de forma sincrónica la pantalla se bloquea. El XAML de la pantala es el siguiente:
<Window x:Class="ClienteAsincronicoWCF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="447">
    <Grid>
        <ListBox Height="197" HorizontalAlignment="Left" Margin="47,74,0,0" Name="lstFrutas" VerticalAlignment="Top" Width="120" />
        <Label Content="Frutas" Height="28" HorizontalAlignment="Left" Margin="47,40,0,0" Name="label1" VerticalAlignment="Top" />
        <Button Content="Cargar Sincronicamente" Height="23" HorizontalAlignment="Left" Margin="213,220,0,0" Name="btnSincronico" VerticalAlignment="Top" Width="140" Click="btnSincronico_Click" />
        <Button Content="Cargar Asincronicamente" Height="23" HorizontalAlignment="Left" Margin="213,249,0,0" Name="btnAsincronico" VerticalAlignment="Top" Width="140" Click="btnAsincronico_Click" />
        <Label Content="Cantidad de Productos" Height="28" HorizontalAlignment="Left" Margin="213,146,0,0" Name="label2" VerticalAlignment="Top" />
        <TextBox Height="23" HorizontalAlignment="Left" Margin="213,180,0,0" Name="txtCantidad" VerticalAlignment="Top" Width="140" />
        <Button Height="75" HorizontalAlignment="Left" Margin="269,40,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click">
            <Button.Content>
                <StackPanel>
                    <Image Height="48" Name="image1" Stretch="Fill" Width="48" Source="/ClienteAsincronicoWCF;component/pens.png" />
                    <Label Content="Otra Tarea" Height="28" Name="label3" />
                StackPanel>
            Button.Content>
        Button>
    Grid>
Window>

Y la pantalla en modo de diseño es la siguiente:

image

El código del botón para la invocación sincrónica del servicio es el siguiente:
private void btnSincronico_Click(object sender, RoutedEventArgs e)
{
    lstFrutas.ItemsSource = null;
    ServicioProductosClient _proxy = new ServicioProductosClient();
    lstFrutas.ItemsSource =  _proxy.ObtenerProductos(int.Parse(txtCantidad.Text));
}

No olvidar agregar el namespace del servicio – el que digitamos en la pantalla para agregar la referencia al mismo.
using ClienteAsincronicoWCF.ReferenciaServicioProductos;

Como podemos ver en el código del botón, la forma de invocar este servicio es la tradicional; este procedimiento bloquea la pantalla y no permite realizar ninguna otra tarea mientras la invocación al servicio se esta ejecutando.

image

Ahora procedemos a agregar el código de la llamada asincrónica.
private void btnAsincronico_Click(object sender, RoutedEventArgs e)
{
    lstFrutas.ItemsSource = null;
    ServicioProductosClient _proxy = new ServicioProductosClient();
    AsyncCallback _callBack =
        delegate(IAsyncResult pResult)
        {
            this.Dispatcher.BeginInvoke((Action)delegate { lstFrutas.ItemsSource = _proxy.EndObtenerProductos(pResult); });                    
        };

    _proxy.BeginObtenerProductos(int.Parse(txtCantidad.Text), _callBack, _proxy);           
}

En este código nos vamos a detener un momento para analizarlo un poco mas detalladamente. En primera instancia procedemos a crear un delegate en donde vamos a obtener la respuesta del servicio. En este delegate además, debemos hacer un llamado a la operación BeginInvoke porque el thread en donde se invoca el proceso es diferente al thread del UI, por lo tanto no se puede asignar el resultado directamente a la lista. Por último, invocamos el servicio de forma asincrónica utilizando el método BeginObtenerProductos.

En el botón del MessageBox tenemos el siguiente código:
private void button1_Click(object sender, RoutedEventArgs e)
{
    MessageBox.Show("Iniciando otra operación");
}

Ahora procedemos a ejecutar el servicio con el botón btnAsincronico. Como podemos ver en la siguiente imagen, se pudo invocar al messageBox mientras el servicio estaba procesándose.

image


miércoles, junio 29, 2011
Posted by Carlos
Tag :

Saving changes is not permitted. The changes that you have made require the following tables to be dropped and re-created

ERROR:

“Saving changes is not permitted. The changes that you have made require the following tables to be dropped and re-created. You have either made changes to a table that can’t be re-created or enabled the option Prevent saving changes that require the table to be re-created.”
This error happens because “Saving Changes is not permitted” when using SQL Server 2008 Management Studio to modify the structure of a table especially when SQL Server needs to drop and recreate a table to save the structural changes. It is always advised to make a structural change for a table using TSQL. However, it is a convenient option for database developers to use SQL Server Management Studio make such changes  as the Prevent Saving Changes That Require Table Re-creation  option is enabled by default in SQL Server 2008 Management Studio.
Disable “Prevent saving changes that require the table re-creation” 
1.    Open SQL Server 2008 Management Studio (SSMS). Click Tools menu and then click on Options… as shown in the snippet below.

2.    In the navigation pane of the Options window, expand Designers node and select Table and Database Designers option as shown in the below snippet. Under Table Options you need to uncheck “Prevent saving changes that require the table re-creation” option and click OK to save changes.
This option when enabled prevents users from making structural changes to table using SQL Server Management Studio especially when SQL Server needs to recreate the table to save changes. By default, this option is checked and you need to uncheck this option to allow users to make any structural change through SSMS that   require table recreation.
A table needs to be recreated whenever any of the below   changes are made to the table structure.
·         Insert a new column in the middle of the table.
·         Add a new column in the table.
·         Change the Allow Nulls setting of a column.
·         Modify the identity property of a column.
·         Reorder the columns within a table.
·        Modify the datatype of a column.
Once you have disabled “Prevent saving changes that require the table re-creation” option you can go ahead and save the changes to the Employee Table. This will create a Validation Warning dialog box as shown in the below snippet. The warning message will be “One or more existing columns have ANSI_PADDING ‘off’ and will be re-created with ANSI_PADDING ‘on’”. Click “Yes” to save the changes.
Risks of Turing Off “Prevent Saving Changes that Require Table Re-creation” in SSMS
If you turn off this feature then you can avoid table recreation. However, if you have the Change Tracking feature of SQL Server 2008 enabled to track the table changes then the change tracking information will be lost completely whenever table is recreated. So, it is always advised to use this feature very carefully especially in a production environment.
Posted by Carlos

Cambiar el lenguaje de un sitio de Windows Sharepoint Services 3.0

Si estás leyendo esta página es muy probable que tu sitio de SharePoint WSS 3.0 se encuentre en un lenguaje distinto al que tu quieres por ejemplo tengo mi sitio de SharePoint en Ingles pero deseo cambiarlo a español y lo peor es que el sitio está lleno de información está en producción y está altamente personalizado, Instalaste el language pack en español pero no paso nada. Pues estas en el lugar apropiado para solucionar el incidente.

1. Instalar el Language Pack en español

En el sitio de la descarga, asegúrate deseleccionar el lenguaje Spansih



2. Instalar En el servidor el SQL Server Management Studio Express


3. Instalar el SQL Server Native Client

Clic aqui para ir al sitio de descarga

Una vez instalado, Abrir el Sql Server Management Studio Express y Conectarse a la instancia de SharePoint v3 con el canal named pipe, para esto, mirar en el registro (Inicio/Ejecutar Regedit) y navegar en la siguiente direccion:

HKEY_LOCAL_MACHINE
SOFTWARE
MicrosoftMicrosoft SQL Server
MICROSOFT##SSEE
MSSQLServer
SuperSocketNetLib
Np

Abrir la key llamada NamedPipe y copiar el contenido de esa key
Cierre el Editor de Registro de Windows.

4. Abra el sql server management studio express



Conectarse con los siguientes parametros:
Server Name: el named pipe que copiaste en la key NamedPipe del regedit
Autenticación: windows
Clic en Conectar


5. Cambiar el lenguaje


Navegar hasta la base de datos wss_content

Buscar la tabla dbo.webs y darle clic derecho abrir




Buscar el campo LANGUAGE y LOCALE y cambiarlos por el id del lenguaje en español tradicional es decir el 3082 el ingles Eu es el 1033

Esta tarea se puede hacer con un QUERY
UPDATE DBO.WEBS SET LANGUAGE = 3082, LOCALE = 3082
Cierre el SQL Server Management Studio Express.

6. Abra el sitio de SharePoint que estaba en Ingles

Hasta el momento hemos hecho la mayor parte del trabajo lo que sigue a continuación es revisar el sitio y mirar que algunos formularios tienen contenido en ingles, esto es por que cuando sitio del lenguaje anterior fue creado, el SharePoint generó unos formularios bajo los cuales incluyo el lenguaje Ingles por lo tanto, es necesario abrirlos con el SharePoint Designer y cambiar a mano el contenido de español a Ingles.


Eider Mauricio Aristizabal


martes, junio 14, 2011
Posted by Carlos

Paginar una colección List

public List ListaPaginada(int pPagina, int pItemsPorPagina)
{          
   return ColFiltrada.Skip((pPagina - 1) * pItemsPorPagina).Take(pItemsPorPagina).ToList();
}
viernes, junio 10, 2011
Posted by Carlos
Tag :

Como amo a mi mamá

 7 años: ¡¡¡Mami Te Amo!!! 
10 años: ¡¡¡Mamá Te Quiero!!! 
15 años: ¿Ma ...má? 
17 años:¡¡¡Cómo jodes vieja!!!
20 años: ¡¡¡Quiero irme de esta casa!!! 
35 años: ¡¡¡Quiero volver con mamá!!! 
50 años: No te vayas viejita... 
70 años: ¡¡¡Cuanto daría por cinco minutos con mi mamá!!! 
viernes, junio 03, 2011
Posted by Carlos
Tag :

Utilizando generics para hacer un DeepCopy

Para hacer una copia de un objeto y tengamos dos objetos independientes, se requiere un DeepCopy:
public static class DeepCopier
    {
        /// Se usa un tipo generic para poder copiar cualquier objeto
        public static T Copy(T pItem)        {
            BinaryFormatter vFormatter = new BinaryFormatter();
            MemoryStream vStream = new MemoryStream();
            vFormatter.Serialize(vStream, pItem);
            vStream.Seek(0, SeekOrigin.Begin);
            T vResult = (T)vFormatter.Deserialize(vStream);
            vStream.Close();
            return vResult;
        }
    }

Para utilizarlo:

 /// Copiamos el objeto por si se va a cancelar
cGrid vObjCancel = DeepCopier.Copy(ConfigReporto);
miércoles, junio 01, 2011
Posted by Carlos

Seleccionar un archivo, con un item de un PropertyGrid

Se debe crear una clase que derive de UITypeEditor

public class MyControl : Control
{
    string filePath;
    [Editor(typeof(FileLocationEditor), typeof(UITypeEditor))]
    public string FilePath
   {
        get { return filePath; }
        set { filePath = value; }
    }
}

public class FileLocationEditor : UITypeEditor
{
        public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) {
        return UITypeEditorEditStyle.Modal;
    }

    public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
   {
        using (OpenFileDialog ofd = new OpenFileDialog())
          {
            // set file filter info here
            if (ofd.ShowDialog() == DialogResult.OK) {
                return ofd.FileName;
            }
        }
      return value;
  }
lunes, mayo 30, 2011
Posted by Carlos

Que es postear



Remitir un mensaje al público mediante un foro, bitácora, grupo de noticias u otro medio informático similar

Un post se traduce en español como ‘artículo’, aunque se suele utilizar con la terminología inglesa o el nombre de ‘entradas’ en la publicaciones hechas en blogs.
Los posts son los artículos que vamos publicando en la parte central del blog y que se ordenan de manera cronológica. Por lo general, los posts tienen un titular, un cuerpo del artículo donde se puede introducir texto, fotografía, código html e incluso audio.
Los posts están archivados por categorías y también se acompañan de palabras clave relacionadas con el contenido del artículo.
Además, por lo general, los posts permiten que los lectores realicen comentarios, aunque es una función que se puede habilitar o deshabilitar en función de interés del autor del blog.
Este pequeño artículo que estás leyendo es un post!!!


viernes, mayo 27, 2011
Posted by Carlos

How big should text be? What's the ideal font size?

How can you be certain that everyone in the audience can read the text on your slides?
While the fonts and colors you choose have a definite impact on legibility, the single biggest factor is text size. The 8H rule is the time-honored way to make sure that even the folks in the back row can read the text on your slides.
The 8H rule says that the maximum viewing distance shouldn't be more than 8 times the height (H) of the screen; if that condition is met then as long as your text is at least 1/50th the height of the screen, then it'll be legible at the maximum viewing distance. That assumes that the person in the back row has good eyes, that the projected image is perfectly crisp, and that no other factors interfere. And it's an absolute minimum, not a recommended size.
A normal screen show slide in PowerPoint is 7.5 inches or 540 points tall, so the absolute, don't go below it minimum text size would be 540 / 50 or roughly 11 point text. For 35mm slides or good quality overheads, that's not unreasonable. For screenshow projection, it's wildly optimistic. You simply can't form legible text at this height ... roughly 12 pixels ... in most fonts. For projected 800x600 screens, I'd at least double that, or use 1/25th the screen height to determine minimum text size. That translates to roughly 22 points. Use 24 points to give yourself some extra leeway in case projection conditions or your audience's vision aren't perfect (they won't be).
Keep in mind that your screen may not be big enough to meet the 8H rule. If not, you'll have to compensate. For example, if the screen is 5 feet high in an 80 foot deep room, it's only half the recommended size, so you'll need to double the minimum text height to compensate.
miércoles, mayo 25, 2011
Posted by Carlos

Script para mostrar tablas segun su tamaño físico y numero de registros

Select Tabla,
       cast(Reservado    * d.low as int) ReservadoKB,
       cast(Data         * d.low as int) DatosKB,
       cast((Usado-Data) * d.low as int) IndicesKB,
       cast((Reservado-Data) * d.low as int) NoUsadoKB,
       registros
from (
select left(o.name,35) Tabla, o.id, ii.reserved Reservado,
      isnull(ip1.pages, 0) + isnull(ip2.pages, 0) data,
      ip3.usado,   --indexp= usado - data    no usado = reserved - usado
      r.Registros
from sysobjects o
inner join sysindexes ii on o.id = ii.id
inner join (select id, sum(dpages) pages from sysindexes where indid < 2 group by id) ip1
     on o.id = ip1.id
left  join (select id, isnull(sum(used), 0) pages from sysindexes where indid = 255 group by id) ip2
     on o.id = ip2.id
inner join (select id, sum(used) Usado from sysindexes where indid in (0, 1, 255) group by id) ip3
     on o.id = ip3.id
inner join (select id, rows Registros from sysindexes where indid < 2) r
     on o.id = r.id
where o.xtype = 'U'
and   ii.indid in (0, 1, 255)
) A, master.dbo.spt_values D
where D.number = 1
and   D.type = 'E'
lunes, mayo 23, 2011
Posted by Carlos

Populares!

- Copyright © - Oubliette - -Metrominimalist- Powered by Blogger - Designed by Johanes Djogan -