Rafael del Corr...'s profile..:: Blog de Rafael del ...BlogLists Tools Help

Rafael Del Corro

Occupation
Location

Text Controls

We have three  type of “Text Controls” inside the WMC´s:  the LiteralText, Label and TextView control. Each one, has their functionalities. Some of them admit HTML labels, some can alternate their behaviors through server code, etc. This is what we are going to see in this article, in order according to their functionalities:

First of all we have the LiteralText. Though  is not a WMC, it is a class that inherits from MobileControl and represent all kind of text that we want to make visible to the user and we do not want to control from the server. This text allows to use some labels similar to HTML ones. For example, we can use:

-          Paragraph labels (<p></p>)

-          Font style labels (black and italic) (<b></b> and <i></i>)

-          Line feed labels (<br> or </br>)

-          Link labels (<a href=”url”></a>)

This labels will be processed according to the language that the device that make the request supports. And here we have an example of a literal text using all the supported labels:

<html xmlns="http://www.w3.org/1999/xhtml" >
<body>
   <
mobile:Form id="Form1" runat="server">
     
<p>
        
This a <b>test</b> to see that a <i>simple</i> text <br></br>
         could be reached using similar <a href="http://www.msn.com">HTML</a>
      </p>

   </mobile:Form>
</body>
</html>

The ASP.NET engine will render the page code according to the  device that make the request (HTML, WML, etc.).

In second place: the Label control. This is a WMC and it behavior could be modified from the server code side. This control, apart from the common properties has a new one: “Text”. This property allows us to change the text value of the label,  and could be modified in any time. In this type of controls you are not able to use HTML labels as in the case of the LiteralText control. There are two possibles sintax to set the text value of a label:

a)      Between the labels

   <mobile:Form id="Form1" runat="server">
      <mobile:Label ID="Label1" Runat="server">
         We are setting the text property value between the labels.
      </mobile:Label>
   </
mobile:Form>

b)      Modifying the Text property

   <mobile:Form id="Form1" runat="server">    
      <mobile:Label ID="Label2" Runat="server"
         Text="We are setting the text    through the Text property">
      </mobile:Label>        
   </mobile:Form>

Something to bear in mind is that a label can not be paginated. This is not the same for  our third text control: the TextView.

This controls has the common properties and it is added Text, that satisfies the same necessity that the case of a Label control. But if you are wondering what is the difference between the Labels and the TextView, the answer is that this control allows to, for example, bind data with a database. We should use this control, for all those texts that, storing it in a database requires a Memo or Text field type.

In this control, we can use the same HTML labels that we can use in the LiteralText, added to all the rest of the HTML labels (always respecting the type of labels permitted according with what we see in the second post of this blog). Apart from the modifications that this labels permit, we are able to use the common properties as any control (Font.Bold, Font.Italic, etc.)

An other very important feature of this control, as we said, is that it could be “paginated”. This is very useful in the case that we are navigating with a low memory capacity device and the text is too long for it to support it. In this case, we must “turn on” the property that allows the pagination (Paginate=”True”)

Here we have an example:

<mobile:Form id="Form1" runat="server">    
   <
mobile:TextView ID="TV1" Runat="server">
      This is a <b>looooong</b> text, that it could be paginated, wrapped, bolded or what ever we
      want to do according to the common and owned properties.
<br />
Excelent... is not it?
   </
mobile:TextView>
</mobile:Form>

Well, that´s it all for now. We are seeing in the next post with those controls that allows as to go and came back to the server, to another page, etc.: Image, Link and Command, their common properties, their owned properties and events, and how, mixing these we can get more functionalities.

See you!!

Containers

As I said in the previous post, we are going to see each control specifically. The first of all controls there will be those that make possible to contain other controls: the “Forms” and the “Panels”. If we are accustomed to work with ASP.NET Desktop WebSites (standards ASP.NET pages) we know that a page can only contain one form control.

And here there is a great advantage if we make it work properly: ASP.NET allows us to include more than one form in one page. If you bear in mind that a request from a mobile device it is expensive compare with a standard ASP.NET page request, the possibility of having two forms in one page, and being able to call one form at a time (writing “#” followed by the name of a form in a Link control in the Action property or through the ActiveForm property through the server code) will allow us to improve the quality (speed and cost) of our site.

An other advantage of this functionality is that the variables continue existing between a call of a form to an other, since ASP.NET does not keep the variables state between different pages (ASP.NET standard). The functions and methods developed for the page are available for all forms.

The problem with this functionality, is that if the page is plenty of forms, it will take more time to download it to the mobile device, and the page is reached by one URL, and this URL always point to the first form.

This functionality is inherited from WML that works with “cards” instead of forms, but in the same way, to explain it quickly.

There are some rules to work with the forms and the panels. They are:

-          A form can not contain another form.

-          A panel can not contain a form.

-          The panels are able to have one or more panels inside them.

-          A panel must exists inside a form, like any control.

The forms, apart from having the common WMC´s properties and events, has their own. For now, we are going to see:

Title
Set the title of the page. This make easily and more effectively the search for the seekers.

Paginate
Not all devices are prepared to receive an entire page due to it low memory capacity. To avoid this, ASP.NET automatically separates a form in several steps. By default this property is set as “False”, so if we are navigating in a low memory capacity device and appears a message like “Out of memory”, we know de reason why. About pagination, there are two more properties: CurrentPage (returns the page where “we” are visiting) and PageCount (quantity of pages that the forms was separated in)

Action
Set  an alternative URL to where the page could be redirectioned. By default this property is set as Null, so, it will do a postback to the same page.

ControlToPaginate
This property allows to specify a certain control, that want to be paginated. It must be defined de control´s ID, and by default is Null.

PagerStyle-NextPageText or PagerStyle-PreviousPageText
In the majority of the browsers appears two buttons that allows us to move forward or towards through the different pages that we visited. In case that a browser has not this controls, ASP.NET automatically includes it. So, this properties allows the developer to specify the text of this buttons.

PagerStyle-PageLabel
Sets or gets the text that indicates to what page the user may go, for example “Go to page {2} of {3}”. This is the way to specify. This property is not available in devices that only support WML.

PagerStyle-StyleReference
This property sets or gets the style that is used to render de pagination of the page, in case that “Paginate” is set as true of course. This property is not available in WML devices neither.

You can download an example from here.

In the other hand, continue talking about “containers” we must name the “Panels”. This controls has not a visual interface, and its principal function is to group controls so that the developer can assign a certain value to a common property between the controls contained in the panel.

Apart from having the common properties of the WMC´s, the panels has their own properties, and they are:

Paginate
It has a similar function to the form one. It allows to establish the panel as a non “step-divided” control (True or False). For example. If the property “Paginate” of the form that contains the panel is set as “True”, the ASP.NET engine will try to keep the controls inside the panel together, not to divide them in several steps or pages.

StyleReference
Allows to set a certain style for the panel.

In the example that you can download above you can see how a panel can contain other controls. Try creating other controls inside a panel, changing a common property between them, and you will see how it changes for all of them.

I hope that you find of your interest this article, and we are seeing in the next post, where I will continue talking about the ASP.NET Web Mobile Controls.

Good Luck!

WMC Common Events

There are certain events that all control has. Most of it are very similar to standard ASP. In the coming posts we will see properties and event of each control, for now I will describe the common events and it´s description.

To call a method when an event occurs we must follow the following syntax:

<mobile:Command ID="btnBoton" Runat="server" OnInit="Method1">
   Boton
</mobile:Command>

The name of the event must be preceded of the word “On”. It means, if we want to call a method when the Init event occurs we should write ‘OnInit=Method1’. The syntax to write a method is:

<script runat="server">
    void Method1(object sender, EventArgs e)
    {
        btnBoton.Text = "Boton cambiado";
    }
</script>

The method receives two parameters: the first, is the object from where we are getting the method, and in second place,  an EventArgs type that can be used by the developer by using different optional arguments for the event.

Now, as we said at the beginning  there common events between the WMC, and they are:

DataBinding
It occurs when the control is vinculated with a data source. This event ask to the server for the logical data that it is writed for him.

Disposed
When a control is no longer exists the last event that occurs is this. The control was disposed from memory.

Init
This event constitute the first stage when a control is initialized from the server.

Load
Occurs when the page is loaded.

UnLoad
This event occurs when the page in unloaded.

PreRender
This event occurs after the page is loaded, but before the page is rendered. This method can be used, for example, when you want to make a change in the ViewState property of any control, like this (try this example in a new website):

<html xmlns="http://www.w3.org/1999/xhtml" >
<body>
    <mobile:Form id="Form1" runat="server">
        <mobile:Command ID="btnBoton1" Runat="server" OnPreRender="Method1">
            Boton
        </mobile:Command>
    </mobile:Form>   

    <script runat="server">
        void Method1(object sender, EventArgs e)
        {
            btnBoton1.EnableViewState = false;
        }
    </script>
</body>
</html>

Well, today we talked about the common events of the WMC´s. In the followings posts we will see each control specifically, their properties, events and methods.

See you soon.

WMC Common Properties

After a long time of being absent due to study, I restart posting, and this time introducing WMC (Web Mobile Controls). In this case we will talk about their properties.

In the previous post I made an introduction that can be interpreted as explanation about the difference between the WMC and the Standard ASP Controls (if you did not read it I recommend you to do it so that you don´t miss important concepts that must have been understood)

So each control has their own properties and events, there are some that are common for all of them (the specific properties of the most important controls will be descript in the coming posts). Until now we have seen how to create a control, and what I want to show in this case are the common properties and their permitted values:

<mobile:Control id="idControl" Runat="server"

     Alignment=[Center|Right|Left|NotSet]

     BackColor=[Color de Fondo]

     BreakAfter=[True|False]

     EnableViewState=[True|False]

     Font-Bold=[True|False|NotSet]       

     Font-Italic=[True|False|NotSet]

     Font-Name=[Nombre de la fuente]

     Font-Size=[Large|Medium|Small|NotSet]

     ForeColor=[Color del Control]

     StyleReference=[Nombre del estilo que queremos asociar]

     Visible=[True|False]

     Wrapping=[Wrap|NoWrap|NotSet]>

</mobile:Control>

Alignment

Set the alignment of the control in relation with it container (may be a form or a panel). You can modify this property in design time or execution time.

BackColor

Set the background color of the control.

BreakAfter

Allows to define if after a control will be inserted a break (new line) or other control will be next to it. The property is seted as default as “True”.

EnableViewState

This property gets o sets a value that indicates if the view state of the control must remain after a request from the client. For example if you are getting data from a control in a server and this control does not need to be shown, setting this property in false you will improve the performance of your web page. The state view of a control it is and array of it properties and it is send after a request to the server. The property is seted as default as “True”.

Click here to download an example

Font-Bold, Font-Italic, Font-Name, Font-Size

This properties modifies the size, the style and the name of the font of certain control.

ForeColor

Through this property we can set or get de fore color of a control.

StyleRereference

This property associate a style with a control. The way of doing this is setting as value of this property the property Name of a Style.

Visible

Set or gets the visibility of a control. If it is false the control will not be shown.

Wrapping

The property can be set as “Wrap”, “NoWrap” or “NotSet. If you set it as “Wrap” the text will break automatically once it reachs the end of the page. In other way, if you set this property as “NoWrap” when the text reachs the end of the page, will appear an horizontal scroll bar. The default value is “NotSet”, and in this case the control´s size has not been seted.

Try copying the code below in a .NET mobile solution. It shows the difference between a wrapped text and a no wrapped text:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %>

<html>

  <body>

        <mobile:Form id="Form1" runat="server">

          <mobile:TextView ID="txtWrapped" Runat="server"

        Wrapping="Wrap"> WRAPPED TEXT. This is a loooong text, that do not can be displayed in a device that does not has a display big enough if you want to show it in one line due to the most of the devices´s displays sizes are 320 x 240

     </mobile:TextView>

           <mobile:TextView ID="txtNotWrapped" Runat="server"

Wrapping="NoWrap"><BR />NO WRAPPED TEXT. This is a loooong text, that can not be displayed in a device that does not has a display big enough if you want to show it in one line due to the most of the devices´s displays sizes are 320 x 240

     </mobile:TextView>

   </mobile:Form>

 </body>

</html>

Try changing the browser´s window size and you will see how the text automatically wrap to the page.

Well, that´s it till now. In the next post we will talk about the common events of the WMC.

Good Luck.

HTML Controls vs. WMC

Estamos acostumbrados quizá, a generar código para que luego se renderice basado en HTML, pero nos tenemos que acostumbrar a la idea que en ASP.NET MOBILE el código que se devuelve a un dispositivo luego de un request no está definido por el servidor, sino por el dispositivo.

En ASP.NET se podía codificar un control HTML y que corriera en el servidor con el simple hecho de agregarle dentro de las propiedades "runat=server", lo cual permitía acceder a las propiedades, métodos y eventos del control, pudiendo modificar así, por ejemplo, la propiedad "Text" de un Label.

En ASP.NET MOBILE, al no trabajar con un lenguaje de etiquetas fijo, no podemos anexar a nuestro código ningún control de tipo HTML o WML, sino que los únicos controles con los que podemos trabajar son los Web Mobile Controls (System.Web.UI.MobileControls).

El siguiente es un ejempo de como crear y alterar las propiedades de un Mobile Control:

<%

@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<%

@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %>

<

html xmlns="http://www.w3.org/1999/xhtml" >

  <

body>

    <

mobile:Form id="Form1" runat="server">

      <

mobile:Label ID="Label1"

        runat="server"

        Alignment

="Left"

        Font-Bold

="True"

        Visible

="True"

        Wrapping

="Wrap"

        Text

="El mundo de ASP.NET MOBILE..."

      />

    </mobile:Form>

  </body>

</html>

Este código tiene que funcionar perfectamente si uno lo copia en el "Markup View" en Visual Studio 2005. Hagan la prueba de colocar un control HTML, y van a comprobar que el motor de ASP.NET no lo procesa.

En el Compact Framework 2.0, se han agregado un par de nuevo controles (no son muchos) y ahora se puede modificiar la propiedad "BackColor" en la mayoría de ellos. A continuación, dejo una tabla con el Mobile Web Control y su correspondiente en ASP estándar:

 

ASP.NET
(asp:Nombre_Control)
ASP.NET MOBILE (mobile:Nombre_Control)
AdRotator AdRotator
BulletedList SelectionList
Button Command
Calendar Calendar
CheckBox SelectionList
CheckBoxList SelectionList
RangeValidator RangeValidator
CustomValidator CustomValidator
DataList List
DataGrid ObjectList
- DeviceSpecific
DropDownList SelectionList
Hyperlink Link
Image Image / DynamicImage
ImageButton Command
LinkButton Command
Label Label
ListBox SelectionList
Panel Panel
- Phone Call
RadioButton SelectionList
RadioButtonList SelectionList
RangeValidator RangeValidator
RegularExpressionValidator RegularExpressionValidator
RequireExpressionValidator RequireExpressionValidator
Repeater

Repeater

Table -
TextBox TextBox
- TextView
ValidationSummary ValidationSummary

 

Como pueden ver, hay casos en que los controles son los mismos, y basta con cambiar alguna o algunas propiedades para obtener un WMC que reemplace a un ASP Control (es el caso de un SelectionList o un Command). Por otra parte, también tenemos controles que no existen en ASP.NET (como ser PhoneCall, DeviceSpecific,TextView).

Hay controles de ASP.NET 2.0 que no aparecen en la lista, pero que a medida que pueda subirlos junto con su respectivo WMC, lo ire haciendo porque quizá hay controles en ASP.NET que no tienen su correspondiente en ASP.NET MOBILE, pero que se pueden conseguir, como ya vimos que pasa con el SelectionList, tan solo cambiando algunas propiedades, asíque cuando tenga nuevas soluciones, las postearé.

Hasta la próxima.

Primero pasos con ASP.NET MOBILE

"Distintos dispositivos, distintas plataformas, distintos soportes, distintos lenguajes..."

Es grande... la cantidad de dispositivos que hoy nos ofrece el mercado, sumado a la cantidad de dispositivos que ya ofreció y que están circulando como para pensar que se puede desarrollar un sitio web en un solo lenguaje (elegiríamos el que tenga mayores prestaciones), dejando de lado a todos aquellos que tengan dispositivos con un soporte más limitado. Es el ejemplo de la PocketPC con HTML (HyperText Markup Languaje) en relación con los celulares que soportan WML (Wireless Markup Languaje), cHTML (Compact Hyper Text Markup Languaje), iHTML (para dispositivo que soportan i-mode), entre otros.

Esta es una de las ventajas de ASP.NET para desarrollo de aplicaciones web móviles. El lenguaje con el cual codifica la página que envía, varía de acuerdo a las características del equipo que la solicita. El procedimiento consiste básicamente en los siguientes pasos:

  1. Una vez enviada la solicitud (HttpRequest), lo primero que hace el server es identificar las características del dispositivo (Device Capabilities), como por ejemplo browser y lenguaje soportado.
  2. El MMIT (Microsoft Mobile Internet Toolkit) guarda esta información que recibe a partir del HttpRequest realizado por el dispositivo, en el archivo "Machine.Config" y contiene los siguientes valores:

    - URL: dirección solicitada.

    - User Agent: el navegador.

    - Header Information: los encabezados.

  3. Una vez localizada la página (a través del parámetro URL enviado en el HttpRequest), la primera vez que es solicitada, la página con extensión aspx. atraviesa el siguiente proceso:

    a) Se envía al parser, que funciona de la siguiente manera: éste recibe una serie de sentencias (en este caso el código que proviene de una página aspx), que de acuerdo a su gramática puede identificar la estructura y las propiedades de los datos que se envían.

    b) La página es enviada al compilador, donde se genera el assembly de la página.

    c) Se almacena el assembly generado en el "Assembly Cache".

    d) El servidor crea una nueva instancia de la página emsamblada que la usará luego para procesar el pedido del HttpRequest enviado por el dispositivo.

    e) Una vez que la página .aspx está instanciada, los Mobile Web Controls (luego haremos una aclaración respecto a la diferencia entre los controles HTML y los Mobile Web Controls) son instanciados también, y la Bussines Logic es ejecutada. Vale la pena destacar, que al existir la posibilidad que dentro de un proyecto tipo "Desktop Asp.NET WebSite" podemos incluir páginas .aspx para dispositivos móviles, podemos utilizar la misma lógica de negocios en uno que en otro (por ejemplo, el caso que querramos hacer una misma página que pueda ser visualizada en una PC de escritorio o en una PocketPC o SmartPhone).

    d) Se genera el lenguaje correspondiente en base a las características del dispositivo, que luego se encapsula en un HttpResponse y es enviado al dispositivo que realizo el HttpRequest.

    En caso que la página ya esté instanciada, los pasos de a) hasta d) se saltean. Esto por supuesto que se va a ver reflejado en una mejor performance del sitio.

  4. Finalmente, la página se renderiza en el dispositivo.

En un dispositvo que no soporte el protocolo HTTP, y que soporte WAP (Wireless Application Protocol), el proceso es idéntico, sólo que entre el server y el dispositivo interviene un Gateway para codec de HTTP A WAP y viceverza.

Bueno, para dar los primeros pasos con asp.net mobile creo que hemos tomado el camino correcto. Han visto una excelente caraceterística de asp.net mobile: la posibilidad de desligarle al desarrollador la tarea de tener que identificar con que lenguaje se debe trabajar, que por supuesto se puede hacer manualmente (conociendo el tipo MIME que representa a cada uno de los formatos que el dispositivo permite (tipo_de_formato/formato_especifico), a través del método "AcceptTypes" de la instanciación de la clase System.Web.HttpRequest, que devuelve un vector de cadenas con los tipos aceptados por el dispositivo).

 

Ésto ha sido todo por ahora, hasta la próxima.