martes, 8 de diciembre de 2009

Ocultar partes de un documento al imprimir

Algunas veces queremos programar un javascript que imprima nuestra página actual, pero a veces hay encabezados con imagenes que podrían gastar mucha tinta.

Una solución para esto es utilizar un estilo que oculte esos objetos cuando se mande a imprimir, eso se haría de la siguiente forma


<
style media="print" type="text/css">

.ocultarEnImpresion

{

DISPLAY: none;

}

</style>

jueves, 26 de noviembre de 2009

Registrar un dll en windows

Para registra un dll en Windows se debe ingresar el siguiente comando (cmd)

regsvr32 dllaregistrar.dll

viernes, 13 de noviembre de 2009

Exportar DataSet a Excel

public void exportToExcel(DataSet source, string pArchivo)
    {
        System.IO.MemoryStream o = new System.IO.MemoryStream();
        System.IO.StreamWriter excelDoc;

        excelDoc = new System.IO.StreamWriter(o);//fileName);
        const string startExcelXML = "<xml version>\r\n<Workbook " +
              "xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"\r\n" +
              " xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\n " +
              "xmlns:x=\"urn:schemas-    microsoft-com:office:" +
              "excel\"\r\n xmlns:ss=\"urn:schemas-microsoft-com:" +
              "office:spreadsheet\">\r\n <Styles>\r\n " +
              "<Style ss:ID=\"Default\" ss:Name=\"Normal\">\r\n " +
              "<Alignment ss:Vertical=\"Bottom\"/>\r\n <Borders/>" +
              "\r\n <Font/>\r\n <Interior/>\r\n <NumberFormat/>" +
              "\r\n <Protection/>\r\n </Style>\r\n " +
              "<Style ss:ID=\"BoldColumn\">\r\n <Font " +
              "x:Family=\"Swiss\" ss:Bold=\"1\"/>\r\n </Style>\r\n " +
              "<Style     ss:ID=\"StringLiteral\">\r\n <NumberFormat" +
              " ss:Format=\"@\"/>\r\n </Style>\r\n <Style " +
              "ss:ID=\"Decimal\">\r\n <NumberFormat " +
              "ss:Format=\"0.0000\"/>\r\n </Style>\r\n " +
              "<Style ss:ID=\"Integer\">\r\n <NumberFormat " +
              "ss:Format=\"0\"/>\r\n </Style>\r\n <Style " +
              "ss:ID=\"DateLiteral\">\r\n <NumberFormat " +
              "ss:Format=\"mm/dd/yyyy;@\"/>\r\n </Style>\r\n " +
              "</Styles>\r\n ";
        const string endExcelXML = "</Workbook>";

        int rowCount = 0;
        int sheetCount = 1;
        /*
       <xml version>
       <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
       xmlns:o="urn:schemas-microsoft-com:office:office"
       xmlns:x="urn:schemas-microsoft-com:office:excel"
       xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">
       <Styles>
       <Style ss:ID="Default" ss:Name="Normal">
         <Alignment ss:Vertical="Bottom"/>
         <Borders/>
         <Font/>
         <Interior/>
         <NumberFormat/>
         <Protection/>
       </Style>
       <Style ss:ID="BoldColumn">
         <Font x:Family="Swiss" ss:Bold="1"/>
       </Style>
       <Style ss:ID="StringLiteral">
         <NumberFormat ss:Format="@"/>
       </Style>
       <Style ss:ID="Decimal">
         <NumberFormat ss:Format="0.0000"/>
       </Style>
       <Style ss:ID="Integer">
         <NumberFormat ss:Format="0"/>
       </Style>
       <Style ss:ID="DateLiteral">
         <NumberFormat ss:Format="mm/dd/yyyy;@"/>
       </Style>
       </Styles>
       <Worksheet ss:Name="Sheet1">
       </Worksheet>
       </Workbook>
       */
        excelDoc.Write(startExcelXML);
        excelDoc.Write("<Worksheet ss:Name=\"Sheet" + sheetCount + "\">");
        excelDoc.Write("<Table>");
        excelDoc.Write("<Row>");
        for (int x = 0; x < source.Tables[0].Columns.Count; x++)
        {
            excelDoc.Write("<Cell ss:StyleID=\"BoldColumn\"><Data ss:Type=\"String\">");
            excelDoc.Write(source.Tables[0].Columns[x].ColumnName);
            excelDoc.Write("</Data></Cell>");
        }
        excelDoc.Write("</Row>");
        foreach (DataRow x in source.Tables[0].Rows)
        {
            rowCount++;
            //if the number of rows is > 64000 create a new page to continue output

            if (rowCount == 64000)
            {
                rowCount = 0;
                sheetCount++;
                excelDoc.Write("</Table>");
                excelDoc.Write(" </Worksheet>");
                excelDoc.Write("<Worksheet ss:Name=\"Sheet" + sheetCount + "\">");
                excelDoc.Write("<Table>");
            }
            excelDoc.Write("<Row>"); //ID=" + rowCount + "

            for (int y = 0; y < source.Tables[0].Columns.Count; y++)
            {
                System.Type rowType;
                rowType = x[y].GetType();
                switch (rowType.ToString())
                {
                    case "System.String":
                        string XMLstring = x[y].ToString();
                        XMLstring = XMLstring.Trim();
                        XMLstring = XMLstring.Replace("&", "&");
                        XMLstring = XMLstring.Replace(">", ">");
                        XMLstring = XMLstring.Replace("<", "<");
                        excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
                                       "<Data ss:Type=\"String\">");
                        excelDoc.Write(XMLstring);
                        excelDoc.Write("</Data></Cell>");
                        break;
                    case "System.DateTime":
                        //Excel has a specific Date Format of YYYY-MM-DD followed by 

                        //the letter 'T' then hh:mm:sss.lll Example 2005-01-31T24:01:21.000

                        //The Following Code puts the date stored in XMLDate

                        //to the format above

                        DateTime XMLDate = (DateTime)x[y];
                        string XMLDatetoString = ""; //Excel Converted Date

                        XMLDatetoString = XMLDate.Year.ToString() +
                             "-" +
                             (XMLDate.Month < 10 ? "0" +
                             XMLDate.Month.ToString() : XMLDate.Month.ToString()) +
                             "-" +
                             (XMLDate.Day < 10 ? "0" +
                             XMLDate.Day.ToString() : XMLDate.Day.ToString()) +
                             "T" +
                             (XMLDate.Hour < 10 ? "0" +
                             XMLDate.Hour.ToString() : XMLDate.Hour.ToString()) +
                             ":" +
                             (XMLDate.Minute < 10 ? "0" +
                             XMLDate.Minute.ToString() : XMLDate.Minute.ToString()) +
                             ":" +
                             (XMLDate.Second < 10 ? "0" +
                             XMLDate.Second.ToString() : XMLDate.Second.ToString()) +
                             ".000";
                        excelDoc.Write("<Cell ss:StyleID=\"DateLiteral\">" +
                                     "<Data ss:Type=\"DateTime\">");
                        excelDoc.Write(XMLDatetoString);
                        excelDoc.Write("</Data></Cell>");
                        break;
                    case "System.Boolean":
                        excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
                                    "<Data ss:Type=\"String\">");
                        excelDoc.Write(x[y].ToString());
                        excelDoc.Write("</Data></Cell>");
                        break;
                    case "System.Int16":
                    case "System.Int32":
                    case "System.Int64":
                    case "System.Byte":
                        excelDoc.Write("<Cell ss:StyleID=\"Integer\">" +
                                "<Data ss:Type=\"Number\">");
                        excelDoc.Write(x[y].ToString());
                        excelDoc.Write("</Data></Cell>");
                        break;
                    case "System.Decimal":
                    case "System.Double":
                        excelDoc.Write("<Cell ss:StyleID=\"Decimal\">" +
                              "<Data ss:Type=\"Number\">");
                        excelDoc.Write(x[y].ToString());
                        excelDoc.Write("</Data></Cell>");
                        break;
                    case "System.DBNull":
                        excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
                              "<Data ss:Type=\"String\">");
                        excelDoc.Write("");
                        excelDoc.Write("</Data></Cell>");
                        break;
                    default:
                        throw (new Exception(rowType.ToString() + " not handled."));
                }
            }
            excelDoc.Write("</Row>");
        }
        excelDoc.Write("</Table>");
        excelDoc.Write(" </Worksheet>");
        excelDoc.Write(endExcelXML);
        excelDoc.Close();
        Response.AddHeader("Content-Disposition", "attachment; filename=" + pArchivo + ".xls");
        Response.ContentType = "application/vnd-excel";
        Response.BinaryWrite(o.GetBuffer());
        o.Close();
    }

Desencriptar el viewstate y asegurarlo

Si se desea desencriptar el viewstate se debe utilizar las siguientes instrucciones

byte
[] bytes = Convert.FromBase64String("/wEPDwUJOTU4MjMyMzI1DxYCHgRob2xhBQVtdW5kb2Rk0TeQYE/t2A4VPFBDnmXKxAU3Ndo=");
string decoded = System.Text.Encoding.ASCII.GetString(bytes);
Response.Write(decoded);



<%@ Page ViewStateEncryptionMode="Always|Never|Auto" %>
<%@ Page EnableViewStateMac="true" %>

martes, 10 de noviembre de 2009

Submit con javascript y masterpage vs 2008

Permitir hacer submint con javascript teniendo un masterpage

miércoles, 12 de agosto de 2009

Abrir ventana del Inmediato

La ventana Inmediato se utiliza en tiempo de diseño para depurar y evaluar expresiones, ejecutar instrucciones, imprimir valores de variables, etc. Permite escribir expresiones que el lenguaje de programación evalúa o ejecuta durante la depuración. Para mostrar la ventana Inmediato, abra un proyecto para su edición, a continuación, elija Ventanas en el menú Depurar y seleccione Inmediato.

martes, 11 de agosto de 2009

Reiniciar, detener y arrancar el IIS desde linea de comando

Iniciar
cmd.exe
iisreset /start

Detener
cmd.exe
iisreset /stop

Reiniciar
cmd.exe
iisreset

miércoles, 15 de julio de 2009

Cerrar sesión cuando se utiliza seguridad integrada

function redirect(id)
{
if (document.all)
{
// Limpia la autenticación en Internet Explorer
document.execCommand("ClearAuthenticationCache");

//Redirije a la página de principal
var url='<%= Page.ResolveUrl("~/frmMenu.aspx") %>';
window.location.replace(url+'?id='+id.toString());
}else
{
//En Firefox y los demás navegadores cierra la ventana pero antes
//despliega un mensaje
alert("Para finalizar la sesión su navegador debe ser cerrado");
window.close();
}
}

martes, 7 de julio de 2009

Bajar de rapidshare sin esperar

Para aquellas personas que no cuentan con una cuenta premium de rapidshare, aqui les traigo este truco que podria ayudarles.
1. Le damos click a enlace que queremos bajar, por ejemplo: http://rapidshare.com/files/230628121/JBlogIE8Portable.zip
2. Le damos clic en "Free User"
3. Luego nos aparecera el contador que va disminuyendo, debemos copiar lo siguiente en la barra de direcciones: javascript:alert(c=0) y le damos enter.
4. Observaran la siguiente imagen:
5. Le dan aceptar y luego veran que aparecera el boton de "Download" y Listo.

martes, 30 de junio de 2009

Respaldar imagenes del Messenger

Para respaldar los iconos del Messenger se pueden copiar los archivos que se encuentran en la siguiente dirrección, se debe cambiar la extensión de los mismos a .GIF

C:\Documents and Settings\USUARIO\Configuración local\Datos de programa\Microsoft\Messenger\CUENTA@hotmail.com\ObjectStore\CustomEmoticons


Otra manera es con el msnbackup

La dirección para bajarlo es la siguiente

http://www.baisoft.it/msnbackup_download.asp

viernes, 26 de junio de 2009

Declaración de Cursores en SQL 2000

Esta es la sintaxis basica para declarar un cursor en SQL SERVER 2000

DECLARE authors_cursor CURSOR FOR
SELECT au_lname FROM authors
WHERE au_lname LIKE "B%"
ORDER BY au_lname

OPEN authors_cursor

-- Perform the first fetch.
FETCH NEXT FROM authors_cursor

-- Check @@FETCH_STATUS to see if there are any more rows to fetch.
WHILE @@FETCH_STATUS = 0
BEGIN
-- This is executed as long as the previous fetch succeeds.
FETCH NEXT FROM authors_cursor
END

CLOSE authors_cursor
DEALLOCATE authors_cursor
GO

lunes, 22 de junio de 2009

Acceder a los Settings de la aplicación en Windows Forms con C#

Para acceder a los settings que tiene la aplicación form se hace de la siguiente manera

prjAdmUsuarios.Properties.Settings.Default.lenc

Proyecto.Properties,Settings.Usuario.Setting


Fuente: http://www.codeproject.com/KB/cs/UserSettings.aspx

sábado, 20 de junio de 2009

Obtener datos ocultos de un GridView

Para obtener valores ocultos de un GridView se deben almacenar las columnas del objeto enlazado en una popiedad llamada DataKeys, cada columna debe ir separada por coma (,), estos DataKeys se llaman de la siguiente forma:

dgView.SelectedRow.DataKey["NombreDelDataKey"]

Pasar valores desde un popup

Primero para llamar una ventana como popup se puede usar el siguiente JavaScript:

function OpenDefault(url, height, width) {
var str = "toolbar=0,location=0,directories=0,status=1,menubar=0,scrollbars=1,Titlebar=0,resizable=0,fullscreen=0,"
str += "height=" + height + ",innerHeight=" + height;
str += ",width=" + width + ",innerWidth=" + width;
var name = "_blank"
if (window.screen) {
var ah = screen.availHeight - 30;
var aw = screen.availWidth - 10;
var xc = (aw - width) / 2;
var yc = (ah - height) / 2;
str += ",left=" + xc + ",screenX=" + xc;
str += ",top=" + yc + ",screenY=" + yc;
}
window.open(url, name, str);

}

Luego para devolver un valor del popup a la página principal se utiliza el opener de la siguiente forma

window.opener.document.getElementById("campo").value = valorDelPopUp;

jueves, 11 de junio de 2009

T-SQL: Obtener diferencia entre fechas

FUNCION DATEDIFF ( datepart , startdate , enddate )

Parámetros
datepart

Is the part of startdate and enddate that specifies the type of boundary crossed. The following table lists all valid datepart arguments. User-defined variable equivalents are not valid.

datepart Abbreviations

year

yy, yyyy

quarter

qq, q

month

mm, m

dayofyear

dy, y

day

dd, d

week

wk, ww

hour

hh

minute

mi, n

second

ss, s

millisecond

ms

microsecond

mcs

nanosecond

ns

startdate

Is an expression that can be resolved to a time, date, smalldatetime, datetime, datetime2, or datetimeoffset value. date can be an expression, column expression, user-defined variable or string literal. startdate is subtracted from enddate.

To avoid ambiguity, use four-digit years. For information about two digits years, see two digit year cutoff Option.

enddate

See startdate.


Ejemplo
DECLARE @startdate datetime2 = '2007-05-05 12:10:09.3312722';
DECLARE @enddate datetime2 = '2007-05-04 12:10:09.3312722';
SELECT DATEDIFF(day, @startdate, @enddate);

miércoles, 10 de junio de 2009

JavaScript para Evitar el botón derecho

Se debe utilizar el siguiente JavaScript de preferencia en un archivo .js



var message="";

function clickIE()
{
if (document.all)
{
(message);
return false;
}
}

function clickNS(e)
{
if (document.layers||(document.getElementById&&!document.all))
{
if (e.which==2||e.which==3)
{
(message);
return false;
}
}
}

if (document.layers)
{
document.captureEvents(Event.MOUSEDOWN);document.onmousedown=clickNS;
}
else
{
document.onmouseup=clickNS;document.oncontextmenu=clickIE;
}

document.oncontextmenu=new Function("return false")

Cambiar Application pool en IIS 6.0

  1. Se debe crear un usuario del dominio con los permiso para ejecutarse como servicio (Logon as a service) y como un trabajo de lotes (Log on as a batch job)


  1. Ese usuario debe pertenecer al grupo IIS_WPG del servidor donde correrá el pool de aplicaciones


  1. Se deben otorgar permisos al usuario sobre la carpeta “%Windir%\Microsoft.NET\Framework\version\Temporary ASP.NET Files


  1. En línea de comando (Ejecutar > cmd), en la ruta: C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727 y ejecutar el comando: aspnet_regiis -ga Domino\usuario

  1. Crear un nuevo application pool en el IIS

  1. Se debe asignar el usuario creado


  1. Por último se debe reiniciar el IIS mediante línea de comando digitando IISRESET

Actualizar políticas del Active Directory

Para actualizar las políticas del Active Directory se debe ejecutar desde línea de comandos (cmd) el comando gpupdate /force
 
Locations of visitors to this page