viernes, 30 de mayo de 2008

Operaciones de Acceso a datos Asincronico

1 comentario:
Se han fijado que en los commands tiene nuevos metodos que son parecidos a los que ya conoces pero tienen la palabra Begin ante puesta, como por ejemplo el ExecuteReader tiene
BeginExecuteReader y EndExecuteReader estos son metodos del modelo asincronico, aqui un ejemplo de como utilizarlos.
Solo recuerde que para utilizar sincronia necesita poner la siguiente clausula en el connetion string:
Asynchronous Processing=true

Dim cnstring As String = "user id=sa;" & _
"password=pass;initial catalog=northwind;" & _
" data source=.\sqlexpress;Asynchronous Processing=true"


Dim cn1 As New SqlClient.SqlConnection(cnstring)
Dim cn2 As New SqlClient.SqlConnection(cnstring)
Dim cn3 As New SqlClient.SqlConnection(cnstring)


Dim commandText1 As String = _
"WAITFOR DELAY '0:0:01';" & _
"SELECT * FROM products " & _
" WHERE PRODUCTID=50"


Dim commandText2 As String = _
"WAITFOR DELAY '0:0:05';" & _
"SELECT * FROM products " & _
" WHERE PRODUCTID=50"


Dim commandText3 As String = _
"WAITFOR DELAY '0:0:10';" & _
"SELECT * FROM products " & _
" WHERE PRODUCTID=50"


Dim waitHandles(2) As Threading.WaitHandle
Try
cn1.Open()
Dim command1 As New SqlClient.SqlCommand(commandText1, cn1)
Dim result1 As IAsyncResult = command1.BeginExecuteReader()
waitHandles(0) = result1.AsyncWaitHandle


cn2.Open()
Dim command2 As New SqlClient.SqlCommand(commandText2, cn2)
Dim result2 As IAsyncResult = command2.BeginExecuteReader()
waitHandles(1) = result2.AsyncWaitHandle


cn3.Open()
Dim command3 As New SqlClient.SqlCommand(commandText3, cn3)
Dim result3 As IAsyncResult = command3.BeginExecuteReader()
waitHandles(2) = result3.AsyncWaitHandle


Dim index As Integer
For countWaits As Integer = 1 To 3
index = Threading.WaitHandle.WaitAny(waitHandles, 60000, False)
Select index
Case 0
     Dim reader1 As SqlClient.SqlDataReader
     reader1 = command1.EndExecuteReader(result1)
    If reader1.Read Then
          TextBox1.Text = "Terminado 1 - " & _
          System.DateTime.Now.ToLongTimeString()
    End If
    reader1.Close()

Case 1
     Dim reader2 As SqlClient.SqlDataReader
     reader2 = command2.EndExecuteReader(result2)
     If reader2.Read Then
            TextBox2.Text = "Terminado 2 - " & _
            System.DateTime.Now.ToLongTimeString()
     End If
   reader2.Close()
Case 2
     Dim reader3 As SqlClient.SqlDataReader
     reader3 = command3.EndExecuteReader(result3)
    If reader3.Read Then
        TextBox3.Text = "Terminado 3 - " & _
        System.DateTime.Now.ToLongTimeString()
    End If
    reader3.Close()
 Case Threading.WaitHandle.WaitTimeout
      Throw New TimeoutException("Timeout")
 End Select

  Next
Catch ex As Exception
     TextBox4.Text = ex.ToString
End Try
Ver

martes, 27 de mayo de 2008

Como leer y escribir fotos en una db en .net

No hay comentarios.:
Manejar objetos de gran tamaño en .net es sumamente facil, cuando me refiero a objetos grandes me refiero a Fotos o textos grandes.
aqui doy un ejemplo de como guardar fotos en la base de datos:

Guardar fotos


Tabla del sql server
CREATE TABLE fotos(
[codigo] [int] primary key IDENTITY (1, 1),
[nombre] [varchar](50) NULL,
[foto] [image] NULL
)



Tu formulario tiene que estar de la siguiente manera:


-- Codigo del boton Imagen
(despliega la ventan para seleccionar la imagen)


OpenFileDialog1.ShowDialog()
txtruta.Text = OpenFileDialog1.FileName


-- codigo del boton grabar

Dim cn As New SqlClient.SqlConnection("user id=sa;password=pass;initial" & _ "catalog=northwind;data source=.\sqlexpress")

'lectura de la foto de imagen a binario
Dim filePath As String = txtruta.Text
Dim stream As IO.FileStream = New IO.FileStream(filePath, _
IO.FileMode.Open, IO.FileAccess.Read)
Dim reader As IO.BinaryReader = New IO.BinaryReader(stream)
Dim foto() As Byte = reader.ReadBytes(stream.Length)
reader.Close()
stream.Close()

'guardado de la fot en la db
Dim cmd As SqlClient.SqlCommand = New SqlClient.SqlCommand( _
"INSERT INTO fotos( nombre, foto) " & _
"Values(@nombre, @foto)", _
cn)
cmd.Parameters.Add("@nombre", SqlDbType.VarChar, 50).Value = txtnombre.Text
cmd.Parameters.Add("@foto", SqlDbType.Image, foto.Length).Value = foto


cn.Open()
cmd.ExecuteNonQuery()
cn.Close()


Lleer fotos
Tu formulario tiene que estar de la siguiente manera:

-- Codigo del boton buscar(busca el codigo del textbox y despliega la imagen)
nota: no usen * en el select, es mas eficiente poner los campos.

Dim cn As New SqlClient.SqlConnection("user id=sa;" & _
"password=pass;initial catalog=northwind;data source=.\sqlexpress")
Dim cmd As New SqlClient.SqlCommand("", cn)
Dim dr As SqlClient.SqlDataReader
Dim sql As String
sql = "select nombre, foto from fotos where codigo=@codigo"
cmd.CommandText = sql
cmd.Parameters.Add("@codigo", SqlDbType.Int, 4).Value = txtcodigo.Text
cn.Open()
dr = cmd.ExecuteReader(CommandBehavior.SequentialAccess _
Or CommandBehavior.CloseConnection)
If dr.HasRows Then
While dr.Read()
'nombre de la foto
lblnombre.Text = Convert.ToString(dr!nombre)
'
If (dr.IsDBNull(1)) Then
MessageBox.Show("No hay imagen", "", _
MessageBoxButtons.OK, MessageBoxIcon.Stop)
Else
Dim bytes As SqlTypes.SqlBytes = dr.GetSqlBytes(1)
PictureBox1.Image = Image.FromStream(bytes.Stream)
'PictureBox1.Image=bytes.Write
End If
End While
Else
MessageBox.Show("Codigo no existe", "", _
MessageBoxButtons.OK, MessageBoxIcon.Stop)
End If
cn.Close()

Cambien la propiedad SizeMode a StretchImage para que la imagen se adapte al control.
Ver