9.29.2008

Paging using a CheckBoxList, a PagedDataSource and the Ajax.NET

Recently, I had the need for doing paging using a check list box. Besides, I need to use Ajax.Net for making the paging work faster. So I decided to blog on how to do this task.

First web have to add the Ajax Script Manager and the Ajax Update panel to the page, so we can drag our list control inside it and page using the ajax functionality.

    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <div>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
        
        </ContentTemplate>
        </asp:UpdatePanel>

    </div>

Then we add the list and the next and previous controls for moving using the paging functionality.

<ContentTemplate>

        <asp:CheckBoxList ID="CheckBoxList1" runat="server">
        </asp:CheckBoxList>
        <div>
            <asp:LinkButton ID="lnkPrev" runat="server"  onclick="lnkPrev_Click"><<</asp:LinkButton> ||
            <asp:LinkButton ID="lnkNext" runat="server" onclick="lnkNext_Click">>></asp:LinkButton>

        </div>

</ContentTemplate>

Then we need to add the code functionality to make the complete code work. First, we have to create a function that does the Binding for the list. Here is where the PagedDataSource object is used. Instead of doing the bind directly from the collection to the list, we have to bind it to the PagedDataSource object, this allows all the paging functionality for the List. Besides, we need to set the page index, this will be doing by the use of a session variable.Then we just bind the list to the PagedDataSource object like follows.

private void DoPaging( )
{
    List<int> sampleData = new List<int>();
    for (int i = 0; i < 150000; i++)
    {
        sampleData.Add(i);
    }

    PagedDataSource pagingSource = new PagedDataSource( );
    pagingSource.DataSource = sampleData;
    pagingSource.AllowPaging = true;
    pagingSource.PageSize = 10;
    pagingSource.CurrentPageIndex = (int) Session ["PageNumber"];

    CheckBoxList1.DataSource = pagingSource;
    CheckBoxList1.DataBind( );

}

We have to initialize the page doing the call for the method explained before and we also set the Page number session variable to the first page since we are initializing the form.

protected void Page_Load(object sender, EventArgs e)
{
    if ( !Page.IsPostBack)
    {
        Session["PageNumber"] = 0;
        DoPaging();
    }
}

Then we have to create the next and the previous events handlers for the link buttons we placed for navigation.

protected void lnkNext_Click( object sender, EventArgs e )
{
    int currentIndex = (int) Session["PageNumber"];
    Session["PageNumber"] = currentIndex + 1;
    DoPaging();
}
protected void lnkPrev_Click( object sender, EventArgs e )
{
    int currentIndex = (int)Session["PageNumber"];
    Session["PageNumber"] = currentIndex - 1;
    DoPaging();
}

And that’s all. We run the demo and we have a CheckListBox with paging and with ajax.

It is important to point that we are initializing the paging using a simple int generic that fills with 150000 items. If we are going to the database, we have to use some other method for not keep going to the database each time we click next or previous, for example, storing your entity object inside a session variable or Serializing your object in the server side.

2.04.2008

Conectar un servicio Web desde un emulador de Smartphone

En días pasados, tuve la oportunidad de llevar a cabo una simple aplicación que consumía un servicio web desde una aplicación móvil desde un emulador de un Smartphone desde Windows Vista. Llevar a cabo esta tarea parece simple, ya que uno tiende a pensar que simplemente lo que requiero es desarrollar la aplicación móvil, agregar la referencia web y listo…consumirla. Pero como siempre, hay condiciones que se dan y no se tienen en cuenta a la hora de desarrollar este tipo de aplicación. Por esta razón, me doy a la tarea de documentar todos los pasos que tuve que llevar a cabo para lograr que la aplicación funcionara tal y como se esperaba.
Para conectar un emulador a un servicio Web se deben de tomar las siguientes consideraciones:
1. El primer paso es desarrollar el servicio web y probarlo desde el internet explorer para validar su funcionamiento correcto. Luego se instala el servicio Web en el IIS. Esto para permitir a la aplicación web referenciar el servicio desde el servidor del sistema operativo y no desde el servidor web que trae para desarrollo Visual Studio .NET.
2. El segundo paso es agregar la referencia web del servicio recién instalado y que se desea consumir en el proyecto móvil. En este paso es importante no usar la referencia del proyecto de servicio web que reside en la misma solución, ya que esto conlleva a que el debuguer de la aplicación utilice el Web server que trae .NET por defecto para hacer deploy del servicio web recién desarrollado; y este servidor web, bloquea todas las conexiones externas que se le hagan, incluso si se está usando un emulador desde la misma máquina.
3. Seguidamente, nos aseguramos que el servicio web no tenga en el URI, el nombre localhost. Esto porque el emulador no encontrará el servicio web, ya que cuando hace referencia a localhost, busca en el Sistema Operativo del emulador. Un ejemplo de cómo debería quedar esta dirección es la siguiente:
this.Url = "http://192.168.1.65/Query/Consulta.asmx";
4. El cuarto paso es levantar y conectar el emulador. Para esto, se procede desde la opción del Visual Studio -> Tools -> Device Emulator Manager a llevar a cabo esta tarea. Una vez en esta pantalla, procedemos a seleccionar la opción conectar, dando clic derecho en el emulador que queremos utilizar. Seleccionamos conectar y esperamos hasta que el ícono de conectado, esté disponible. Seguidamente, seleccionamos en el emulador que esta ejecutándose la opción de Cradle.

5. El siguiente paso es conectar el emulador utilizando el Windows Mobile Device Center. Para tal fin primera mente inicializamos el device center y lo configuramos desde la opción “connection settings” quedando la configuración final de la siguiente forma.

Seguidamente agregamos el loopback adapter como un dispositivo de red en el sistema operativo ( agregar software – dispositivos de red – Microsoft LoopbackAdapter – y procedemos a establecer este dispositivo, como el dispositivo de red del emulador de la siguiente forma. Para llevar a cabo esta tarea, ubicamos la pantalla del emulador ( donde se ve el teléfono) y seleccionamos File-Configure. En esta pantalla seleccionamos este adapter como dispositivo de red, tal y como se ve en la siguiente figura.

Y listo, con esta configuración, ya se debe de tener reconocido el dispositivo en el Windows Mobile Device Center y proceder a ejecutar la aplicación móvil desde Visual Studio.