lunes, 17 de septiembre de 2012

MVC POST

Creamos un formulario con dos textBoxes (txtApellido y txtNombre) y un botón (Enviar)

<form action="Buscar" method="POST">
@Html.Label("Nombre:")
@Html.TextBox("txtNombre")
@Html.Label("Apellido:")
@Html.TextBox("txtApellido")
<input type="submit" value="Enviar" />
</form>

Creamos una clase (Clientes) con dos atributos: Apellido y Nombre


    public class Clientes
    {
        public string Apellido { get; set; }

        public string Nombre { get; set; }
    }

Un método que devuelve una lista de clientes cuyos apellidos y nombres coinciden con los pasados por parámetros: ObtenerListaClientes

    public List<Clientes> ObtenerListaClientes(string apellido,string nombre)
        {
            var cliente1 = new Clientes { Apellido = "Marchetti", Nombre = "Javier" };
            var cliente2 = new Clientes { Apellido = "Perez", Nombre = "Juan" };
            var cliente3 = new Clientes { Apellido = "Diehl", Nombre = "Dieter" };
            var cliente4 = new Clientes { Apellido = "Lee", Nombre = "Chuang" };
            var cliente5 = new Clientes { Apellido = "Dustin", Nombre = "Josh" };

            var lista = new List<Clientes> { cliente1, cliente2, cliente3, cliente4, cliente5 };

            return lista.Where(l => l.Apellido == apellido && l.Nombre == nombre).ToList();
        }

El Action: Buscar:
obtenemos los valores de los textBoxes:

 var apellido = form["txtApellido"];
 var nombre = form["txtNombre"];

y llamamos al método: ObtenerListaCliente pasando como parametros el apellido y el nombre

Retornamos el Json con la lista obtenida:

return Json(lista);


   [HttpPost]
        public ActionResult Buscar(FormCollection form)
        {
            var apellido = form["txtApellido"];
            var nombre = form["txtNombre"];

            var lista = ObtenerListaClientes(apellido, nombre);
         
            return Json(lista);
        }



miércoles, 12 de septiembre de 2012

$.load()

ejemplo de la función load:

$("#contenedor").load("../Inicio/Lista #DivContenido");

Lanza una petición a la url: ../Inicio/Lista del html de la respuesta obtenemos solo el div: DivContenido a este mismo lo insertamos en el div: contenedor

jueves, 27 de octubre de 2011

seguridad en ASP.NET (C#)

En el Web.config.

<authentication mode="Forms">

   <forms name=".ASPXFORMSDEMO" loginUrl="logon.aspx"

   protection="All" path="/" timeout="30" />

</authentication>

 



<authorization>

   <deny users ="?" />

   <allow users = "*" />

</authorization>



private bool Validar_Usuario( string userName, string passWord )

{

SqlConnection conn;

SqlCommand cmd;

string lookupPassword = null;



// Check for invalid userName.

// userName must not be null and must be between 1 and 15 characters.

if ( (  null == userName ) || ( 0 == userName.Length ) || ( userName.Length > 15 ) )

{

System.Diagnostics.Trace.WriteLine( "[ValidateUser] Input validation of userName failed." );

return false;

}



// Check for invalid passWord.

// passWord must not be null and must be between 1 and 25 characters.

if ( (  null == passWord ) || ( 0 == passWord.Length ) || ( passWord.Length > 25 ) )

{

System.Diagnostics.Trace.WriteLine( "[ValidateUser] Input validation of passWord failed." );

return false;

}



try

{

// Consult with your SQL Server administrator for an appropriate connection

// string to use to connect to your local SQL Server.

conn = new SqlConnection( "server=localhost;Integrated Security=SSPI;database=pubs" );

conn.Open();



// Create SqlCommand to select pwd field from users table given supplied userName.

cmd = new SqlCommand( "Select pwd from users where uname=@userName", conn );

cmd.Parameters.Add( "@userName", SqlDbType.VarChar, 25 );

cmd.Parameters["@userName"].Value = userName;



// Execute command and fetch pwd field into lookupPassword string.

lookupPassword = (string) cmd.ExecuteScalar();



// Cleanup command and connection objects.

cmd.Dispose();

conn.Dispose();

}

catch ( Exception ex )

{

// Add error handling here for debugging.

// This error message should not be sent back to the caller.

System.Diagnostics.Trace.WriteLine( "[ValidateUser] Exception " + ex.Message );

}



// If no password found, return false.

if ( null == lookupPassword )

{

// You could write failed login attempts here to event log for additional security.

return false;

}



// Compare lookupPassword and input passWord, using a case-sensitive comparison.

return ( 0 == string.Compare( lookupPassword, passWord, false ) );



}





Generar el vale de autenticación
Cifrarlo
Crear una cookie
Agregarla a la respuesta y redirija al usuario.

Esto le ofrece más control sobre cómo crear la cookie. También puede incluir datos personalizados junto con FormsAuthenticationTicket en este caso.





private void cmdLogin_ServerClick(object sender, System.EventArgs e)

{

   if (Validar_Usuario(txtUserName.Value,txtUserPass.Value) )

   {

      FormsAuthenticationTicket tkt;

      string cookiestr;

      HttpCookie ck;

      tkt = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now,

DateTime.Now.AddMinutes(30), chkPersistCookie.Checked, "your custom data");

      cookiestr = FormsAuthentication.Encrypt(tkt);

      ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);

      if (chkPersistCookie.Checked)

      ck.Expires=tkt.Expiration;

    ck.Path = FormsAuthentication.FormsCookiePath;

      Response.Cookies.Add(ck);



      string strRedirect;

      strRedirect = Request["ReturnUrl"];

      if (strRedirect==null)

            strRedirect = "default.aspx";

         Response.Redirect(strRedirect, true);

   }

   else

      Response.Redirect("logon.aspx", true);

}




Los Espacios de Nombres que debemos agregar:

using System.Data.SqlClient;
using System.Web.Security;

Exportar los datos de un GridView de ASP.NET a Excel

<code>
Response.ClearContent();<br />
&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Response.AddHeader("content-disposition", "attachment;filename=ArchivoExcel.xls");<br />
&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Response.Charset = "";<br />
&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Response.Cache.SetCacheability(HttpCacheability.NoCache);<br />
&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Response.ContentType = "application/vnd.xls";<br />
<br />
&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;System.IO.StringWriter stringWrite = new System.IO.StringWriter();<br />
&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);<br />
<br />
&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;GridServidores.RenderControl(htmlWrite);<br />
&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Response.Write(stringWrite.ToString());<br />
&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Response.End();
</code>



Para que esto funcione en la cabecera del Archivo .aspx

<code>
EnableEventValidation = "false"
</code>

sábado, 22 de octubre de 2011

Conexiones con ASP.net

aquí pueden encontrar las cadenass de conexión a cualquier servidor de bases de datos:

http://www.connectionstrings.com/


 
y más!!!

Cadena de conexión (C# y SQL Server)

Cadena de conexión con autenticación de Windows

Para conectar a una base de datos de SQL Server con autenticación de Windows, la cadena de conexión será:

Data Source = ServidorSQL; Initial Catalog = BaseDatos; Integrated Security = True

Cadena de conexión con autenticación de SQL Server

Para conectar a una base de datos de SQL Server usando autenticación del propio SQL Server, la cadena de conexión será:

data source = ServidorSQL; initial catalog = BaseDatos; 
user id = Usuario; password = Contraseña