Translate

domingo, 5 de febrero de 2017

Android key concepts

What is an activity?
An activity is responsible for managing user interaction with a screen of information.
What is a layout file?
A layout defines a set of user interface objects and their position on the screen. A layout is made up of definitions written in XML. Each definition is used to create an object that appears on screen, like a button or some text.
Min sdk
The minimum API Level required for the application to run. The Android system will prevent the user from installing the application if the system's API Level is lower than the value specified in this attribute.
Target sdk version
This attribute informs the system that you have tested against the target version and the system should not enable any compatibility behaviors to maintain your app's forward-compatibility with the target version. The application is still able to run on older versions (down to minSdkVersion).
Max sdk version
An integer designating the maximum API Leven however due to the backwards compatibility is not recomended to declare this attribute.

Resources in Android
You should always externalize application resources such as images and strings from your code, so that you can maintain them independently. You should also provide alternative resources for specific device configurations, by grouping them in specially-named resource directories. At runtime, Android uses the appropriate resource based on the current configuration.

Resource directory
In the /res folder you can have:

  • anim/ - XML files that define tween animations
  • color/ - XML files that define a state list of colors.
  • drawable/ - Bitmap files / Nine-Patches (re-sizable bitmaps) / State lists / Shapes / Animation drawables / Other drawables
  • layout/ - XML files that define a user interface layout.
  • menu/ - XML files that define application menus, such as an Options Menu, Context Menu, or Sub Menu.
  • raw/ - Arbitrary files to save in their raw form.
  • values/ - XML files that contain simple values, such as strings, integers, and colors.
    • arrays.xml for resource arrays (typed arrays).
    • colors.xml for color values
    • dimens.xml for dimension values.
    • strings.xml for string values.
    • styles.xml for styles.
  • xml/ - Arbitrary XML files
Caution in Resources Folder
Never save resource files directly inside the res/ directory—it will cause a compiler error
Files in assets/ are not given a resource ID, so you can read them only using AssetManager.

Assets VS Resources
With resources, there's built-in support for providing alternatives for different languages, OS versions, screen orientations, etc., as described here. None of that is available with assets.

Activity LifeCycle




MethodDescriptionKillable?Next
onCreate()Called when the activity is first created. This is where you should do all of your normal static set up: create views, bind data to lists, etc. This method also provides you with a Bundle containing the activity's previously frozen state, if there was one.Always followed by onStart().NoonStart()
    onRestart()Called after your activity has been stopped, prior to it being started again.Always followed by onStart()NoonStart()
onStart()Called when the activity is becoming visible to the user.Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.NoonResume()or onStop()
    onResume()Called when the activity will start interacting with the user. At this point your activity is at the top of the activity stack, with user input going to it.Always followed by onPause().NoonPause()
onPause()Called when the system is about to start resuming a previous activity. This is typically used to commit unsaved changes to persistent data, stop animations and other things that may be consuming CPU, etc. Implementations of this method must be very quick because the next activity will not be resumed until this method returns.Followed by either onResume() if the activity returns back to the front, or onStop() if it becomes invisible to the user.Pre-HONEYCOMBonResume()or
onStop()
onStop()Called when the activity is no longer visible to the user, because another activity has been resumed and is covering this one. This may happen either because a new activity is being started, an existing one is being brought in front of this one, or this one is being destroyed.Followed by either onRestart() if this activity is coming back to interact with the user, or onDestroy() if this activity is going away.YesonRestart()or
onDestroy()
onDestroy()The final call you receive before your activity is destroyed. This can happen either because the activity is finishing (someone called finish() on it, or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing() method.Yesnothing


Fragments

miércoles, 30 de septiembre de 2015

Tutorial Android Azure Mobile Services

Windows Azure Mobile Services (AMS) a la vez como Amazon Services o Google App Engine es una plataforma en la nube que nos permite tener un gran numero de servicios. Uno de estos servicios es llamado Windows Azure Mobile Services que os funciona como backend de nuestra aplicación móvil.

Cuando los usuarios descargan la aplicación los usuarios finales realmente no les interesa cual es el backend de la aplicación si no que la aplicación funcione adecuadamente, AMS nos quita parte de la carga para la generación de ese toda la lógica que se ejecuta en el servidor.

Una de las grandes ventajas es que nos permite tener una gran facilidad para escalar nuestra aplicación así como personalización de la lógica del servidor y monitoreo de nuestros servicios.

Para iniciar vamos a ingresar al sitio para inscribirnos en la prueba de Windows Azure Services:





Creando un nuevo servicio móvil.
  1. Para la creación tenemos que entrar a el portal de administración.

Seleccionamos nuestra cuenta.
Al entrar por primera vez vamos a tener un pequeño paseo que nos explica como generar los recursos disponibles en nuestra consola de administración.


Vamos a ir a la parte baja de la pantalla de navegacion y hacemos click en +Nuevo. Se va a expandir la sección de Proceso -> Serivicio Mòvil -> Crear.



2. Ahora vamos a poder ver el dialogo para la creación de un servicio móvil. Llenamos la dirección URL, Seleccionamos crear una base de datos SQL de 20 MB gratuita, region dejaremos Oeste de EE. UU. Y como Back-end seleccionamos JavaScript.


3. En el nombre de la base de datos vamos a seleccionar el nombre de nuestra nueva base de datos, en servidor seleccionamos nuevo servidor de base de datos sql, nombre de inicio de sesión es el nombre de administrador de la base de datos, escribimos la contraseña y confirmamos la contraseña.


Vamos a ver como se inicia la generación de nuestro servicio.


Al finalizar veremos una imagen como la siguiente:


Creando una nueva aplicación Android.

Una vez que tenemos nuestro servicio móvil, tenemos una seria de pasos que nos permiten generar de forma sencilla crear una nueva aplicación o modificar una existente para conectarla con nuestro servicio móvil.


  1. Vamos a seleccionar nuestro servicio móvil.



2. Como podemos ver tenemos varias opciones para la generación de nuestra aplicación móvil.



  1. Vamos a seleccionar Android -> Crear una aplicación Android. Nos va a mostrar las opciones para la generación de nuestra aplicación.


  1. En mi caso ya tengo las herramientas instaladas, en caso de contar con ellas las pueden descargar en: http://developer.android.com/sdk/index.html

  1. Vamos a seleccionar crear la tabla TodoItem donde se van a almacenar nuestros datos. Se va genera la tabla por nosotros.
  2. Ahora vamos a descargar la aplicación.
    • Una vez que tengamos los archivos que se descargan compresos en formato zip, vamos a descomprimir e importar el proyecto en Android Studio.

Ejecutar tu aplicación Android.

  1. Vamos a navegar a la ruta donde se encuentran los archivos descargados desde nuestro servicio móvil.
  2. Abrimos Android Studio seleccionamos abrir un proyecto existente, navegamos a la ruta donde se extrajeron los archivos y seleccionamos OK.

Ruta del proyecto.


Una vez abierto el proyecto vamos a abrir la clase ToDoActivity:


Vamos a ver en el método onCreate se encuentra la generación e invocación hacia nuestro servicio móvil. (en algunos casos se tiene que actualizar para mi caso no era necesario).


En nuestro servicio en la tabla de TodoItem vamos a encontrar los elementos almacenados.


Eso es todo para este tutorial.
Saludos.
Roque.

domingo, 1 de diciembre de 2013

Creando un sitio web ASP .Net. Parte 5

Para continuar con la creación de nuestro sitio web vamos a crear una conexión con la base de datos la cual nos va a permitir obtener información de la base que creamos.
Crear un usuario en la base de datos

-- Create user for SQL Authentication
CREATE LOGIN clothesUsr WITH PASSWORD = 'HolaMundo'
,DEFAULT_DATABASE = LuisClothes
GO
-- Add User to first database
USE LuisClothes;
CREATE USER clothesUsr FOR LOGIN clothesUsr;
EXEC sp_addrolemember 'db_datareader', 'clothesUsr'
EXEC sp_addrolemember 'db_datawriter', 'clothesUsr'
GO
Crear un rol para ejecución de procedimientos almacenados.
-- 1 - db_executestoredprocedures
-- 1a - Create role
CREATE ROLE db_produccion
GO
Una vez que terminemos la creación de nuestros procedimientos y funciones almacenadas ejecutaremos las siguientes sentencias.
-- 1b - Grant permissions
GRANT EXECUTE TO db_produccion
GO

También vamos a crear el rol para la selección de funciones.
-- 2 - db_selecttablevaluedfunctions
-- 2a - Create role
CREATE ROLE db_select_funtions
GO
Para dar permisos de seleccion a nuestras funciones se ejecutara el siguiente script una vez que terminemos la creacion de las funciones.
-- 2 - Create permissions
DECLARE @Function_Name nvarchar(250);
DECLARE @CMDEXEC1 nvarchar(2000);
DECLARE db_cursor CURSOR FOR 
SELECT [name]
FROM sys.objects
WHERE Type = 'TF'
OPEN db_cursor  
FETCH NEXT FROM db_cursor INTO @Function_Name
WHILE @@FETCH_STATUS = 0  
BEGIN
  
 SET @CMDEXEC1 = 'GRANT SELECT ON [' + @Function_Name + '] TO db_select_funtions;'
 --- SELECT @CMDEXEC1
 EXEC(@CMDEXEC1)
 FETCH NEXT FROM db_cursor INTO @Function_Name
END
CLOSE db_cursor  
DEALLOCATE db_cursor
GO

Ahora vamos a crear algunos procedimientos almacenados como por ejemplo la creación de un producto. Para esto en nuestro Object Explorer vamos a dar clic derecho en stored procedures.



Con lo que nos a generar una plantilla para nuestro procedimiento almacenado.
-- ================================================
-- Template generated from Template Explorer using:
-- Create Procedure (New Menu).SQL
--
-- Use the Specify Values for Template Parameters
-- command (Ctrl-Shift-M) to fill in the parameter
-- values below.
--
-- This block of comments will not be included in
-- the definition of the procedure.
-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:        <Author,,Name>
-- Create date: <Create Date,,>
-- Description:   <Description,,>
-- =============================================
CREATE PROCEDURE <Procedure_Name, sysname, ProcedureName>
      -- Add the parameters for the stored procedure here
      <@Param1, sysname, @p1> <Datatype_For_Param1, , int> = <Default_Value_For_Param1, , 0>,
      <@Param2, sysname, @p2> <Datatype_For_Param2, , int> = <Default_Value_For_Param2, , 0>
AS
BEGIN
      -- SET NOCOUNT ON added to prevent extra result sets from
      -- interfering with SELECT statements.
      SET NOCOUNT ON;

    -- Insert statements for procedure here
      SELECT <@Param1, sysname, @p1>, <@Param2, sysname, @p2>
END
GO

Ahora solo tenemos que dar la definición de nuestro procedimiento.
-- ================================================
-- Project Luis Clothes.
-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:        Roque Rueda.

-- Create date: 24/11/2013

-- Description:   Creates a new product record in
--              the database. If you need to inser
--                      a new row you should give a -1
--                      product id(this is the default value)
-- =============================================
CREATE PROCEDURE Insert_Product (
      -- stored procedure params
      @product_id             int = -1,
      @product_name           nvarchar(150),
      @product_price          decimal(10, 2) = 1,
      @product_photo          nvarchar(2083),
      @product_type           int
      )
AS
BEGIN
      -- SET NOCOUNT ON added to prevent extra result sets from
      -- interfering with SELECT statements.
      SET NOCOUNT ON;
     
      -- Update information or insert if not exists
      UPDATE Product SET Name = @product_name,
                                Price = @product_price,
                                Photo = @product_photo,
                                IdType = @product_type
      WHERE Id = @product_id;
      IF @@ROWCOUNT = 0 -- Check if the row was updated.
      INSERT INTO Product (Name,
                                    Price,
                                    Photo,
                                    IdType,
                                    CreationDate)
      VALUES (@product_name, -- Name
                  @product_price, -- Price
                  @product_photo, -- Photo
                  @product_type, -- Typeid from ProductType
                  GETDATE()); -- Gets the current date
                 
      -- Reset SET NONCOUNT
      SET NOCOUNT OFF;

END

GO




Por que hacer store procedure para hacer los llamados a base de datos. Supongamos que por algún motivo necesitamos saber qué fecha fue modificado un producto. Por desgracia la tabla ya fue creada y nuestro programa ya está utilizando. Algo como lo siguiente:

            string connectionString = "connection Settings";
            using (var conn = new SqlConnection(connectionString))
            using (var command = new SqlCommand("InsertProduct", conn)
            {
                CommandType = System.Data.CommandType.StoredProcedure
            })
            {
                conn.Open();
                command.Parameters.AddWithValue("@product_id", 1);
                ...
                command.Parameters.AddWithValue("@@product_type", 1);
                command.ExecuteNonQuery();
                conn.Close();
            }

Para nuestra aplicación que está usando el procedimiento almacenado lo que se debe hacer es nada... así es ya que solo se proporciona el nombre y parámetros mientras la interfaz y el numero de parámetros se mantengan igual no hay necesidad de cambiar.

-- Roque Rueda add a column to know when the produc
-- was modified.

ALTER TABLE Product
ADD LastModified DATETIME

Si se agrega la columna lo único que debemos realizar es agregar las sentencias necesarias en nuestro store procedure.
-- ================================================
-- Project Luis Clothes.
-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:        Roque Rueda.

-- Create date: 24/11/2013

-- Description:   Creates a new product record in
--              the database. If you need to inser
--                      a new row you should give a -1
--                      product id(this is the default value)
-- =============================================
ALTER PROCEDURE InsertProduct (
      -- stored procedure params
      @product_id             int = -1,
      @product_name           nvarchar(150),
      @product_price          decimal(10, 2) = 1,
      @product_photo          nvarchar(2083),
      @product_type           int
      )
AS
BEGIN
      -- SET NOCOUNT ON added to prevent extra result sets from
      -- interfering with SELECT statements.
      SET NOCOUNT ON;
     
      -- Update information or insert if not exists
      UPDATE Product SET Name = @product_name,
                                Price = @product_price,
                                Photo = @product_photo,
                                IdType = @product_type,
                                LastModified = GETDATE()
      WHERE Id = @product_id;
      IF @@ROWCOUNT = 0 -- Check if the row was updated.
      INSERT INTO Product (Name,
                                    Price,
                                    Photo,
                                    IdType,
                                    CreationDate)
      VALUES (@product_name, -- Name
                  @product_price, -- Price
                  @product_photo, -- Photo
                  @product_type, -- Typeid from ProductType
                  GETDATE()); -- Gets the current date
                 
      -- Reset SET NONCOUNT
      SET NOCOUNT OFF;

END
GO

Si se dan cuenta no se afectaría en ningún momento el código de la aplicación. Es por eso que en este proyecto vamos a seguir este modelo, aunque en algunos casos no utilicemos un store procedure, tratare de explicarle el por qué no de uso.