miércoles, 18 de enero de 2017

Manejar Session de ASP.net con el servicio ASP.net State Service

Este servicio permite compartir la sesión entre aplicaciones ASP.net, esto es muy útil para el tema de balanceo de cargas o cuanto se utilizan varios Worker Process (Ya que cada uno maneja su propia memoria por tanto su sesión no es compartida) o la aplicación está alojada en una granja.

¿Qué se requiere? 

Hay que tener instalado el IIS.

Cómo se habilita?

Se debe iniciar el servicio de Windows ASP.net State Service.

 

Importante, por defecto el servicio se encuentra inactivo y escucha por el puerto 42424, además viene configurado por defecto para que no permita conexiones remotas por lo que en caso de querer habilitar las mismas debe modificar el valor de la llave en el siguiente registro de windows.


HKLM\SYSTEM\CurrentControlSet\Services\aspnet_state\Parameters\AllowRemoteConnection   --> El valor debe estar en 1 para que permita las conexiones 




miércoles, 6 de junio de 2012

Como obtener las columnas de todas las tablas con SQL Server

Algunas ocasiones se requiere crear un diccionario de datos sobre un SQL Server, para obtener todas las columnas de todas las tablas de una BD se puede ejecutar este script anónimo begin declare @tabla varchar(100) declare cTablas cursor for select table_name from INFORMATION_SCHEMA.TABLES order by table_name open cTablas fetch cTablas into @tabla while @@FETCH_STATUS=0 begin select @tabla SELECT column_name "Columna",DATA_TYPE "Tipo",ISNULL(CONVERT(varchar,COALESCE(numeric_precision,CHARACTER_MAXIMUM_LENGTH)),'N/A') "Tamaño",is_nullable "Acepta Nulos",' ' "Descripción" FROM INFORMATION_SCHEMA.COLUMNS c WHERE c.TABLE_NAME = @tabla fetch cTablas into @tabla print @tabla end close cTablas deallocate cTablas end

martes, 15 de febrero de 2011

Serializar y Deserializar clases

 using System; 
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;
using System.Xml;
namespace TestStuff
{
public class Configuration
{
#region properties
public List<string> UIComponents { get; set; }
public List<string> Settings { get; set; }
#endregion
//serialize itself
public string Serialize()
{
MemoryStream memoryStream = new MemoryStream();
XmlSerializer xs = new XmlSerializer(typeof(Configuration));
using (StreamWriter xmlTextWriter = new StreamWriter(memoryStream))
{
xs.Serialize(xmlTextWriter, this);
xmlTextWriter.Flush();
//xmlTextWriter.Close();
memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
memoryStream.Seek(0, SeekOrigin.Begin);
StreamReader reader = new StreamReader(memoryStream);
return reader.ReadToEnd();
}
}
//deserialize into itself
public void Deserialize(string xmlString)
{
String XmlizedString = null;
using (MemoryStream memoryStream = new MemoryStream())
{
using (StreamWriter w = new StreamWriter(memoryStream))
{
w.Write(xmlString);
w.Flush();
XmlSerializer xs = new XmlSerializer(typeof(Configuration));
memoryStream.Seek(0, SeekOrigin.Begin);
XmlReader reader = XmlReader.Create(memoryStream);
Configuration currentConfig = (Configuration)xs.Deserialize(reader);
this.Settings = currentConfig.Settings;
this.UIComponents = currentConfig.UIComponents;
w.Close();
}
}
}
static void Main(string[] args)
{
Configuration thisConfig = new Configuration();
thisConfig.Settings = new List<string>(){
"config1", "config2"
};
thisConfig.UIComponents = new List<string>(){
"comp1", "comp2"
};
//serializing the object
string serializedString = thisConfig.Serialize();

Configuration myConfig = new Configuration();
//deserialize into myConfig object
myConfig.Deserialize(serializedString);
}
}

}

lunes, 31 de enero de 2011

Habilitar SSL en un WCF (Https)

Para habilitar el SSL en un WCF el web.config debe contener las siguientes instrucción:

<system.serviceModel>


<behaviors>    


 <endpointBehaviors>


  <behavior name="TestServiceAspNetAjaxBehavior">


   <enableWebScript />


  </behavior>


 </endpointBehaviors>


</behaviors>


<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />


<services>


 <service name="TestService">


  <endpoint address="" behaviorConfiguration="TestServiceAspNetAjaxBehavior"


   binding="webHttpBinding" bindingConfiguration="webBinding" contract="TestService" />


 </service>


</services>


 <bindings>


   <webHttpBinding>


     <binding name="webBinding">


       <security mode="Transport">


       </security>


     </binding>


   </webHttpBinding>


 </bindings>


</system.serviceModel>

lunes, 22 de noviembre de 2010

Subir o bajar el Scroll de un div con JavaScript

Esta es una función para realizarlo con animación

<script type="text/javascript">

var t;
var doLoop = true;

function scrollDivToTop(divid)
{
var div = document.getElementById(divid);

if (div.scrollTop>0 && doLoop)
{
div.scrollTop-=3;
t = setTimeout("scrollDivToTop('" + divid + "')", 1);
}
else clearTimeout(t);
}

function scrollDivToBottom(divid)
{

var div = document.getElementById(divid);

if (div.scrollTop<999999999 && doLoop)
{
div.scrollTop+=3;
t = setTimeout("scrollDivToBottom('" + divid + "')", 1);
}
else clearTimeout(t);
}

function stop()
{
doLoop = false;
setTimeout('doLoop = true;', 5);
}

</script>

Lo importante es esta parte

div.scrollTop=0; //0 para que se suba al principio del div  y 999999999 para que baje al fondo del div

Join entre DataTables en LINQ

private void algo()
{
     DataTable dtPolizas = new DataTable();
     DataTable dtServicios = new DataTable();
     var ret = from p in dtPolizas.AsEnumerable()
               join q in dtServicios.AsEnumerable() on p.Field<int>("ID") equals q.Field<int>("ID") into UP
               from q in UP.DefaultIfEmpty()
               where (q.Field<string>("estado") == "00" || q.Field<string>("estado") == "12" && q.Field<int>("estado") == Convert.ToInt32(DateTime.Now.AddDays(-90).ToString("yyyyMMdd")))
               select new
               {
                   ID = Convert.ToDateTime(p.Field<int>("ID")),
                   Type = p.Field<string>("Type"),
                   Part = q.Field<int>("Part"),
                   Quantity = q.Field<int>("Quantity")
               };
     foreach (var ins in ret)
     {
     }
}

Filtrar caracteres de una cadena con LINQ

private string ReemplazarCadena(string pOrigen, int pTamano)
{
IEnumerable stringQuery =
from ch in pOrigen
where !Char.IsNumber(ch)
select ch;
foreach (char item in stringQuery)
pOrigen = pOrigen.Remove(pOrigen.IndexOf(item),1);

pOrigen = pOrigen.PadLeft(pTamano,'0');
return pOrigen;
}

lunes, 12 de julio de 2010

Contador regresivo en JavaScript

Contador regresivo generado en JavaScript

var tiempo = 10;

function ContadorRegresivo()
{
var valor = document.getElementById('tiempo');
valor.value = tiempo;
tiempo = tiempo-1;
if (tiempo > -1)
{
setTimeout("ContadorRegresivo()", 1000);
}
}

function InicializarContador()
{
tiempo = 10;
ContadorRegresivo();
}

lunes, 5 de julio de 2010

Error con el ambiente de Visual Studio 2010

En caso de que al generar una referencia web el editor muestre este mensaje "Los componentes de enumeracion de servicios web no estan disponibles. es necesario reinstalar visual studio para agregar las referencias web a su aplicacion"

Se debe ingresar el comando devenv /resetskippkgs

martes, 13 de abril de 2010

Hacer que la página expire

Muchas veces se requiere que una página se cargue en su totalidad, en ocasiones para evitar que el navegador despliegue nuevamente los datos que se ingresaron la última vez que se presentó la página

Para evitar esto se debe quitar la página del cache agregando las siguientes instrucciones

Código en C#

Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();

Código en Vb.net

Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1))
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.Cache.SetNoStore()


lunes, 29 de marzo de 2010

Como instalar un servicio desarrollado en .net

Para instalarlo se ejecuta desde la línea de comando de .net la siguiente instrucción

 

installutil  “ruta del ejecutable”

para desinstalar se ejecuta la siguiente

installutil  /u “ruta del ejecutable”

viernes, 5 de marzo de 2010

Agregar usuario en Active Directory desde .net (C# Framework 3.5)

using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;

public string AgregarUsuario(string pUsuario,
string Nombre,
string Apellido,
string PasswordEncriptado,
string email,
bool forzarCambioClave,
bool ClaveNoExpira,
bool UsuarioHabilitado)
{
try
{
string[] arrTokens = _domainName.Split(new char[] { '.' }, 100, StringSplitOptions.None);
string LDAPDomainPath = this._ouName + ",DC=" + string.Join(",DC=", arrTokens);

//Contexto del active directory (Raíz)
PrincipalContext insPrincipalContext = new PrincipalContext(ContextType.Domain, this._serverName + "." + this._domainName, LDAPDomainPath, "UsuarioConPrivilegiosEnElAD", "ClaveDelMismo");//"domainController.Dominio.com" "Dominio.com","DC=dominio,DC=com"

//Creamos el nuevo usuario


UserPrincipal user = new UserPrincipal(insPrincipalContext, pUsuario.Trim(), PasswordEncriptado, UsuarioHabilitado);

//Nombre de la entidad de seguridad
user.GivenName = Nombre.Trim();
user.DisplayName = Nombre.Trim();

//Apellido del Usuario
user.Surname = (Apellido == "") ? Nombre.Trim() : Apellido.Trim();

//Usuario @ Dominio
user.UserPrincipalName = pUsuario.Trim().ToLower() + "@" + _domainName;

if (Cedula.Length < 20)
user.SamAccountName = Cedula.Trim().ToLower();
else
user.SamAccountName = Cedula.Trim().Substring(0, 20).ToLower();

//Seteamos el correo
if (email.Trim() != "")
user.EmailAddress = email;

//force the user to change password at next logon
if (forzarCambioClave)
user.ExpirePasswordNow();

//El password no expira
if (ClaveNoExpira)
user.PasswordNeverExpires = true;

//save the user to the directory
user.Save();


return "true,Usuario incluido satisfactoriamente";
}
catch (Exception ex)
{
return "false," + ex.Message;
}


}

miércoles, 27 de enero de 2010

Pasar valores a una ventana padre de un popup

<script type="text/javascript">
    function Salir() {
        window.opener.document.getElementById('TextBox1').value = document.getElementById('texto').value; //Aqui asigna el valor al textbox del padre
        window.opener.document.getElementById('form1').submit(); //hace le hace el submit al padre
        window.close(); //cierra el popup
    }
</script>

lunes, 4 de enero de 2010

Crear un servicio de Windows con intervalo

En el archivo Designer.cs del servicio se deben modificar las siguientes líneas

private void InitializeComponent()

{

this.mytimer = new System.Timers.Timer();

((System.ComponentModel.

ISupportInitialize)(this.mytimer)).BeginInit();

//

// mytimer

//

this.mytimer.Enabled = true;

this.mytimer.Interval = 300000; //El equivalente en milisegundos en este caso son 5 minutos

this.mytimer.Elapsed += new System.Timers.ElapsedEventHandler(this.mytimer_Elapsed);

//

// Nombre del Servicio

//

this.ServiceName = "Nombre del Servicio";

((System.ComponentModel.

ISupportInitialize)(this.mytimer)).EndInit();

}

Luego en el código del servicio de programan los siguientes metodos

protected override void OnStart(string[] args)
{
   //Se ejecuta cuando se inicia el proceso
}

protected override void OnStop()
{
   //Se ejecuta cuando se ejecuta el proceso
}

private void mytimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    //Se ejecuta una vez que ha trascurrido el tiempo definido en el

//Timer

}

 

 

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.
 
Locations of visitors to this page