lunes, 6 de diciembre de 2010

IIS 32 64 bits

1. Enable the 32-bit mode on x64 Windows server
cscript %SYSTEMDRIVE%\inetpub\adminscripts\adsutil.vbs SET W3SVC/AppPools/Enable32bitAppOnWin64 1
2. Install the version of ASP.NET 1.1 and the script maps at the IIS root and under
%SYSTEMROOT%\Microsoft.NET\Framework\v1.1.4322\aspnet_regiis.exe –i
3. Install the version of ASP.NET 2.0 (32-bit) and the script maps at the IIS root and under
%SYSTEMROOT%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe –i


http://www.codeproject.com/KB/aspnet/setup64bitserver.aspx

miércoles, 25 de agosto de 2010

JQuery - URL leer parametros

1ro definir la función:

$.urlParam = function (name) {

var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);

if (results != null)

return results[1] || 0;

else

return results;

//return results != null ? results[1] || 0 : results;

}

2do: utilizar la función

if ($.urlParam('pk') != null) {
alert(pk);
}

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/

miércoles, 30 de junio de 2010

SQL - Comparar Fechas sin Horas

Con esta instrucción CONVERT(date, FechaVisita,103) , saca solo la fecha sin la hora.
Ejm:

select
PK_Visita
,FechaVisita
, convert(date,GETDATE(),103)
from Visita
where CONVERT(date, FechaVisita,103) >= CONVERT(date,getdate(),103)

viernes, 18 de junio de 2010

js script desde server-code

Aqui les dejo dos maneras de invocar a codigo de cliente desde servidor, espero les sea de utilidad

Dim stScript As String = _
"" & vbCrLf & vbCrLf
Page.ClientScript.RegisterStartupScript(GetType(Page), "_RadMsgBox_radalert", stScript)


ScriptManager.RegisterClientScriptBlock(Me.Page, Me.Page.GetType(), Guid.NewGuid().ToString(), "returnToParent();", True)

martes, 15 de junio de 2010

SQL Insertar un Select en un Insert

INSERT INTO Tabla1 (Nombre,Nic,Servicios,Email,PaginaWeb,Telefono,Usuario,Contraseña,Direccion )

Select

Pr.Nombre,Pr.Nic,Pr.Servicios,Pr.Email,Pr.PaginaWeb,Pr.Telefono,Pr.Usuario,
Pr.Contraseña,Pr.Direccion
from Tabla2 as Pr

Evento Error de llamada Asincrona $.ajax

Podemos agregar un evento “error”, cuando suceda un error en la llamada asincrona.

Ejemplo para poner el evento “error”

$.ajax({
type: "post",
url: "http://myServer/cgi-bin/broker" ,
dataType: "text",
data: {
'_service' : 'myService',
'_program' : 'myProgram',
'start' : start,
'end' : end
},
beforeSend: function() {
$("#loading").removeClass("hide");
},
timeout: 5000,
error: function(request,error) {
$("#loading").addClass("hide");
if (error == "timeout") {
$("#error").append("The request timed out, please resubmit");
}
else {
$("#error").append("ERROR: " + error);
}
},
success: function(request) {
$("#loading").addClass("hide");
var t = eval( "(" + request + ")" ) ;
} // End success
}); // End ajax method



Y una lista de otros eventos que podemos utilizar en la llamada Asincrona

Referencia: http://docs.jquery.com/Ajax_Events

Events
This is the full list of Ajax events that are broadcast, and in the order in which they are broadcast. The indented events are broadcast for each and every Ajax request (unless a global option has been set). The ajaxStart and ajaxStop events are events that relate to all Ajax requests together.

ajaxStart (Global Event)
This event is broadcast if an Ajax request is started and no other Ajax requests are currently running.
beforeSend (Local Event)
This event, which is triggered before an Ajax request is started, allows you to modify the XMLHttpRequest object (setting additional headers, if need be.)
ajaxSend (Global Event)
This global event is also triggered before the request is run.
success (Local Event)
This event is only called if the request was successful (no errors from the server, no errors with the data).
ajaxSuccess (Global Event)
This event is also only called if the request was successful.
error (Local Event)
This event is only called if an error occurred with the request (you can never have both an error and a success callback with a request).
ajaxError (Global Event)
This global event behaves the same as the local error event.
complete (Local Event)
This event is called regardless of if the request was successful, or not. You will always receive a complete callback, even for synchronous requests.
ajaxComplete (Global Event)
This event behaves the same as the complete event and will be triggered every time an Ajax request finishes.
ajaxStop (Global Event)
This global event is triggered if there are no more Ajax requests being processed.

martes, 8 de junio de 2010

La tecla que se pulso en la pagina en JavaScript

$().ready(function() {
document.onkeypress = manejarTecla;
});

var Tecla_pulsada;
function manejarTecla(elEvento) {
var evento = elEvento || window.event;
Tecla_pulsada = evento.charCode || evento.keyCode;
var srcEl = evento.srcElement ? evento.srcElement : evento.target;
//si Tecla_pulsada == 13 -> Enter
}

sábado, 5 de junio de 2010

postear en twitter

Compartir en Twitter

Leer más: http://devblab.net/como-crear-un-boton-para-enviar-post-a-twitter-en-wordpress/#ixzz0pqeQebse
Under Creative Commons License: Attribution






miércoles, 2 de junio de 2010

shared facebook

señores les dejo una joyita, aunque es parece facil, pues a mi me costo encontrarla:

Es un ejemplo para que puedan postear información hacia el facebook:

function fbs_click()
{
u=location.href;
t=document.title;
window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
return false;
}

sábado, 29 de mayo de 2010

asp.net Autenticar por formulario

http://www.elguille.info/net/aspnet/tutorialLogin/tutorialLogin.htm

jueves, 27 de mayo de 2010

Leer XML con Jquery

Tenemos el siguiente XML:


<NewDataSet>
<Table1>
<idUsuario>123456</idUsuario>
<nombre>Angelica Maria</nombre>
<apellidoPaterno>Roca</apellidoPaterno>
<apellidoMaterno>Fong</apellidoMaterno>
</Table1>
<Table1>
<idUsuario>1738043</idUsuario>
<nombre>Angélica María</nombre>
<apellidoPaterno>Roca</apellidoPaterno>
<apellidoMaterno>Fong</apellidoMaterno>
</Table1>
<Table1>
<idUsuario>2984560</idUsuario>
<nombre>Jorge Rodolfo</nombre>
<apellidoPaterno>Roca</apellidoPaterno>
<apellidoMaterno>Mercado</apellidoMaterno>
</Table1>
<Table1>
<idUsuario>3394347</idUsuario>
<nombre>Paola Lenny</nombre>
<apellidoPaterno>Márquez</apellidoPaterno>
<apellidoMaterno>Pinto</apellidoMaterno>
</Table1>
<Table1>
<idUsuario>3830628</idUsuario>
<nombre>SHIRLEY DANNY</nombre>
<apellidoPaterno>TOTOLA</apellidoPaterno>
<apellidoMaterno>MORÓN</apellidoMaterno>
</Table1>
</NewDataSet>


Para leer un XML (aplicado al xml del ejemplo):
// tenemos que tener referenciados los archivos de Jquery "jquery.js"
// xml (variable de tipo XML)
// trabaja como un 'foreach' ...

$(xml).find('Table1').each(function(){
var atributo1 = $(this).attr('id'); //para leer los atributos del tag, si los tubiera
var idusuario = $(this).find('idUsuario').text();
var nombre = $(this).find('nombre').text();
var apMaterno = $(this).find('apellidoMaterno').text()
var apPaterno = $(this).find('apellidoPaterno').text()
});


A continuacion un ejemplo :
en un archivo Javascript, por ejemplo la siguiente funcion:

function TraerDatosUsuarios() {

// Estamos realizando una llamada ajax de JQuery
// url: la ruta del servidor, data: le mandamos los parametros necesarios
// success: la funcion que se va a ejecutar con los datos xml que retorne la llamada
// en la funcion se esta leyendo el xml "datos" con JQuery
$.ajax({
type: "POST",
datetype: "xml",
url: "../Utilidades/comunicador.ashx",
data: "consulta=obtenerpersonas",
success: function(datos) {
if ($(datos).find('NewDataSet').length > 0) {
var j = 0;
$(datos).find('Table1').each(function() {
var DatosUnicos = new Object();
DatosUnicos.legajo = $(this).find('idUsuario').text();
DatosUnicos.nombre = $(this).find('nombre').text() + ' ' + $(this).find('apellidoPaterno').text() + ' ' + $(this).find('apellidoMaterno').text();

});
}
}
});

}


-------------------------------------------------
Para preguntarse si un elemento es null:
if ($(this).find('FK_PadreValor').length == 0)

lunes, 24 de mayo de 2010

Documentar proyectos C# e integrarlo en la IDE de Visual Studio .NET

http://www.elguille.info/colabora/puntoNET/jtorres_HelpNDoc.htm

Message Box in ASP.NET 2.0

http://www.beansoftware.com/ASP.NET-Tutorials/Message-Box.aspx

viernes, 21 de mayo de 2010

SQL - Case

Select
PK_Persona,
Nombre
(CASE WHEN TipoRelacion = 1 THEN
'Empleado'
WHEN TipoRelacion = 0 THEN 'Contratista' END) as Tipo
From Persona

jueves, 20 de mayo de 2010

SQL - Cantidad de días en el mes de la fecha que especifiques

declare @fecha as datetime;
set @fecha = '01/02/2010';
--este servidor sql recibe las fechas en formato 'dia/mes/año'
--cambiar segun la configuracion del servidor sql


SET @fecha = CONVERT(VARCHAR(10), @fecha, 101)

SET @fecha = @fecha - DAY(@fecha) + 1

select DATEDIFF(DD, @fecha, DATEADD(MM, 1, @fecha))



Con esto ya podes saber la fecha fin de un mes especifico en SQL :)

martes, 11 de mayo de 2010

Adicionar Filas dinamicamente a una Tabla HTML (vamos a adicionar Texto)

Adicionar filas dinamicamente a una tabla HTML en JavaScript.
En este ejemplo vamos a adicionar texto

function addRowToTableDatos(pk, nombre, apellidos) {
var nombreTabla = 'tblPersona';
var tbl = document.getElementById(nombreTabla);
var lastRow = tbl.rows.length;
// if there's no header row in the table, then iteration = lastRow + 1
var iteration = lastRow;
var row = tbl.insertRow(lastRow);

//esta columna es no visible, por eso en su style.display ='none'
var cell0 = row.insertCell(0); //PK
cell0.style.display = 'none';
var textNode0 = document.createTextNode(pk);
cell0.appendChild(textNode0);

var cellNombre = row.insertCell(1);
var textNombre = document.createTextNode(nombre);
cellNombre .appendChild(textNombre );

var cellAp = row.insertCell(2);
var textAp = document.createTextNode(apellidos);
cellAp.appendChild(textAp);

}

viernes, 7 de mayo de 2010

ejecutar script js , usando updatepanel

Señores, como sabemos cuando utilizamos el ajax del framework de .net , en este caso scriptmanager y update panel, ningun javacript "$(document).ready(function(){...}", que se ejecuto la primera vez (en el cargado), se vuelve a ejecutar...

SOLUCION:

ScriptManager.RegisterClientScriptBlock(Me.Page, Me.Page.GetType(), Guid.NewGuid().ToString(), "toolMostrar();", True)



esto lo colocas en cualquier evento de un botno del servidor y listo , funciona 100% seguro!!
Pdta.- dedicado para la administradora de este blog que poco aporta..

miércoles, 5 de mayo de 2010

Ajustar el tamaño fisico de una imgen para que encaje e un DIV

Esta funcion me la acaban de pasar, (me parece que se puede optimizar) por ese motivo no la voy a explicar , pero garantizarles que si funciona, solo usenla ,no reinventen la rueda


Dim ImagePercentSize As Integer = 100



Protected Function GetThumbNailSizeImage(ByVal binaryData() As Byte) As Byte()
Dim ThumbNailBinaryData() As Byte = Nothing
Try
Dim TempMemStream As New System.IO.MemoryStream(binaryData)
Dim ImageObj As System.Drawing.Image
Dim ThumbSizeImageObj As System.Drawing.Image
ImageObj = System.Drawing.Image.FromStream(TempMemStream)
Dim temHeight As Integer
Dim temWidth As Integer
temHeight = ImageObj.Height
temWidth = ImageObj.Width
Dim TempFileStream As New System.IO.MemoryStream
'If Imagesize is less than 20*20 then return the original image
If (temWidth <= 460 And temHeight <= 211) Then
Dim ImageBinaryData() As Byte
ImageObj.Save(TempFileStream, System.Drawing.Imaging.ImageFormat.Jpeg)

ImageBinaryData = New Byte(CType(TempFileStream.Length, Integer)) {}
ImageBinaryData = TempFileStream.ToArray()
Return ImageBinaryData
End If
Dim ImagePercentSize As Double = Me.ImagePercentSize


Dim a, b As Double

If (460 > temWidth) And 211 > temHeight Then
a = 211 / temHeight
b = 460 / temWidth

If (a < b) Then
temHeight = CInt(temHeight * a)
temWidth = CInt(temWidth * a)
Else
temHeight = CInt(temHeight * b)
temWidth = CInt(temWidth * b)
End If

Else
a = 211 / temHeight
b = 460 / temWidth

If (a < b) Then
temHeight = CInt(temHeight * a)
temWidth = CInt(temWidth * a)
Else
temHeight = CInt(temHeight * b)
temWidth = CInt(temWidth * b)
End If

End If



'Create thumbnail size of the original Image ImageObj
If (Me.ImagePercentSize = 0.0) Then
ThumbSizeImageObj = ImageObj.GetThumbnailImage(temWidth, temHeight, Nothing, IntPtr.Zero)
Else
ThumbSizeImageObj = ImageObj.GetThumbnailImage(temWidth, temHeight, Nothing, IntPtr.Zero)
End If
ThumbSizeImageObj.Save(TempFileStream, System.Drawing.Imaging.ImageFormat.Jpeg)

ThumbNailBinaryData = New Byte(CType(TempFileStream.Length, Integer)) {}
ThumbNailBinaryData = TempFileStream.ToArray()
Catch ex As Exception

End Try
Return ThumbNailBinaryData
End Function


'----------- para llamar a la funcion
Dim binaryData() As Byte = f.Item(0) ' donde f.Item(0) es un conuto de Byte tra

Dim TempMemStream As New System.IO.MemoryStream(GetThumbNailSizeImage(binaryData))

'luego esta imagen redimencionada la puden guardar de la siguiente manera

Dim image_ As New Bitmap(TempMemStream)
Dim filepath As String = Server.MapPath("images/")
Dim dir As New DirectoryInfo(filepath)
Dim filecount As FileInfo() = dir.GetFiles()
Dim i As Integer = filecount.Length
Dim imagename As String = filepath + ((i + 1) & ".jpg")
image_.Save(imagename)

Nota.- cuando agregen la imagen al componente html , no usen las propiedades width ni heigth

miércoles, 28 de abril de 2010

Propuesta de manejo de errores

para procedimientos creados por el programador:

Try
//codigo
Catch ex As Exception
Throw New Exception(DateTime.Now.ToString() & " Error ObtenerAppConfig : " & ex.Message)
End Try

Importante crear un nueva Excepcion , para poder personalizarla, de esa manera podemos agregar algun comentario al error, que nos ayude a ubicarlo.

//--------------------------------------------------

Para funciones que se disparan con un manejador (Handles).


Try
//codigo
Catch ex As Exception

MessageBox.Show(DateTime.Now.ToString() & " Error btn_guardar_Click : " & ex.Message)
Me.EscribirLog(DateTime.Now.ToString() & " Error btn_guardar_Click : " & ex.Message, EventLogEntryType.Error)

End Try

Solo de muestra un mensaje y un valor agregado registrarlo en el visor de sucesos de windows

Nota.- La funcion EscribirLog la describire en una Entrada posterior

lunes, 19 de abril de 2010

funcion trim en JavaScript

Funcion que permite elminar espacios en blanco de una cadena
al principio y al final.

En JavaScript no existe una funcion trim.
Con esta funcion podemos simular un trim en js:

function trim (myString)
{
return myString.replace(/^\s+/g,'').replace(/\s+$/g,'')
}

jueves, 15 de abril de 2010

Exportar datos de un excel a una tabla SQL

Selecciono la Base de datos/Task/Import data/

Choose a Data Source
'Data source' : Microsoft Excel (Busco y selecciono esta opción)
'Excel file path': (seleccionamos la ruta del archivo excel)
'First row has column names' (check, el cual indica que las primeras filas del excel seran los nombres de la nueva tabla)
Siguiente/

Choose a Destination
Server name: (seleccionamos nombre del servidor)
Authentication (seleccionamos la autentificacion)
Database: (verificamos que este seleccionada la Base de datos correcta)
Siguiente/

Specify Table Copy or Query
Copy data from one or more tables or views (lo seleccionamos)

Select Source Tables and Views
(Seleccionamos la(s) hoja(s) del excel con los datos)
En la columna 'Destination' seleccionamos la tabla destino o el nombre de la nueva tabla
Le damos en 'Preview' para ver como quedaria la tabla destino 'Destination'
Siguiente/

Save and Run Package
Run immediately(seleccionamos)
/Finalizar

The execution was successful


Una vez creada la tabla.. ya podemos manipularla con consultas o procedimientos almacenados
para pasar los datos como querramos a la tabla que necesitemos.

viernes, 9 de abril de 2010

Leer un XML en javascript

Supongamos un XML, con esta estructura:

<NewDataSet>
<Table1>
<nombre>Soy el nombre 1</nombre>
.
.
<campoN>campo N , del nombre 1</campoN>
</Table1>
<Table1>
<nombre>Soy el nombre 2</nombre>
.
.
<campoN>campo N , del nombre 2</campoN>
</Table1>
</NewDataSet>


Para leerlo, llamando con el nombre de su Etiqueta:

datos.childNodes[0].childNodes[0].selectNodes("nombre")[0].text
//esto me retorna “Soy el nombre 1”

datos.childNodes[0].childNodes[1].selectNodes("nombre")[0].text
//esto me retorna “Soy el nombre 2”

martes, 6 de abril de 2010

sharepoint video enlace

Aqui os dejo un enlace para un video de sharepoint:
http://www.microsoft.com/spain/technet/spotlight
, en la pagina podeis encontrar webcast y tutoriales de productos microsoft muy buenos

miércoles, 24 de marzo de 2010

JQuery Solar System


JQuery solar system
un ejemplo de animación muy bueno usando JQuery.. :)



http://www.willjessup.com/sandbox/jquery/solar_system/rotator.html

martes, 16 de marzo de 2010

Mostrar un Mensaje de javascript desde el servidor "code behind" en C#

private void MostrarMensajito(string mensaje)
{
try
{
string jscript = string.Empty;

jscript = "<script language=\"javascript\">function Mensaje(){alert" +
"(\" " + mensaje + " \")} Mensaje();</script>";

ClientScript.RegisterStartupScript(this.GetType(), "sJscript", jscript);
}
catch (Exception err)
{
llamarFormularioError(_Pagina, "MostrarMensajito", err.Message);
}


}

viernes, 26 de febrero de 2010

link convertir codigo Net visual -> c#

http://www.elguille.info/NET/WebServices/vb2csWeb.aspx

http://www.elguille.info/NET/WebServices/deCSaVB_web.aspx

http://www.elguille.info/NET/WebServices/deVBaCS_web.aspx

jueves, 18 de febrero de 2010

Convertir pdf a word en linea

Encontré una página que me resulto muy util para convertir en linea un archivo pdf a word.
Intente convertir el archivo pdf con otros programitas que descargue pero me retornaban un word mal, con caracteres extraños.

Con esta página se puede transformarlo sin problema:


http://www.freepdftoword.org/es/online.htm?step=1

miércoles, 10 de febrero de 2010

Crear un usuario para una Base de datos

use Master

exec sp_addlogin 'usuarioBDPrueba', '123'

GO

Use BDPrueba

exec sp_grantdbaccess 'usuarioBDPrueba'
GO

exec sp_addrolemember 'db_owner','usuarioBDPrueba'
GO


El script 1ro sobre master se crea el usuario "usuarioBDPrueba" y le da un password "123".
2do sobre la base de datos "BDPrueba" , se esta autorizando al usuario "usuarioBDPrueba" para que pueda acceder a la base de datos con "sp_grantdbaccess" y hacemos que el usuario tome el rol de dueño de la Base de datos con "db_owner".

jueves, 28 de enero de 2010

Buscar y reemplazar saltos de linea en excel (ALT + ENTER)

Buscando encontré en la web esta forma para reemplazar los saltos de línea en excel y me fué muy util:

Para reemplazar SALTOS DE LINEA (ALT+ENTER) dentro de cada celda de Excel 2007 haz lo siguiente:


1. Selecciona la celdas que contienen satos de línea
2. Abre la ventana de Buscar y Reemplazar
3. En la casilla "Buscar" manten presionada la tecla ALT mientras pulsas en el teclado numérico 0010
4. Notaras que el cursor de texto que parpadea como una línea se transforma en un punto que parpadea.
5. En la casilla "Reemplazar por" escribe un texto por lo que quieras reemplazar.
6. Click en "Reemplazar Todo"


Si tienes problemas intenta usar el otro alt, yo usé el alt izquierdo.

miércoles, 27 de enero de 2010

Cursores en SQL

DECLARE
@pk_tarea AS VARCHAR;
DECLARE
@descripcion as Varchar;

-- declaro el cursor.
DECLARE CURSOR_TAREA CURSOR FOR
-- mi consulta
select pk_Tarea
, convert(varchar,tarea) as tarea
from tarea

-- abro el cursor ojo... a lo ultimo debe cerrarse.
OPEN CURSOR_TAREA
-- saco el primer registro.
FETCH NEXT from CURSOR_TAREA
-- y las meto en mis variables.. cuidando el orden.
INTO @pk_tarea , @descripcion;

WHILE
@@FETCH_STATUS = 0
BEGIN
PRINT 'PKTAREA : ' + @pk_tarea
PRINT 'DESCRIPCION : ' + @descripcion

-- aqi avanzo al proximo registro
FETCH NEXT from CURSOR_TAREA
-- y le pongo los nuevos valores a mis variables..
INTO @pk_tarea , @descripcion;

END
;

CLOSE CURSOR_TAREA;
DEALLOCATE CURSOR_TAREA;
-- y por ultimo estas dos lineas para cerrar el cursos... ojo...sino despues salen errores.. porq el cursor se quedo abierto...

Diseño de formularios

Si estan el etapa de diseño de prototipos , pues una herramienta buena para usa es balsamiq mockups, pueden realizar una presentacion buena a sus usuarios de como van a verse sus formularios.

modificar un valor de una llave del config .NET

con esta función puedes modificar un valor del config en .NET

Public Sub ModificarAppConfig(ByVal Key As String, ByVal ValueNew As String)
Dim config As Configuration
config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None)
config.AppSettings.Settings(Key).Value = ValueNew
config.Save(ConfigurationSaveMode.Modified)
ConfigurationManager.RefreshSection("appSettings")
End Sub

es importante realizar el Refresh, ya que si no lo haces no veras los cambios que realizas

Imprimir el contenido de un Div con Javascript

<DIV ID="seleccion">Este texto es el que se va a imprmir </DIV>

colocamos un enlace que llame a la función de imprimir

<a href="javascript:imprSelec('seleccion')" >Imprime la ficha</a>

Y en JavaScript:

<script language="Javascript">
function imprSelec(nombre)
{
var ficha = document.getElementById(nombre);
var ventimp = window.open(' ', 'popimpr');
ventimp.document.write( ficha.innerHTML );
ventimp.document.close();
ventimp.print( );
ventimp.close();
}
</script>

ConfigurationSettings es obsoleto

System.Configuration.ConfigurationSettings.AppSettings

esta manera de acceder a las variables del config es obsoleta, la manera ideal de acceder es:

System.Configuration.ConfigurationManager.AppSettings

si por alguna razon , no te reconoce ConfigurationManager debes agregar la referencia "System.Configuration".

Formato universal de fechas para SQL SERVER

Siempre que manejes fechas en sql server debes utilizar el formato yyyyMMdd HH:mm:ss, ya que si manejas otro puede ser que tu version varia de español a ingles.

aqui les dejo un ejemplo para visual basic.net

Private Const FormatoUniversal As String = "yyyyMMdd HH:mm:ss" 'FORMATO DE FECHA UNIVERSAL
Public Shared Function SQL_ObtenerFecha(ByVal __fecha As Date) As String
Return Format(__fecha, FormatoUniversal)
End Function

quitar horas de una fecha en SQL

Cast(Floor(Cast(fecha_hora as Float))as DateTime)

esta instruccion te permite resetear a 00:00:00 la parte de las horas de un DateTime de SQL, espero que les sea de utilidad, a mi me funcionó perfectamente.

Funcion Split en SQL

En SQL, no existe una función 'Split' como tal, por lo que investigando encontré una que simula hacer un 'Split'.
La idea de hacer un Split es dividir una cadena, la cual deberia ser dividida por un caracter en comun.
Este ejemplo @String recibe la cadena y @Delimiter es la cadena de caracteres utilizados para identificar los límites de las subcadenas.

DECLARE @NextString NVARCHAR(40)
DECLARE @Pos INT
DECLARE @NextPos INT
DECLARE @String NVARCHAR(40)
DECLARE @Delimiter NVARCHAR(40)

SET @String ='SQL,TUTORIALS'
SET @Delimiter = ','
SET @String = @String + @Delimiter
SET @Pos = charindex(@Delimiter,@String)

WHILE (@pos <> 0)
BEGIN
SET @NextString = substring(@String,1,@Pos - 1)
SELECT @NextString -- muestra los resultados
SET @String = substring(@String,@pos+1,len(@String))
SET @pos = charindex(@Delimiter,@String)
END