miércoles, 27 de enero de 2010

Clase para conectarse a base de datos C#

http://comunicandotj.wordpress.com/2009/02/27/basedatos_csharp/
Pues bien, les mostrare la forma en como hasta hoy he trabajado con Bases de Datos tanto SQLExpress como SQL Server. Tal ves existan algunas otras mejores maneras de hacerlo, si conoces alguna porfavor hasmelo saber.

Primero que nada, les dire que Necesitamos hacer una Clase de Conexion la cual nos sirve tanto para Desktop Application como para Web Site.

Clase Conexion:

/* Importamos las Librerias Necesarias para Trabajar */

using System.Data;

using System.Data.SqlClient;

using System.Data.Common;

/* Creamos la Clase */

class Conexion

{

private SqlConnection Con; // Obj Conexion

public Conexion()

{

string DtsConection = “”; // Contendra los Datos las Conexion.

/* Para trabajar con el servidor SQLExpress de la maquina */

string DtsConection = “Data Source=.\SQLEXPRESS;Initial Catalog=NOMBRE_BD; ” + “Integrated Security=True;”;

/* Para trabajar con Archivo de BD (.mdf), si que este montado en SQLExpress */

//DtsConection = “Server=.\SQLExpress;AttachDbFilename=C:\Direccion\NOMBRE.mdf; Database=NOMBRE;

Trusted_Connection=Yes;”;

/* Para trabajar con un servidor remoto Ya sea una Base de datos Remota o en Caso de WEB SITE cuando la pongamos en el Host */

/* Necesitamos la IP del Servidor de BD, el puerto generalmente es 1533, Usuario y Password lo proporciona el Hostring */

//DtsConection = “Data Source=72.17.135.40,1533; Database=NOMBRE_BD; User ID=USUARIO; Password=PASSWORD;”;

Con = new SqlConnection(DtsConection);

}

public void Abrir() // Metodo para Abrir la Conexion

{

Con.Open();

}

public void Cerrar() // Metodo para Cerrar la Conexion

{

Con.Close();

}

public DataSet Ejecutar(string Comando, string Tabla) // Metodo para Ejecutar Comandos

{

SqlDataAdapter CMD = new SqlDataAdapter(Comando, Con); // Creamos un DataAdapter con el Comando y la Conexion

DataSet DS = new DataSet(); // Creamos el DataSet que Devolvera el Metodo

CMD.Fill(DS, Tabla); // Ejecutamos el Comando en la Tabla

return DS; // Regresamos el DataSet

}


} // Fin de la Clase

Ahora que Ya tenemos Nuestra Clase Conexion, lo unico que necesitamos para Conectarnos a una Base de Datos o Ejecuar un Comando, etc. es:

Crear un Objeto del Tipo Conexion.

Conexion CN = new Conexion();

Abrir la Conexion

CN.Abrir();

Ejecutar los Comando que Deseemos.

Recordemos que el Metodo Ejecutar no Regresa un Objeto del tipo DataSet que es como una Colecion de Tablas. Y si queremos poner el resultado del comando en una Tabla hariamos lo siguiente:

DataTable Tabla = CN.Ejecutar(“SELECT * FROM USUARIOS”,”USUARIOS”).Tables[0];

Antes de Terminar permiten Recomendarles la forma de utilizar la clase Conexion y el Manejo de Excepciones.

Try

{

CN.Abrir();

DataTable DT = CN.Ejecutar(“COMANDO…”,”TABLA”).Tables[0];

CN.Cerrar();

}

Catch (Exception ex) // Maneja los Posibles Errores

{

// Para Mostrar la origen del Error

MessageBox.Show(ex.ToString());

}

Finally

{

CN.Cerrar();// Evitar que la Conexion quede Abierta

}

martes, 26 de enero de 2010

Convertidor de Visual Basic a C#

http://www.developerfusion.com/tools/convert/vb-to-csharp/

archivos en visual basic

http://www.recursosvisualbasic.com.ar/htm/vb-net/3-ejemplos-con-archivos-en-vb-net.htm

Serializar archivos con VB.NET

http://www.startvbdotnet.com/files/default.aspx

Files in VB .NET

Working with Files

File handling in Visual Basic is based on System.IO namespace with a class library that supports string, character and file manipulation. These classes contain properties, methods and events for creating, copying, moving, and deleting files. Since both strings and numeric data types are supported, they also allow us to incorporate data types in files. The most commonly used classes are FileStream, BinaryReader, BinaryWriter, StreamReader and StreamWriter.

FileStream Class

This class provides access to standard input and output files. We use the members of FileAccess, FileMode and FileShare Enumerations with the constructors of this class to create or open a file. After a file is opened it's FileStream object can be passed to the Binary Reader, BinaryWriter, Streamreader and StreamWriter classes to work with the data in the file. We can also use the FileStreamSeek method to move to various locations in a file which allows to break a file into records each of the same length.

StreamReader and StreamWriter Class

The StreamReader and StreamWriter classes enables us to read or write a sequential stream of characters to or from a file.

BinaryReader and BinaryWriter Class

The BinaryReader and BinaryWriter classes enable us to read and write binary data, raw 0's and 1's, the form in which data is stored on the computer.

The following examples puts some code to work with textual data using FileStream and StreamReader and StreamWriter classes.

Code to create a File

Imports System.IO
'NameSpace required to be imported to work with files
Public Class Form1 Inherits System.Windows.Forms.Form
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e_
As System.EventArgs) Handles MyBase.Load
Dim fs as New FileStream("file.doc", FileMode.Create, FileAccess.Write)
'declaring a FileStream and creating a word document file named file with
'access mode of writing
Dim s as new StreamWriter(fs)
'creating a new StreamWriter and passing the filestream object fs as argument
s.BaseStream.Seek(0,SeekOrigin.End)
'the seek method is used to move the cursor to next position to avoid text to be
'overwritten
s.WriteLine("This is an example of using file handling concepts in VB .NET.")
s.WriteLine("This concept is interesting.")
'writing text to the newly created file
s.Close()
'closing the file
End Sub
End Class

The default location where the files we create are saved is the bin directory of the Windows Application with which we are working. The image below displays that.

Code to create a file and read from it

Drag a Button and a RichTextBox control onto the form. Paste the following code which is shown below.

Imports System.IO
'NameSpace required to be imported to work with files
Public Class Form1 Inherits System.Windows.Forms.Form
Private Sub Button1_Click(ByVal....., Byval.....)Handles Button1.Click
Dim fs as New FileStream("file.doc", FileMode.Create, FileAccess.Write)
'declaring a FileStream and creating a document file named file with
'access mode of writing
Dim s as new StreamWriter(fs)
'creating a new StreamWriter and passing the filestream object fs as argument
s.WriteLine("This is an example of using file handling concepts in VB .NET.")
s.WriteLine("This concept is interesting.")
'writing text to the newly created file
s.Close()
'closing the file

fs=New FileStream("file.doc",FileMode.Open,FileAccess.Read)
'declaring a FileStream to open the file named file.doc with access mode of reading
Dim d as new StreamReader(fs)
'creating a new StreamReader and passing the filestream object fs as argument
d.BaseStream.Seek(0,SeekOrigin.Begin)
'Seek method is used to move the cursor to different positions in a file, in this code, to
'the beginning
while d.peek()>-1
'peek method of StreamReader object tells how much more data is left in the file
RichTextbox1.Text &= d.readLine()
'displaying text from doc file in the RichTextBox
End while
d.close()
End Sub

The image below displays output of the above code.

miércoles, 13 de enero de 2010

Guardar archivos en Base de datos SQL Server

http://www.picacodigos.com/CommentView,guid,0a921d29-8810-49f8-90e2-98d4659a651b.aspx

domingo, 3 de enero de 2010

Mejorar el rendimiento de sql server

he aqui los vinculos que indican las opciones a deshabilitar y lo relacionado con los archivos ndf
http://msdn.microsoft.com/es-es/library/ms179316.aspx
http://consejosdelguru.blogspot.com/2007/10/mejorar-rendimiento-de-sql-server-2000.html