miércoles, 14 de julio de 2010

Llamada Asyncrona JQuery - Ejemplo

1) En tu pagina haces referencia a los scripts de JQuery: jquery-1.4.2.min.js y jquery.js

http://jquery.com/

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
2) en Javascript tu llamada asincrona:

function CargarDatosComboTipoTiempo() {

$.ajax({
type: "POST",
datetype: "xml", // tipo de dato que va a retornar
beforeSend: function(objeto) { // se ejecuta antes llamada asincrona
MostrarDivEspere();
},
url: "../Utilidades/Comunicador.ashx", //dirección del servidor
error: function(request, error) { //error en la llamada asincrona
if (error == "timeout") {
alert("The request timed out, please resubmit");
}
else {
alert("ERROR: " + error);
}
},
data: "consulta=devolvervalores&tipo=0", //parametros
success: function(datos) { //aqi en la var 'datos' retorna un xml
if ($(datos).find('error').length == 0) {
var combo = $("#cmbTipoTiempo")[0];
var cantidadElementos = $(datos).find('Table1').length;
if ($(datos).find('NewDataSet').length > 0 && (cantidadElementos > 0)) {
combo.length = cantidadElementos;
var j = 0;
$(datos).find('Table1').each(function() {
combo.options[j].text = $(this).find('Nombre').text();
combo.options[j].value = $(this).find('PK_Valor').text();
j++;
});
}
}
else {
alert("Error en la Lista 'Tipo de Tiempo'");
}
},
complete: function(objeto, exito) {
//alert("Me acabo de completar")
if (exito != "success") {
alert("Error en 'Búsqueda de Personas por CI'");
}
OcultarDivEspere();
}
});
}
--------------------------------------------------------------------------------------------------------------------------------------------
3) Ejemplo de la estructura xml que me retorna a mi llamada asincrona:
cuando le doy al dataset.GetXml(); me retorna como tag principal <NewDataSet> y cada fila del resultado dentro del tag <Table1>.
Los tags q estan dentro de <Table1> , son las columnas de la consulta que ejecutaste a la Base de Datos. ejem: <PK_Valor>, <Nombre>, <Tipo>
como ya se que mi xml tiene esta estructura asi leo con JQuery cuando me retorna el resultado la llamada asyncrona

<NewDataSet>
<Table1>
<PK_Valor>1</PK_Valor>
<Nombre>Minutos</Nombre>
<Tipo>0</Tipo>
</Table1>
<Table1>
<PK_Valor>2</PK_Valor>
<Nombre>Horas</Nombre>
<Tipo>0</Tipo>
</Table1>
<Table1>
<PK_Valor>3</PK_Valor>
<Nombre>Dias</Nombre>
<Tipo>0</Tipo>
</Table1>
</NewDataSet>
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
4 ) Otro ejemplo de una llamada asyncrona

function BuscarVisitasProgramadasRecepcion(nroPagina) {
var pkVisita = $("#hdd_Identificador")[0].value;
if (pkVisita == '') {
pkVisita = '0';
}
var ci = $("#hdd_CI")[0].value;
var nombres = $("#hdd_Nombres")[0].value;
var apellidos = $("#hdd_Ap")[0].value;
var empresa = $("#hdd_Empresa")[0].value;
var fecha = $("#hdd_Fecha")[0].value;
var hora = $("#hdd_Hora")[0].value;

$.ajax({
type: "POST",
datetype: "xml",
url: "../Utilidades/comunicador.ashx",
data: "consulta=buscarvisitasprogramadasrecepcion&nropagina=" + nroPagina + '&cantfilas=' + CantRegistros
+ '&ci=' + ci + '&nombre=' + nombres + '&apellidos=' + apellidos + '&empresa=' + empresa + '&fecha=' + fecha
+ '&hora=' + hora + '&pkvisita=' + pkVisita,
beforeSend: function(objeto) {
MostrarDivEspere();
},
error: function(request, error) {
if (error == "timeout") {
alert("The request timed out, please resubmit");
}
else {
alert("ERROR: " + error);
}
},
complete: function(objeto, exito) {
if (exito != "success") {
alert("Error en 'Búsqueda de Visitas Programadas'");
}
OcultarDivEspere();
},

success: function(datos) {
if ($(datos).find('error').length == 0) {
if ($(datos).find('NewDataSet').length > 0 && ($(datos).find('Table1').length > 0)) {

$(datos).find('Table1').each(function() { el tag <Table1> son filas con resultado de la consulta
var pkVisita = $(this).find('PK_Visita').text();
var pkPersona = $(this).find('PK_PersonaVisita').text();
var ciPersona = $(this).find('CI').text();
var nombrePersona = $(this).find('Nombres').text();
var ApellidoPersona = $(this).find('Apellidos').text();
var empresaPersona = $(this).find('Empresa').text();
var fechaVisita = $(this).find('FechaVisita').text();
var horaVisita = $(this).find('HoraVisita').text();
var fkAnfitrion = $(this).find('FK_Anfitrion').text();
var usuario = $(this).find('Usuario').text();
var tiempo = $(this).find('Tiempo').text();
var tiempoTotal = $(this).find('TiempoTotal').text();
var tipoTiempo = $(this).find('TipoTiempo').text();
var tipoVisita = $(this).find('TipoVisita').text();
var observacion = $(this).find('Observacion').text();

cantTotal = $(this).find('CantTotal').text();
addRowToTableVisitasRecepcion(pkVisita, pkPersona, ciPersona, nombrePersona, ApellidoPersona, empresaPersona
, fechaVisita, horaVisita, fkAnfitrion, usuario, tiempo, tiempoTotal, tipoTiempo, tipoVisita, observacion);

});
}
else {
alert('no hay registros');
}
}
else {
OcultarDivEspere();
alert("Error en 'Búsqueda de Visitas Programadas'");
}
}
});
}

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
5 ) Estructura del xml de esta llamada asincrona:

<NewDataSet>
<Table1>
<CantTotal>2</CantTotal>
<PK_Visita>27</PK_Visita>
<PK_PersonaVisita>54</PK_PersonaVisita>
<CI>123471</CI>
<Nombres>JUAN ANGEL</Nombres>
<Apellidos>BASARRATE BARRENECHEA</Apellidos>
<Empresa>DHOBAL AUDITORES</Empresa>
<FechaVisita>14/07/2010</FechaVisita>
<HoraVisita>15:30:00</HoraVisita>
<FK_Anfitrion>97112131</FK_Anfitrion>
<Usuario>MIRIAM CECILIA LIMPIAS ORTIZ</Usuario>
<Tiempo>2</Tiempo>
<TiempoTotal>Dias</TiempoTotal>
<TipoTiempo>3</TipoTiempo>
<TipoVisita>4</TipoVisita>
<Observacion>lalsfjalsdfaj</Observacion>
</Table1>
<Table1>
<CantTotal>2</CantTotal>
<PK_Visita>26</PK_Visita>
<PK_PersonaVisita>52</PK_PersonaVisita>
<CI>123456</CI>
<Nombres>JUAN</Nombres>
<Apellidos>PEREZ PEREZ</Apellidos>
<Empresa>NINGUNA</Empresa>
<FechaVisita>14/07/2010</FechaVisita>
<HoraVisita>10:30:00</HoraVisita>
<FK_Anfitrion>97112131</FK_Anfitrion>
<Usuario>MIRIAM CECILIA LIMPIAS ORTIZ</Usuario>
<Tiempo>10</Tiempo>
<TiempoTotal>Dias</TiempoTotal>
<TipoTiempo>3</TipoTiempo>
<TipoVisita>6</TipoVisita>
<Observacion>del gobierno..entonces es obligatorio</Observacion>
</Table1>
</NewDataSet>

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
6) create un archivo .ashx, donde van a estar tus metodos que que vamos a llamar.
El archivo .ashx es mejor crearlo en la aplicacion. no copiar el archivo.

- add/New Item/Generic Handler
(es un archivo con extencion .ashx)

*********************************************
- SI en este archivo queres usar variables de Session aumenta (lo que esta con negrita):
using System.IO;
public class Comunicador : IHttpHandler, IRequiresSessionState

**********************************************

- Ejemplo de mi archivo Comunicador.ashx
por ejem vamonos al metodo devolvervalores


using System;
using System.Collections;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Web.SessionState;
using System.IO;

namespace ControlVisita.Utilidades
{
/// <summary>
/// Summary description for $codebehindclassname$
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Comunicador : IHttpHandler, IRequiresSessionState
{
HttpContext _ContextServer;

public void ProcessRequest(HttpContext context)
{

try
{
_ContextServer = context;
string resultado = string.Empty;
string valorConsulta = context.Request.Form["Consulta"].ToLower(); // aqui obtengo el valor de 'consulta'
switch (valorConsulta)
{
case "devolvervalores":
resultado = DevolverValoresPorTipo(context.Request.Form["tipo"]);
context.Response.ContentType = "text/xml";
break;
case "buscarvisitasprogramadas":
resultado = BuscarVisitasProgramadas(context.Request.Form["nropagina"], context.Request.Form["cantfilas"]
, context.Request.Form["fkanfitrion"], context.Request.Form["ci"], context.Request.Form["nombre"]
, context.Request.Form["apellidos"], context.Request.Form["empresa"], context.Request.Form["fecha"]
, context.Request.Form["hora"]);
context.Response.ContentType = "text/xml";
break;
default:
resultado = "No se Encontro el Metodo.";
break;
}
context.Response.Write(resultado);
}
catch (Exception err)
{
context.Response.Write("<error>error</error>");
context.Response.ContentType = "text/xml";
}

}

public bool IsReusable
{ // esta función viene por defecto con el .ashx . dejarla ahi
get
{
return false;
}
}

#region "Metodos Valores"
private string DevolverValoresPorTipo(string tipo)
{
ControlVisitaLib.Facade facade = (ControlVisitaLib.Facade)_ContextServer.Session["Facade"];
DataTable dtValores = facade.AdmValor.DevolverValoresPorTipo(Convert.ToInt16(tipo));
DataSet dsValores = new DataSet();
dsValores.Tables.Add(dtValores);
return dsValores.GetXml(); // el Dataset.GetXml ya me retorna un xml. abajo esta un ejm del xml q me retorna.
}
#endregion


#region "Visitas"


private string BuscarVisitasProgramadas(string nroPagina, string cantFilas, string fkAnfitrion, string ci, string nombre, string apellidos
, string empresa, string fecha,string hora)
{
ControlVisitaLib.Facade facade = (ControlVisitaLib.Facade)_ContextServer.Session["Facade"];
DataTable dtVisita = facade.AdmVisita.BuscarVisitasProgramadas(Convert.ToInt16(cantFilas), Convert.ToInt16(nroPagina), Convert.ToInt32(fkAnfitrion),ci
,nombre , apellidos,empresa , fecha, hora );
DataSet dsVisita = new DataSet();
dsVisita.Tables.Add(dtVisita );
return dsVisita.GetXml();
}
#endregion

}
}

martes, 13 de julio de 2010

videos puro client side Telerik (como le gusta a marce)

buenos videos de telerik para acceder a los datos por medio de metodos web y javascript

http://blogs.telerik.com/kevinbabcock/posts/08-08-26/client-side_data_binding_in_the_radgrid.aspx

viernes, 9 de julio de 2010

SQL - Case en el Where

WHERE OrderNumber LIKE
CASE WHEN IsNumeric(@OrderNumber) = 1 THEN
@OrderNumber
ELSE
'%' + @OrderNumber
END

------------------------------------------------------------------------------

WHERE
OrderNumber = CASE
WHEN (IsNumeric(@OrderNumber) = 1)
THEN CONVERT(INT, @OrderNumber)
ELSE -9999 -- Some numeric value that just cannot exist in the column
END
OR
FirstName LIKE CASE
WHEN (IsNumeric(@OrderNumber) = 0)
THEN '%' + @OrderNumber
ELSE ''
END

------------------------------------------------------------------------------

WHERE
IF IsNumeric(@OrderNumber) = 1
OrderNumber = @OrderNumber
ELSE
OrderNumber LIKE '%' + @OrderNumber + '%'

viernes, 2 de julio de 2010

Parametros de Ajax de JQuery

Parametros de Ajax de Jquery:


$.ajax({
url: "introduccion-a-jquery.htm",
async:true,
beforeSend: function(objeto){
alert("Adiós, me voy a ejecutar");
},
complete: function(objeto, exito){
alert("Me acabo de completar")
if(exito=="success"){
alert("Y con éxito");
}
},
contentType: "application/x-www-form-urlencoded",
dataType: "html",
error: function(objeto, quepaso, otroobj){
alert("Estas viendo esto por que fallé");
alert("Pasó lo siguiente: "+quepaso);
},
global: true,
ifModified: false,
processData:true,
success: function(datos){
alert(datos);
},
timeout: 3000,
type: "GET"
});

Referencias:
http://api.jquery.com/jQuery.ajax/
http://www.cristalab.com/tutoriales/ajax-en-jquery-c226l/