Windows Presentation Foundation



Subiendo imágenes en ASP.NET

Aquí les paso el código de una clase que hice para subir imagenes a un servidor en formato jpg,jpeg y gif:


Imports Microsoft.VisualBasic
Public Class Upload
#Region "Variables de Clase"
Dim extensiones() As String = {"jpg", "jpeg", "gif"}
Dim tamaño As Double
Const size As Integer = 50
Public control As System.Web.UI.WebControls.FileUpload
Public user As String
Public ubicacion As String = "UplImages\"
Public extension As String
Public cuenta As String
#End Region
#Region "Metodos de Clase"
Function upload(ByVal server) As Boolean
Dim vlext As String = MyClass.obtenerExtension(control.PostedFile.FileName)
tamaño = control.PostedFile.InputStream.Length / 1000
Dim GuardarImagenEn As String
GuardarImagenEn = ubicacion & user & "." & vlext
If verificarExtension(vlext) = True And tamaño <= size Then
Try
Dim subirImagen As System.Drawing.Image
subirImagen = System.Drawing.Image.FromStream(control.PostedFile.InputStream)
subirImagen.Save(server.MapPath(GuardarImagenEn))
Catch ex As Exception
MsgBox("Error: " & ex.Message)
End Try
End If
End Function
Function verificarExtension(ByVal ext As String) As Boolean
Try
Dim n As Integer = MyClass.extensiones.Length - 1
Dim i As Integer
For i = 0 To n - 1
If MyClass.extensiones(i) = ext Then
Return True
End If
Next
Return False
Catch ex As Exception
End Try
End Function
Function obtenerExtension(ByVal controlText As String)
Dim ext As String
Dim parts() As String
parts = controlText.Split(".")
ext = parts(parts.Length - 1)
MyClass.extension = ext
Return ext
End Function
#End Region
End Class

Los procedimientos almacenados son equivalentes a funciones que se guardan en la base de datos.Por ejemplo:
Creamos un procedimiento almacenado en el SQL Server:

create procedure nuevo_cliente
@id_cliente char(10),
@nombres char(50),
@apellidos char(50),
@direccion char(50),
@telefono char(10),
@ruc char(10),
@dni char(10)
as
insert into cliente values(@id_cliente,@nombres,@apellidos,@direccion,@telefono,@ruc,@dni)

Declaramos en la cabecera los Imports necesarios
Imports System.Data
Imports System.Data.SqlClient


en el evento Load del formulario en VB,por ejemplo , escribimos:

Try
xcon.Open()
Dim com As New SqlCommand("nuevo_cliente")
com.Connection = xcon
com.CommandType = CommandType.StoredProcedure 'Indicamos el tipo de comando
Dim id As Stringid = txtRUC.Text.Substring(0, 4) & txtNombre.Text.Substring(0, 3) & txtApellido.Text.Substring(0, 3)
com.Parameters.Add("@id_cliente", SqlDbType.Char, 10).Value = id
com.Parameters.Add("@nombres", SqlDbType.Char, 50).Value = txtNombre.Text
com.Parameters.Add("@apellidos", SqlDbType.Char, 50).Value = txtApellido.Text
com.Parameters.Add("@direccion", SqlDbType.Char, 50).Value = txtDireccion.Text
com.Parameters.Add("@telefono", SqlDbType.Char, 10).Value = txtTelefono.Text
com.Parameters.Add("@ruc", SqlDbType.Char, 10).Value = txtRUC.Text
com.Parameters.Add("@dni", SqlDbType.Char, 10).Value = txtDNI.Textcom.ExecuteNonQuery()
If xcon.State = ConnectionState.Open Then
xcon.Close()
End If
MsgBox("Cliente agregado con exito", MsgBoxStyle.Information, "Error")
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Error")
xcon.Close()
End Try

GRIDVIEW EN ASP.NET

Algo que desde hace tiempo estaba leyendo y nadie daba solucion clara, al menos en VB. NET.

Obtener valores de las columnas de una fila seleccionada de un Control GridView de ASP.NET.
Primero agregamos la propiedad Seleccionar fila del GridView:


Luego damos doble click en el gridview y escribimos el sgte codigo en el evento SelectedIndexChanged:

Protected Sub dgCliente_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles dgCliente.SelectedIndexChanged
lblMensaje.Text = dgCliente.SelectedRow.Cells(2).Text
End Sub

Explicando:

dgcliente : es el nombre del gridview

dgCliente.SelectedRow : obtiene la fila seleccionada

dgCliente.SelectedRow.Cells(2) : obtiene la columna 2 (en mi caso) de la fila seleccionada

dgCliente.SelectedRow.Cells(2).Text : simplemente lo convierte a una cadena de texto

Un servicio es una aplicacion distribuida que te permite obtener datos y acceder a funciones cifradas en xml:
Agregamos un nuevo servicio.asmx a nuestro sitio web:
<%@ WebService Language="VB" Class="WebService" %>
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
_
_

Public Class WebService
Inherits System.Web.Services.WebService

_
Public Function HelloWorld() As String
Return "Hello World"
End Function
End Class


Este servicio web devuelve este archivo en XML:
<?xml version="1.0" encoding="utf-8" ?>
<string xmlns="http://tempuri.org/">Hello World</string>

Un simple lector de archivos XML

Creamos un formulario similar al siguiente:
...Además agregamos un OpenFile Dialog

Public Class Form1

Dim ds As New DataSet 'Declaramos un dataset
Dim archivo As String

Sub abrir()
'Creamos una subrutina para mostrar el dialogo "Abrir Archivo "
OpenFile.ShowDialog() archivo = OpenFile.FileName
'La funcion ReadXml carga el archivo XML en el dataset

ds.ReadXml(archivo)

MsgBox("Carga del archivo correcta.", MsgBoxStyle.Information)
'Llenamos el datagrid

dgdatos.DataSource = ds.Tables(0).DefaultView

End Sub

Private Sub btnCargar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCargar.Click
'En el evento click del boton Cargar escribimos este codigo:
abrir() btnCargar.Enabled = False btnGrabar.Enabled = True
End Sub

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
btnCargar.Enabled = True btnGrabar.Enabled = False
End Sub

Private Sub btnGrabar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGrabar.Click
'En el evento click del boton Grabar usamos la funcion WriteXml para guardar los cambios
ds.WriteXml(archivo)
MsgBox("Guardaste el archivo correctamente", MsgBoxStyle.Information)
End Sub
End Class

Algunos detalles que debemos considerar al momento de Publicar nuestra aplicacion:

  1. Clickeando en Proyecto /Propiedades de (nombre de la aplicacion) .En la opcion Pantalla de Bienvenida seleccionamos nuestro SplashScreen (creado agregando un nuevo elemento de Pantalla de Bienvenida a nuestro Proyecto)
  2. En el boton Información del ensamblado nos saldrá una ventana con información referida al software que hemos creado.
  3. Pueden cambiar el tradicional icono de la ventana en blanco por uno personalizado .Aquí un link para convertir una imagen en icono(*.ico) : http://www.chami.com/html-kit/services/favicon/


MEtodos POST y GET equivalentes entre PHP y ASP.NET

PHP

ASP

Metodo POST$_POST["variable"]Request.Form("variable")
Metodo GET$_GET["variable"]Request.QueryString("variable")