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();
    }

 
Locations of visitors to this page