lunes, 16 de abril de 2012

Server controls

So, instead of defining HTML controls in your pages directly, you define an ASP.NET Server
Control with the following syntax, where the italicized parts differ for each control.

<asp:TypeOfControl ID=”ControlName“ Runat=”Server” />

For the controls that ship with ASP.NET 4 you always use the asp: prefix followed by the name of
the control. For example, to create a TextBox that can hold the same welcome message and current
time, you can use the following syntax:

<asp:TextBox ID=”Message” Runat=”Server” />

Note that the control has two attributes: ID and Runat. The ID attribute is used to uniquely identify
a control on the page, so you can program against it. It’s important that each control on the page
has a unique ID; otherwise the ASP.NET runtime won’t understand what control you’re referring to.
If you accidentally type a duplicate control ID, VWD will signal the problem in the error list. The
mandatory Runat attribute is used to indicate that this is a control that lives on the server. Without
this attribute, the controls won’t be processed and will end up directly in the HTML source. If you
ever feel you’re missing a control in the final output in the HTML of the browser, ensure that the
control has this required attribute. Note that for non-server elements, like plain HTML elements,
the Runat attribute is optional. With this attribute on non-server controls, they can be reached by
your programming code. You learn more about this later in the book.
You can easily add the Runat attribute to an existing element by typing runat and pressing the
Tab key.
The preceding example of the TextBox is using a self-closing tag where the closing slash (/) is embedded
in the opening tag. This is quite common for controls that don’t need to contain child content
such as text or other controls. However, the long version, using a separate closing tag is acceptable as
well:

<asp:TextBox ID=”Message” Runat=”Server”></asp:TextBox>

You can control the default behavior of closing tags per tag using Tools ➪ Options ➪ Text Editor ➪
HTML ➪ Formatting ➪ Tag Specific Options.
You can program against this text box from code that is either placed inline with the page or in a
separate Code Behind file, as you saw in Chapter 2. To set the welcome message and the time, you
can use the following code:

VB.NET
Message.Text = “Hello World, the time is “ & DateTime.Now.TimeOfDay.ToString()
C#
Message.Text = “Hello World, the time is “ + DateTime.Now.TimeOfDay.ToString();

The definition of the control in the markup section of the page is now separated from the actual
code that defines the text displayed in the text box, making it easier to define and program the text
box (or any other control) because it enables you to focus on one task at a time: either declaring the
control and its visual appearance in the markup section of the page, or programming its behavior
from a code block.

domingo, 15 de abril de 2012

Cookies en ASP.NET

Las cookies son una parte muy importante en todas las aplicaciones Web.

Si bien nunca se recomienda basar una aplicación en el funcionamiento de las cookies (ya que el usuario siempre puede borrarlas y/o modificarlas), éstas nos ofrecen la posibilidad a los webmasters de dar muchos y buenos servicios a nuestros usuarios.

Y como siempre, si unimos la palabra webmaster con la de ASP.NET, nos da como resultado la facilidad. Y es que si trabajar con cookies ha sido siempre sencillo en antiguos lenguajes como ASP o PHP, con ASP.NET lo es mucho más, pero además se le une la orientación a objetos y el tipado de las cookies.

En ASP.NET las cookies se manejan con HttpCookie, que está dentro del namespace System.Web.

Pero vayamos al grano con los usos típicos que se les hace a las cookies:

1.- Crear una cookie
        // Creamos elemento HttpCookie con su nombre y su valor
        HttpCookie addCookie = new HttpCookie("subgurim", DateTime.Now.ToString());
       
        // Si queremos le asignamos un fecha de expiración: mañana
        addCookie.Expires = DateTime.Today.AddDays(1).AddSeconds(-1);
       
        // Y finalmente ñadimos la cookie a nuestro usuario
        Response.Cookies.Add(addCookie);


2.- Recoger una cookie
        // Recogemos la cookie que nos interese
        HttpCookie cogeCookie = Request.Cookies.Get("subgurim");

        // O a la antigua usanza, que es lo mismo pero me gusta menos
        // HttpCookie cogeCookie = Request.Cookies["subgurim"];

        // O mostramos todas las cookies por pantalla
        foreach (HttpCookie cookie in Request.Cookies)
        {
            Response.Write(cookie.Name + ":" + cookie.Value + "<br />");
        }



3.- Modificar una cookie
        // Puede darse el caso que lo que queramos es modificar una cookie
        // Por ejemplo vamos a cambiar el tiempo de expiración de la cookie que creamos al principio
        HttpCookie modificaCookie = Request.Cookies.Get("subgurim");
        modificaCookie.Expires = DateTime.Now.AddDays(7);
        Response.Cookies.Set(modificaCookie);


4.- Borrar una cookie
        // Borrarla es realmente sencillo
        Response.Cookies.Remove("subgurim");

        // O si quieres borrarlas todas...
        Response.Cookies.Clear();


5.- Cookies multidimensionales
Sí, ya lo sé, una sóla cookie puede contener varios valores... pero ASP.NET nos lo sigue poniendo muy sencillo. Veamos cómo creamos una cookie multidimensional y cómo la recogemos. Por extensión sabemos ya modificar esa cookie así como borrarla.

5.1 - Crear cookie multidimensional
        HttpCookie addMultiCookie = new HttpCookie("subgurimMultidimensional");
        for (int i = 0; i < 10; i++)
        {
            // Mi modo preferido
            addMultiCookie.Values.Add(i.ToString(), "Elemento " + i.ToString());
            
             // Modo antiguo y que no me gusta
            //addMultiCookie[i.ToString()] = "Elemento " + i.ToString();
        }
        Response.Cookies.Add(addMultiCookie);


Como observamos, la única diferencia es que accedemos a la colección Values (System.Collections.Specialized.NameValueCollection), y en ella podemos ejecutar lo mismo que en cualquier otro tipo de colección.

5.2 Recoger cookie multidimensional
        HttpCookie cogeMultiCookie = Request.Cookies.Get("subgurimMultidimensional");   
        // Accedemos a cualquiera de los valores.
        // Por ejemplo, en este caso recogemos el valor de la cookie cuyo nombre es "5"
        string valorCualquiera = cogeMultiCookie.Values.Get("5");



Nota
: Fijaos en que siempre que recogemos una cookie, utilizamos Request, y cuando la modificamos o borramos, utilizamos Response.
Nota 2: El objeto HttpCookie sólo contiene a la cookie, si queremos darle valor a los cambios que le hagamos, siempre debemos utilizar el Response y el Request.

Aplicar temas en nuestro sitio web

Se puede colocar el elemento <link> en la seccion <head> de la página maestra:

<head runat=”server”>
<title></title>
<asp:ContentPlaceHolder ID=”head” runat=”server”>
</asp:ContentPlaceHolder>
<link href=”../Styles/Styles.css” rel=”stylesheet” type=”text/css” />
</head>


Otra forma es agregar la carpeta App_Themes en la carpeta principal de nuestro sitio web, por defecto ir se crea una subcarpeta llama Theme1, cambiar su nombre por el tema que vamos a aplicar (en este ejemplo Monochrome). En esta subcarpeta agregar el .css que queremos aplicar a nuestro sitio. Luego ir al web.config de nuestro sitio web y directamente dentro del elemento <inside> agregar un elmento <pages>:

<system.web>
<pages theme=”Monochrome”></pages>
...


Extendiendo un tema 

Además de archivos CSS y skins, un tema tambien puede contener imágenes. El uso mas común de imágenes en temas es enlazarlas desde tu CSS. Para hacer bien esto es importante entender como una CSS se enlaza con las imágenes.

Por su diseño, una imagen que esta enlazada a un selector CSS se buscará de forma relativa a la ubicación del archivo CSS, a menos que usted le da una ruta que comienza con una barra diagonal (/) para indicar la raíz del sitio. 
Para referirse al  archivo MenuBackground.jpg del folder Imagenes del tema Monochrome, tu puedes agregar la siguiente CSS a Monochrome.css

#MenuWrapper
{
background-image: url(Images/MenuBackground.jpg);
}


Si se quiere enlazar una imagen a la carpeta Images de la raíz del sitio se usaría esta CSS:


background-image: url(/Images/MenuBackground.jpg);