tag:blogger.com,1999:blog-41089382368844913162024-03-04T23:25:39.000-08:00Ricardo RomoDesarrollador de Software C# (Xamarin & .NET).Rickyhttp://www.blogger.com/profile/08848939336739916405noreply@blogger.comBlogger4125tag:blogger.com,1999:blog-4108938236884491316.post-78247762670759310372014-09-01T14:50:00.000-07:002014-09-01T15:14:22.796-07:00Simple SearchView con Xamarin.AndroidHola buen día,<br />
<br />
El día de hoy les traigo un ejemplo de como crear un SearchView para buscar items dentro de un ListView.<br />
<br />
Primero vamos a crear una nuevo proyecto del tipo "Android Application".<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjpM5UPGEaDMJu2SoQl_V_3giewnz9Q8xti7EFmGgOVdBIbftQHGjqfcOjhioc1jsqInaJ80BLvc5Y8A4u1MY8R4Pocukum0mdOSvD2wY4zjFiCFU7L4rvdnEOntmxKSR6WARzSKvaHTFxt/s1600/-1.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjpM5UPGEaDMJu2SoQl_V_3giewnz9Q8xti7EFmGgOVdBIbftQHGjqfcOjhioc1jsqInaJ80BLvc5Y8A4u1MY8R4Pocukum0mdOSvD2wY4zjFiCFU7L4rvdnEOntmxKSR6WARzSKvaHTFxt/s1600/-1.png" height="390" width="640" /></a></div>
<br />
Despues de crear nuestro proyecto vamos a la carpeta de componentes donde añadiremos el componente de "Android Support Library v7 AppCompat"<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiY-1By8DzPnrr097MSeunK6-1lNLw8JuNCe-t2gatD66vv9HTFHgWedQIKC4SZuylKxvMNRQVuG-kfRQQsyDEAl3vvJJ1QXxKjiXyI1QjZsYlnT6q7MGVP8KKwYwUk8q1dHvvoVlpbMB2x/s1600/1.ong.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiY-1By8DzPnrr097MSeunK6-1lNLw8JuNCe-t2gatD66vv9HTFHgWedQIKC4SZuylKxvMNRQVuG-kfRQQsyDEAl3vvJJ1QXxKjiXyI1QjZsYlnT6q7MGVP8KKwYwUk8q1dHvvoVlpbMB2x/s1600/1.ong.png" height="104" width="640" /></a></div>
Ahora vamos a comenzar una carpeta llamada Menu dentro de la carpeta Resources, y dentro de la carpeta Menu creamos un archivo llamado main.xml con el siguiente codigo.
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh9oVguUykCiBP79hLZd9p3lOcIXegCb-pVHLFc1_FGuIqEEe5OwLuog0_zmd9Fdj9sFqCw-5YtTLApxsKyP975n-xcS_2-LdPtEn0wzWHTWjX4487cXzAtPfUNp3807i2P-7tuuRxUVzA7/s1600/2.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh9oVguUykCiBP79hLZd9p3lOcIXegCb-pVHLFc1_FGuIqEEe5OwLuog0_zmd9Fdj9sFqCw-5YtTLApxsKyP975n-xcS_2-LdPtEn0wzWHTWjX4487cXzAtPfUNp3807i2P-7tuuRxUVzA7/s1600/2.png" /></a></div>
<br />
<pre class="brush: csharp"><menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:icon="@android:drawable/ic_menu_search" android:id="@+id/action_search" android:title="Search" app:actionviewclass="android.support.v7.widget.SearchView" app:showasaction="always|collapseActionView">
</item>
</menu>
</pre>
Ahora vamos con nuestro layout principal que es el que muestra nuestro Search Bar y el ListView con los items donde realizaremos la busqueda.<br />
<pre class="brush: csharp"><linearlayout android:layout_height="fill_parent" android:layout_width="fill_parent" android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android">
<listview android:id="@+id/listView" android:layout_height="fill_parent" android:layout_width="fill_parent">
</listview></linearlayout>
</pre>
Después vamos a nuestro MainActivity.cs, primero cambiamos el tipo de la clase de "Activity" a "ActionBarActivity".<br />
<pre class="brush: csharp">using Android.App;
using Android.Runtime;
using Android.Support.V4.View;
using Android.Support.V7.App;
using Android.Support.V7.Widget;
using Android.Views;
using Android.OS;
using Android.Widget;
namespace SearchBar
{
[Activity(Label = "SearchView Ejemplo", MainLauncher = true, Icon = "@drawable/icon",
Theme = "@style/Theme.AppCompat.Light")]
public class SearchViewActivity : ActionBarActivity
{
private Android.Support.V7.Widget.SearchView _searchView;
private ListView _listView;
private ArrayAdapter _adapter;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
var Names = new[]
{
"Ricardo Romo Gonzalez","Alejandro Ruiz Varela","Christian Salvador Arenas",
"Armando Balleza","Jorge Vazquez","Enrique Torres","Angel Alberto Mejia","Juan Manuel Perez",
"Ruben Perez","Pedro Navajas","Jose Alfredo Jimenez","Antonio Aguilar"
};
_listView = FindViewById<listview>(Resource.Id.listView);
_adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, Names);
_listView.Adapter = _adapter;
}
public override bool OnCreateOptionsMenu(IMenu menu)
{
MenuInflater.Inflate(Resource.Menu.main, menu);
var item = menu.FindItem(Resource.Id.action_search);
MenuItemCompat.SetOnActionExpandListener(item, new SearchViewExpandListener(_adapter));
var searchItem = MenuItemCompat.GetActionView(item);
_searchView = searchItem.JavaCast<android .support.v7.widget.searchview="">();
_searchView.QueryTextChange += (s, e) => _adapter.Filter.InvokeFilter(e.NewText);
_searchView.QueryTextSubmit += (s, e) =>
{
//TODO: Do something fancy when search button on keyboard is pressed
Toast.MakeText(this, "Searched for: " + e.Query, ToastLength.Short).Show();
e.Handled = true;
};
return true;
}
}
}</pre>
Creamos una nueva clase llamada "SearchViewExpandListener" implementado "IOnActionExpandListener" para poder expandir o contrar cuando se realiza una busqueda.
<br />
<br />
<pre class="brush: csharp">using System;
using Android.Support.V4.View;
using Android.Widget;
using Android.Views;
namespace SearchBar
{
public class SearchViewExpandListener
: Java.Lang.Object, MenuItemCompat.IOnActionExpandListener
{
private readonly IFilterable _adapter;
public SearchViewExpandListener(IFilterable adapter)
{
_adapter = adapter;
}
public bool OnMenuItemActionCollapse(IMenuItem item)
{
_adapter.Filter.InvokeFilter("");
return true;
}
public bool OnMenuItemActionExpand(IMenuItem item)
{
return true;
}
}
}
</pre>
Después de realizar los pasos anteriores corremos nuestro proyecto y deber aparecer como a continuación.
<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgHlaMHnGLYAszSiofI5tRQsVTnQHqef3QzfeddHU9zZcr19UHxziJpDyMtEUV-F0_kOG8DzZPNW78AtTkPb_di-XAbVo-cPQbIlwlIDlNS9kOE2rf8vMpGRSsQPHf-0jvXdSx3ozCuqpFU/s1600/3.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"></a><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhok-DDnP74nvJfhhQGFIDns5zriQFyyGQnm933Yy533toi0OBN79gbqy4CVpQD5Z6RnSARJ2kZSPbDPXwFO3NJngsffGF6X09fpr8Cjprj_0tOa-tufeAWM_gAvepKZFWHp_ouDNQwB_2Z/s1600/5.png" imageanchor="1" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhok-DDnP74nvJfhhQGFIDns5zriQFyyGQnm933Yy533toi0OBN79gbqy4CVpQD5Z6RnSARJ2kZSPbDPXwFO3NJngsffGF6X09fpr8Cjprj_0tOa-tufeAWM_gAvepKZFWHp_ouDNQwB_2Z/s1600/5.png" height="320" width="215" /></a><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgHlaMHnGLYAszSiofI5tRQsVTnQHqef3QzfeddHU9zZcr19UHxziJpDyMtEUV-F0_kOG8DzZPNW78AtTkPb_di-XAbVo-cPQbIlwlIDlNS9kOE2rf8vMpGRSsQPHf-0jvXdSx3ozCuqpFU/s1600/3.png" height="320" width="210" /></div>
<br />
<br />
<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgavZLKUWxeJe92YDnSp4VrfmVIo_KoUQ18JWUpuNDN6uyccGQZMDbG4xf9rut1O5EKPNY-kL7pLC3e7mN8yBhEEroM1fysUC6xsP5J0_kLUjl1qlBO0WeWVg4gH1r92AOKBBvLtmSLQrSB/s1600/4.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgavZLKUWxeJe92YDnSp4VrfmVIo_KoUQ18JWUpuNDN6uyccGQZMDbG4xf9rut1O5EKPNY-kL7pLC3e7mN8yBhEEroM1fysUC6xsP5J0_kLUjl1qlBO0WeWVg4gH1r92AOKBBvLtmSLQrSB/s1600/4.png" height="320" width="211" /></a></div>
<br />
Esto fue un pequeño ejemplo de como utilizar el SearchView en Xamarin.Android espero que le ayude cualquier cosa deja un comentario.<br />
<br />
Gracias.
<br />
Puedes descargar el proyecto desde mi github :<a href="https://github.com/ricky3c/SearchBar">SearchBar</a>Rickyhttp://www.blogger.com/profile/08848939336739916405noreply@blogger.com0tag:blogger.com,1999:blog-4108938236884491316.post-25194377484445128772014-04-03T16:21:00.001-07:002014-04-03T17:39:08.753-07:00Consumir Rest Service con RestSharp y Xamarin.AndroidEl día de hoy les traigo un pequeño ejemplo de como consumir un Rest Service desde una aplicación Android creada en Xamarin Studio y utilizando el componente RestSharp para consumir los servicios de una manera mas sencilla.<br />
<br />
Comenzamos creando un nuevo proyecto<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhN7bILTwWiCpUWV5O2aW8XCFOysWuFGDpRPoxngp3P1kdaqALwj3Hrho_IMd8DbX-5F0Wku2t5dSIZW24ngHvaybin4v9DcZjg4m0tCnqRK-dZE5GyPOUTt3Hq1vT9RMSFW_3M4fCA7dkD/s1600/2.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhN7bILTwWiCpUWV5O2aW8XCFOysWuFGDpRPoxngp3P1kdaqALwj3Hrho_IMd8DbX-5F0Wku2t5dSIZW24ngHvaybin4v9DcZjg4m0tCnqRK-dZE5GyPOUTt3Hq1vT9RMSFW_3M4fCA7dkD/s1600/2.png" height="392" width="640" /></a></div>
<br />
Luego vamos a crear un Activity por cada metodo que vamos a utilizar en nuestro caso solo utilizaremos<br />
los metodos de GET,POST,DELETE.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhGbtzqb9hvmCF0bN-p12a99LBTWyi_gKMg2HizPsS3lpCUgbSZSioObdHFH3MetqMp38SK58Zpzb6aHuK-HQMQ9EZl4hztfj7DOWTj-cAyp0sCLRufpgZwQci4-SJCiizs3MDT4z-RkeVf/s1600/3.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhGbtzqb9hvmCF0bN-p12a99LBTWyi_gKMg2HizPsS3lpCUgbSZSioObdHFH3MetqMp38SK58Zpzb6aHuK-HQMQ9EZl4hztfj7DOWTj-cAyp0sCLRufpgZwQci4-SJCiizs3MDT4z-RkeVf/s1600/3.png" height="244" width="320" /></a></div>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi4EU8zPVhUnIhclXhPSPMkO3Dt2Q7DqoPLNcsHL8_25P4e2XV_JUPBcR1BRRkLrybP5gAIPhSctUwZcFZ9Q9POWayfksDItM9Nsj5YD59WsLDLDR3nOQ_bmF7K4b7i6BwmEBCPgk1hhtGV/s1600/4.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi4EU8zPVhUnIhclXhPSPMkO3Dt2Q7DqoPLNcsHL8_25P4e2XV_JUPBcR1BRRkLrybP5gAIPhSctUwZcFZ9Q9POWayfksDItM9Nsj5YD59WsLDLDR3nOQ_bmF7K4b7i6BwmEBCPgk1hhtGV/s1600/4.png" height="175" width="200" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
</div>
<a name='more'></a><br />
<br />
<div class="separator" style="clear: both; text-align: left;">
Ahora creamos un layout por cada metodo para asi mostrar cada metodo en Tabs.</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjt1E4H7ENHmk0iHCnYpRr03RtBl-GLQvZeEMTTIpHykVkdTLZ4bXGhlREeJGTl4XYDzHnFajwO09dXhB61GYiQ0ihlXi8JSp2Vfj6pnry1S_3M5k3wJUzZm6fqMR5dLja6f0FL09x-CVmL/s1600/5.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjt1E4H7ENHmk0iHCnYpRr03RtBl-GLQvZeEMTTIpHykVkdTLZ4bXGhlREeJGTl4XYDzHnFajwO09dXhB61GYiQ0ihlXi8JSp2Vfj6pnry1S_3M5k3wJUzZm6fqMR5dLja6f0FL09x-CVmL/s1600/5.png" height="320" width="215" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
Comenzamos añadiendo el componente de RestSharp, vamos a la carpeta de Components y descargamos el componente y lo agregamos a nuestro proyecto.</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjoZZkWyBjEE8Xx0jE3vOKAiHugFwMjfQghzldnuIeFgnQg7eg0DNKolMKEOuffboQeeisW6H4NaHEIn_oAdufZuTVAHr6I_TVFfzPedtcdbGvPunfKVs_Iwq-4STEXugUFSUt3kUM6QPI0/s1600/1.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjoZZkWyBjEE8Xx0jE3vOKAiHugFwMjfQghzldnuIeFgnQg7eg0DNKolMKEOuffboQeeisW6H4NaHEIn_oAdufZuTVAHr6I_TVFfzPedtcdbGvPunfKVs_Iwq-4STEXugUFSUt3kUM6QPI0/s1600/1.png" height="408" width="640" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
Ahora si vamos comenzar con el codigo y empezamamos con el codigo del MainActivity.cs donde solo vamos a crear las tabs para cada metodo que vamos a utilizar.</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<pre class="brush: csharp">//LIBRERIAS
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using System.Net.Http;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Net;
using Newtonsoft.Json;
using System.Json;
using System.IO;
//Hacemos referencia RestSharp
using RestSharp;
namespace Aplicacion1
{
[Activity (Label = "Aplicacion1", MainLauncher = true)]
//Cambiamos Activity por TabActivity para crear nuestras Tabs
public class MainActivity : TabActivity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
//Mandamo llamar a nuestro metodo que crea las tabs y pasamos los parametros
CreateTab(typeof(GET), "Metodo Get", "Metodo Get", Resource.Drawable.Icon);
CreateTab(typeof(POST), "Metodo Post", "Metodo Post", Resource.Drawable.Icon);
CreateTab(typeof(DELETE), "Metodo Delete", "Metodo Delete", Resource.Drawable.Icon);
}
//Este metodo es el que nos crea las tabs
private void CreateTab(Type activityType, string tag, string label, int drawableId )
{
var intent = new Intent(this, activityType);
intent.AddFlags(ActivityFlags.NewTask);
var spec = TabHost.NewTabSpec(tag);
var drawableIcon = Resources.GetDrawable(drawableId);
spec.SetIndicator(label, drawableIcon);
spec.SetContent(intent);
TabHost.AddTab(spec);
}
}
//Entidad de los datos que vamos a usar.
public class Datos_Usuarios
{
public int Id_Persona { get; set; }
public string Nombre { get; set; }
public string Paterno { get; set; }
public string Materno { get; set; }
public string Telefono { get; set; }
public string Email { get; set; }
public string Direccion { get; set; }
public double Edad { get; set; }
}
}
</pre>
Ahora vamos al Metodo GET donde vamos a obtener todos los datos que nos va a regresar nuestro servicio desde una base de datos.
<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj0OcAnXt06Xw31-DGnkalrE88qcr2w1mrmkhS768NuKTJcWfTjgKpYxTh3x5KMS004TodnhXvZQjEcmKpuaLF3g2K9m08k-kFsGEGm-qTdebv9EkfGWXotbRW-9OAWyKunDuuDZYjVyK7Q/s1600/7.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj0OcAnXt06Xw31-DGnkalrE88qcr2w1mrmkhS768NuKTJcWfTjgKpYxTh3x5KMS004TodnhXvZQjEcmKpuaLF3g2K9m08k-kFsGEGm-qTdebv9EkfGWXotbRW-9OAWyKunDuuDZYjVyK7Q/s1600/7.png" height="320" width="194" /></a></div>
<br />
<pre class="brush: csharp">//Librerias
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
//Libreria Restsharp
using RestSharp;
namespace Aplicacion1
{
[Activity (Label = "GET")]
public class GET : Activity
{
//Declaroamos nuestras variables que utilizaremos
public ArrayAdapter&ltDatos_Usuarios&gt adapter;
//declaremos nuestro cliente
public RestClient cliente;
List<Datos_Usuarios> listausuarios = new List<Datos_Usuarios> ();
Button BtnMostrarDatos ;
ListView LvLIsta;
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
//seleccionamos nuestro layout GET
SetContentView (Resource.Layout.Get);
BtnMostrarDatos = FindViewById<Button> (Resource.Id.button1);
LvLIsta = FindViewById<ListView> (Resource.Id.listView1);
//asignamos la direccion de nuestro servicio
cliente = new RestClient ("http://192.168.1.73:83");
//declaramos nuestro adaptador para llenar nuestro listview
adapter = new ArrayAdapter<Datos_Usuarios>(this, Android.Resource.Layout.SimpleListItem1);
LvLIsta.Adapter = adapter;
MetodoGet ();
BtnMostrarDatos.Click += (object sender, EventArgs e) =>
{
listausuarios = new List<Datos_Usuarios>();
MetodoGet();
};
//declaramos el evento de click en listview para mostrar informacion extra en un toast
LvLIsta.ItemClick += lvlista_ItemClick;
// Create your application here
}
void lvlista_ItemClick (object sender, AdapterView.ItemClickEventArgs e)
{
//toast para mostrar informacion extra de la mostrada
Android.Widget.Toast.MakeText(this, listausuarios[e.Position].Email + " " + listausuarios[e.Position].Telefono, Android.Widget.ToastLength.Short).Show();
}
public void MetodoGet()
{
//limpiamos nuestro adaptador
adapter.Clear ();
//hacemos nuestro request donde declaramos que metodo vamos a utilizar
var request = new RestRequest ("api/Datos_Usuarios",Method.GET);
//ejecutamos el metodo para que nos devuelva todo la informacion y la mostramos en nuestro listview
var resultado = cliente.Execute<List<Datos_Usuarios>>(request).Data;
foreach (Datos_Usuarios x in resultado) {
Datos_Usuarios datos = new Datos_Usuarios ();
datos.Id_Persona = x.Id_Persona;
datos.Nombre = x.Nombre;
datos.Paterno = x.Paterno;
datos.Materno = x.Materno;
datos.Telefono = x.Telefono;
datos.Email = x.Email;
datos.Direccion = x.Direccion;
datos.Edad = x.Edad;
adapter.Add (x.Nombre + " " + x.Paterno + " " + x.Materno) ;
listausuarios.Add (datos);
}
}
}
}
</pre>
A continuación seguimos con nuestro método POST que es con el que insertaremos registros a nuestra base de datos a través del servicio.
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgxTGn7d-diBYaUaHIwl-melMAOrwdTtpKBMJ-TrWNzgFPUe3T29KnWyFPTkyL2Z6LJZJoddLDXmTOgH_JAQdH-RZL5QqTYQOBT8hTmZwpRIITejBoG7AoVuuHLPWgt3ovoZCpujes_Mm-x/s1600/8.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgxTGn7d-diBYaUaHIwl-melMAOrwdTtpKBMJ-TrWNzgFPUe3T29KnWyFPTkyL2Z6LJZJoddLDXmTOgH_JAQdH-RZL5QqTYQOBT8hTmZwpRIITejBoG7AoVuuHLPWgt3ovoZCpujes_Mm-x/s1600/8.png" height="320" width="196" /></a></div>
<pre class="brush: csharp">//Librerias
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using RestSharp;
namespace Aplicacion1
{
[Activity (Label = "POST")]
public class POST : Activity
{
//Variables
public RestClient cliente;
EditText txtnombre;
EditText txtpaterno;
EditText txtmaterno;
EditText txttelefono;
EditText txtemail;
EditText txtdireccion;
Button btnguardar;
string nombre,paterno,materno,telefono,email,direccion;
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
//Asignamos el layout Post
SetContentView (Resource.Layout.Post);
txtnombre = FindViewById<EditText> (Resource.Id.editText1);
txtpaterno = FindViewById<EditText> (Resource.Id.editText2);
txtmaterno = FindViewById<EditText> (Resource.Id.editText3);
txttelefono = FindViewById<EditText> (Resource.Id.editText4);
txtemail = FindViewById<EditText> (Resource.Id.editText5);
txtdireccion = FindViewById<EditText> (Resource.Id.editText6);
btnguardar = FindViewById<Button> (Resource.Id.button1);
//asignamos la direccion de nuestro servicio
cliente = new RestClient ("http://192.168.1.73:83");
//declaramos el evento a nuestro boton para guardar los datos
btnguardar.Click += (object sender, EventArgs e) =&gt {
//Asignamos el valor de nuestras variables
nombre = txtnombre.Text;
paterno = txtpaterno.Text;
materno = txtmaterno.Text;
telefono = txttelefono.Text;
email= txtemail.Text;
direccion = txtdireccion.Text;
//mandamos llamar el metodo post
MetodoPost(nombre,paterno,materno,telefono,email,direccion);
};
// Create your application here
}
public void MetodoPost(string nombre,string paterno, string materno,string telefono,string email,string direccion){
Datos_Usuarios usuarios = new Datos_Usuarios ();
usuarios.Nombre = nombre;
usuarios.Paterno = paterno;
usuarios.Materno = materno;
usuarios.Telefono = telefono;
usuarios.Email = email;
usuarios.Direccion = direccion;
usuarios.Edad = 23;
//hacemos el request del metodo que POST para guardar los datos
var request = new RestRequest("api/Datos_Usuarios", Method.POST);
//asignamos el valor de nuestros datos puede ser en XML O JSON en nuestro caso usaremos json
request.RequestFormat = DataFormat.Json;
//agregamos la entidad con los valores asignado anteriormente
request.AddBody(usuarios);
//ejecutamos el request
cliente.Execute (request);
//limpiamos los campos
txtnombre.Text = "";
txtpaterno.Text = "";
txtmaterno.Text = "";
txttelefono.Text = "";
txtemail.Text = "";
txtdireccion.Text = "";
AlertDialog.Builder dialogo = new AlertDialog.Builder (this);
AlertDialog men = dialogo.Create();
men.SetTitle ("Metodo Post");
men.SetMessage ("Guardado Correctamente");
men.Show ();
}
}
}
</pre>
Y finalmente nuestro Metodo DELETE para eliminar registros de la base de datos.
<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiQ8sgdXtAYXCWj0QwOqj7l4X87PChfBBqVEMwyZ6MEpPb0HvIxYYs5Ovp3rbDOzAlKi8lBut1XJV8EqYR-hZfK7yYJJ7oBFkcEhDj4EfiVnjpG3O11KDNaOZZewcczJk9EcaA4pSRTBkhk/s1600/9.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiQ8sgdXtAYXCWj0QwOqj7l4X87PChfBBqVEMwyZ6MEpPb0HvIxYYs5Ovp3rbDOzAlKi8lBut1XJV8EqYR-hZfK7yYJJ7oBFkcEhDj4EfiVnjpG3O11KDNaOZZewcczJk9EcaA4pSRTBkhk/s1600/9.png" height="320" width="191" /></a></div>
<pre class="brush: csharp">//Librerias
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using RestSharp;
namespace Aplicacion1
{
[Activity (Label = "DELETE")]
public class DELETE : Activity
{
//Variables
public ArrayAdapter<Datos_Usuarios> adapter;
public RestClient cliente;
List<Datos_Usuarios> listausuarios = new List<Datos_Usuarios> ();
ListView LvLIsta;
Button btndatos;
int id ;
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
//seleccionamos layout DELETE
SetContentView (Resource.Layout.Delete);
LvLIsta = FindViewById<ListView> (Resource.Id.listView1);
btndatos = FindViewById<Button> (Resource.Id.button1);
//Declaramos nuestro cliente
cliente = new RestClient ("http://192.168.1.73:83");
//inicializamos nuestro adaptador
adapter = new ArrayAdapter<Datos_Usuarios>(this, Android.Resource.Layout.SimpleListItem1);
LvLIsta.Adapter = adapter;
MetodoGet ();
LvLIsta.ItemClick += lvlista_ItemClick;
btndatos.Click += btndatos_Click;
// Create your application here
}
void btndatos_Click (object sender, EventArgs e)
{
MetodoGet ();
}
void lvlista_ItemClick (object sender, AdapterView.ItemClickEventArgs e)
{
//creamos un dialogo y agregamos 2 botones el de eliminar y el de aceptar
AlertDialog.Builder dialogo = new AlertDialog.Builder (this);
AlertDialog men = dialogo.Create();
men.SetTitle ("Metodo Delete");
men.SetMessage ("Seguro que desea eliminar el registro");
men.SetButton ("Aceptar",delegate(object send, DialogClickEventArgs er) {
id= listausuarios[e.Position].Id_Persona;
MetodoDelete();
listausuarios.RemoveAt(e.Position);
});
men.SetButton2("Cancelar",delegate(object sende, DialogClickEventArgs em) {
});
men.Show ();
}
public void MetodoDelete()
{
//creamos nuestro request con el metodo delete y pasamos el id del registro a eliminar
var request = new RestRequest("api/Datos_Usuarios/{id}", Method.DELETE);
//agregamos parametros
request.AddParameter("id",id);
//ejecutamos el request
cliente.Execute (request);
//llamamos el metodo get para actualizar el listview
MetodoGet ();
}
public void MetodoGet()
{
//limpiamos nuestro adaptador
adapter.Clear ();
//hacemos nuestro request donde declaramos que metodo vamos a utilizar
var request = new RestRequest ("api/Datos_Usuarios",Method.GET);
//ejecutamos el metodo para que nos devuelva todo la informacion y la mostramos en nuestro listview
var resultado = cliente.Execute<Listlt;Datos_Usuarios>>(request).Data;
foreach (Datos_Usuarios x in resultado) {
Datos_Usuarios datos = new Datos_Usuarios ();
datos.Id_Persona = x.Id_Persona;
datos.Nombre = x.Nombre;
datos.Paterno = x.Paterno;
datos.Materno = x.Materno;
datos.Telefono = x.Telefono;
datos.Email = x.Email;
datos.Direccion = x.Direccion;
datos.Edad = x.Edad;
adapter.Add (x.Nombre + " " + x.Paterno + " " + x.Materno) ;
listausuarios.Add (datos);
}
}
}
}</pre>
Este fue todo y solo fue un pequeño ejemplo de como consumir servicios Rest utilizando el componente de xamarin RestSharp.<br />
<br />
Acepto cualquier tipo de Comentario, Queja o Sugerencia.<br />
<br />
referencias:<br />
<a href="http://restsharp.org/">http://restsharp.org</a>/<br />
<a href="http://components.xamarin.com/view/restsharp">http://components.xamarin.com/view/restsharp</a>Rickyhttp://www.blogger.com/profile/08848939336739916405noreply@blogger.com3tag:blogger.com,1999:blog-4108938236884491316.post-6833046800275423702014-03-05T20:54:00.000-08:002014-03-05T21:17:11.969-08:00Entity Framework y Web Service REST.Como sabemos las aplicaciones de la windows store no pueden acceder a una base de datos directamente, esto se debe a que necesitan ser independientes para eliminar cualquier dependencia y así cualquier persona las puede descargar sin la necesidad de configurar un gestor de bases de datos directamente en su ordenador, por lo que normalmente se utiliza un Web Service que se encarga de recuperar y actualizar datos.<br />
<br />
El Entity Framework se encarga de implementar una abstracción de las tablas de la base de datos creando entidades de ellas, esto ayuda al desarrollador a reducir la cantidad de código de manera considerable.<br />
<br />
Comenzaremos con nuestro ejemplo donde primero vamos a acceder a SQL Server utilizando el Server Name "(localdb)\v11.0" este es el string de conexión que identifica la versión de SQL Server que viene instalado con Visual Studio.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgwTxO_iw88tk0r7H9z64sVwOYEotBUdeoclovrLrdQ_PN4DVUprMUL0YU5X4X0_8Q33t928-hJDrfcsXa9xruTdknhi5zHQnshWWY1gbUyGnY61q6Oj_KoAOBWLq2zyAIJv3_CoQGQe2_t/s1600/1.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgwTxO_iw88tk0r7H9z64sVwOYEotBUdeoclovrLrdQ_PN4DVUprMUL0YU5X4X0_8Q33t928-hJDrfcsXa9xruTdknhi5zHQnshWWY1gbUyGnY61q6Oj_KoAOBWLq2zyAIJv3_CoQGQe2_t/s1600/1.png" height="358" width="640" /></a></div>
<br />
Ahora continuaremos con realizar nuestra base de datos que utilizaremos en el ejemplo.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEic8vpRaq5kDYZVFj3uRINCjl0Phgog7eHNRneYr0AQA_9uIiNZzNWkxv9lEkOxgo77uFGoF1uS6KjlmmURok8JeVrat4V29LLA5seB_5IYynEK-RRNlbCxPZtk8D1vWy17yVFIe7O9NA6N/s1600/2.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEic8vpRaq5kDYZVFj3uRINCjl0Phgog7eHNRneYr0AQA_9uIiNZzNWkxv9lEkOxgo77uFGoF1uS6KjlmmURok8JeVrat4V29LLA5seB_5IYynEK-RRNlbCxPZtk8D1vWy17yVFIe7O9NA6N/s1600/2.png" height="358" width="640" /></a></div>
<br />
<a name='more'></a><br /><br />
Ahora pasaremos a Visual Studio donde vamos a crear un nuevo proyecto que sera una aplicacion Windows Store.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgGQc4SP5aY85dg6psKToXMSiVe6uqtWH0_TYIC9eESYAKGxHAnZtCjQpqht7F6VIPfwKA1dd2unChgEUIwecNZXip8PExFWArouPQtaS5bvvg0equRWuXGVD_-sOHr8QBG9B4kRJdbthNw/s1600/2.1nuevo.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgGQc4SP5aY85dg6psKToXMSiVe6uqtWH0_TYIC9eESYAKGxHAnZtCjQpqht7F6VIPfwKA1dd2unChgEUIwecNZXip8PExFWArouPQtaS5bvvg0equRWuXGVD_-sOHr8QBG9B4kRJdbthNw/s1600/2.1nuevo.png" height="359" width="640" /></a></div>
<br />
Ahora con nuestra solución creada vamos a añadir un nuevo proyecto dentro de nuestra solución.<br />
El nuevo proyecto añadido sera del tipo "ASP.NET Web Application" lo seleccionamos y le damos en OK.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg1r-IhLJ5F5QqRq7jWDtg8hCsi0yyUGqKHZ8Iv_2ym14an3n0GadLEc0aTLkUIiHJmHerIXWnGfKAvmardH546AfimsqaEfTLLgpdlVmUclRz7YbnB9iJDT7m5Ggx58zDDGWiT5UxM9q9p/s1600/3agregarservicio.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg1r-IhLJ5F5QqRq7jWDtg8hCsi0yyUGqKHZ8Iv_2ym14an3n0GadLEc0aTLkUIiHJmHerIXWnGfKAvmardH546AfimsqaEfTLLgpdlVmUclRz7YbnB9iJDT7m5Ggx58zDDGWiT5UxM9q9p/s1600/3agregarservicio.png" height="358" width="640" /></a></div>
<br />
Ahora seleccionamos el tipo, que sera una Web Api y presionamos el botón OK.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjg_tF3EwgLBZUL_lQ1wMLL0ZV1i2h-gGEJgU9kXhf42-UQnZsdL9ype4YdKX1tBZgscRsDnTss0E2n7D0yxlAjEG7EFaTfUY2wW7ssdjGBOGehboleUU9cfwZRi-BlU7m-IA6IggkCSRuy/s1600/3agregarservicio.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjg_tF3EwgLBZUL_lQ1wMLL0ZV1i2h-gGEJgU9kXhf42-UQnZsdL9ype4YdKX1tBZgscRsDnTss0E2n7D0yxlAjEG7EFaTfUY2wW7ssdjGBOGehboleUU9cfwZRi-BlU7m-IA6IggkCSRuy/s1600/3agregarservicio.png" height="358" width="640" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
Después de crearlo nos aparecerá la siguiente pantalla.</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjPler2i1WshWEhaxsRB81DPvvymcUIKNWtWlTdHK79g9bKTatov3anKvHgZa-Sw9bjkD_DWyuq8orJ2zuUrVkd2JRN61b4OzjcXr998oecFOVuFSaqtN_ohIq0ICWTHXj6Ly8s9rgKKT_U/s1600/5webapi+creada.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjPler2i1WshWEhaxsRB81DPvvymcUIKNWtWlTdHK79g9bKTatov3anKvHgZa-Sw9bjkD_DWyuq8orJ2zuUrVkd2JRN61b4OzjcXr998oecFOVuFSaqtN_ohIq0ICWTHXj6Ly8s9rgKKT_U/s1600/5webapi+creada.png" height="358" width="640" /></a></div>
<br />
<br />
<br />
Seleccionamos nuestra solución y daremos click derecho y seleccionamos "Set StarUp Project.".<br />
*Seleccionamos "Multiple startup project"<br />
*En nuestro servicio seleccionamos la acción "Start without debugging".<br />
*En nuestra aplicación seleccionamos la acción "Start".<br />
Ya seleccionando las acciones anteriores presionamos el botón aceptar.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjhplCpO77mxAeiFHr9b5ez-e2HXt18tM0_hyphenhyphenztoZrShTIFUy3vapI_R3FTFN4rqf3kYFIkWOK1D0CM_T-PVEVSqOWxylCoBPfBSxVTWTiSrlb1whYxi55O1qC4iUZa9a6bvx28yWGW9NoG/s1600/6Setstart.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjhplCpO77mxAeiFHr9b5ez-e2HXt18tM0_hyphenhyphenztoZrShTIFUy3vapI_R3FTFN4rqf3kYFIkWOK1D0CM_T-PVEVSqOWxylCoBPfBSxVTWTiSrlb1whYxi55O1qC4iUZa9a6bvx28yWGW9NoG/s1600/6Setstart.png" height="358" width="640" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
Seleccionamos nuestro servicio y le damos click derecho y seleccionamos "propierities" saldrá la pantalla como la imagen siguiente.</div>
<div class="separator" style="clear: both; text-align: left;">
Vamos a la pestaña Web y seleccionamos "Don´t open a page, wait for a request from an external application",</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjtUJ1uTsUNNdxhIC9L_TrqIAhWxiBt9PnPfLXnx6UgmJs-7fYkmRwX0P2S1ehEApipePaRRymWBorBVA05IAqJacqj3XmC2MLODcioF0X1g4zkyYMtUEL9m2WnleuV5VYRNm4d5foN0jIm/s1600/7propierity.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjtUJ1uTsUNNdxhIC9L_TrqIAhWxiBt9PnPfLXnx6UgmJs-7fYkmRwX0P2S1ehEApipePaRRymWBorBVA05IAqJacqj3XmC2MLODcioF0X1g4zkyYMtUEL9m2WnleuV5VYRNm4d5foN0jIm/s1600/7propierity.png" height="358" width="640" /></a></div>
<br />
En el apartado de Servers en "Project Url" cambiaremos el puerto por ejemplo yo estoy usando el 50001, el IIS Express asigna un puerto aleatorio pero lo cambiaremos por uno definido por nosotros,<br />
y presionamos "Create Virtual Directory".<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEimstBSipCBh8Yy0WnfSbOG16Gzetwl4MqoseNkMBIsPo9MqxB0mO118Xpd19aBZYcO-tl3KrJtE_wIV8bPaGyH-CEER5Aj__1_wy5YX9dhGKaLpPgQC8blFZuKUxmn7fk_V0cRD6HG4Gkv/s1600/8.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEimstBSipCBh8Yy0WnfSbOG16Gzetwl4MqoseNkMBIsPo9MqxB0mO118Xpd19aBZYcO-tl3KrJtE_wIV8bPaGyH-CEER5Aj__1_wy5YX9dhGKaLpPgQC8blFZuKUxmn7fk_V0cRD6HG4Gkv/s1600/8.png" height="358" width="640" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
Ahora agregaremos un Entity Model a nuestro servicio, para esto daremos click derecho a nuestro servicio, seleccionamos "Add" y después "New Item". </div>
<div class="separator" style="clear: both; text-align: left;">
Seleccionamos "Data" y seleccionamos "ADO.NET Entity Model" y presionamos Add.</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjM2drCd-EB1OJUVILCcnbdi9t4QyaIqYtfzDL3VOcAiCRtTXn3m-MeATB_JQZoEmyUpd0AQjR-4a0FrE0vZj65JgADXKI0H529ngviD3hyphenhyphenvwxeBmGj7gk519Vq4KL-_yN0ENDOrwgMasq9/s1600/9creardataentitymodel.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjM2drCd-EB1OJUVILCcnbdi9t4QyaIqYtfzDL3VOcAiCRtTXn3m-MeATB_JQZoEmyUpd0AQjR-4a0FrE0vZj65JgADXKI0H529ngviD3hyphenhyphenvwxeBmGj7gk519Vq4KL-_yN0ENDOrwgMasq9/s1600/9creardataentitymodel.png" height="358" width="640" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
Ahora seleccionaremos "Generate From database" y presionamos Next</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjIy23YQW4gmSBwzCIOwTgLkxwllT43ZZbAltLt-JdxbVz7JAF-Jw_s1AA8zK_9NXcazf8LWYvBe26KoTbK8ajobTwfexEqBJ9wq5fmvYoB6oKX2_WsKecf8uCqhe7zkezz1tUVOoiRbLQD/s1600/10Seleccionamosfrom.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjIy23YQW4gmSBwzCIOwTgLkxwllT43ZZbAltLt-JdxbVz7JAF-Jw_s1AA8zK_9NXcazf8LWYvBe26KoTbK8ajobTwfexEqBJ9wq5fmvYoB6oKX2_WsKecf8uCqhe7zkezz1tUVOoiRbLQD/s1600/10Seleccionamosfrom.png" height="358" width="640" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
Ahora crearemos una nueva conexión.</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjPzae9L7u-t3RNviN_YSWkZYdpFxjbxwLuGoIrQjS7sWspipB3EZuIjR5fZwBguMsbxCU30ShK_mvtzV_hwH4N7LXsry-4SK6gWWuB0QPJjcLwkI5HZEbOyUadC246U9uGHhTRmGUhzjVy/s1600/11seleccionamos+new+connection.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjPzae9L7u-t3RNviN_YSWkZYdpFxjbxwLuGoIrQjS7sWspipB3EZuIjR5fZwBguMsbxCU30ShK_mvtzV_hwH4N7LXsry-4SK6gWWuB0QPJjcLwkI5HZEbOyUadC246U9uGHhTRmGUhzjVy/s1600/11seleccionamos+new+connection.png" height="358" width="640" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
En server name pondremos (localdb)v11.0 para conectar a nuestra base de datos que creamos anteriormente y seleccionamos la base de datos antes creada.</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhfJCh4mXPitIa-TEnJLdrheuQW-17X70yzeq3TlMkxAZGGyZ3GZEV9kBZ09euzhQE5nTKrtEnIuqHpobeZrtuAWQ3zcWvRrfXowFw9CEkhvHq8GfA4ClGixmzXG1LCt11yGDWPh4rfs-ux/s1600/12configuramosNuevaconexion.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhfJCh4mXPitIa-TEnJLdrheuQW-17X70yzeq3TlMkxAZGGyZ3GZEV9kBZ09euzhQE5nTKrtEnIuqHpobeZrtuAWQ3zcWvRrfXowFw9CEkhvHq8GfA4ClGixmzXG1LCt11yGDWPh4rfs-ux/s1600/12configuramosNuevaconexion.png" height="358" width="640" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
Seleccionamos el Entity Framework 5.0 y presionamos Next.</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg8TksgTz3YX8YBFvMMvpU0SqwBRLzxrJB-gTHSkBtHopMckFbzlloUu8vahjfLHeJlNvcpVAJHB1ghFRdHQ15EisEY9B42HZDCFndSk2KXhMNWP2EbhVGNJNFkoZinSn_uHGANu_0yBMXo/s1600/13framework.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg8TksgTz3YX8YBFvMMvpU0SqwBRLzxrJB-gTHSkBtHopMckFbzlloUu8vahjfLHeJlNvcpVAJHB1ghFRdHQ15EisEY9B42HZDCFndSk2KXhMNWP2EbhVGNJNFkoZinSn_uHGANu_0yBMXo/s1600/13framework.png" height="358" width="640" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
Ahora desplegamos seleccionamos Tables y desplegamos para ver que esta seleccionada nuestra base de datos y presionamos finish.</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh1R3ZweIUlbkbd6a1OxI0AMOsHoSqjThzrxidwLO52p1jRJ-ByqEB6hhelWE_I_DwuqcGsY24JwiMqqfv71OENlydrKvkTT5nD4DDn76rG6Ey0zM3Ey37NbreITDuz6bQinkQg62VyNL_B/s1600/14seleccion.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh1R3ZweIUlbkbd6a1OxI0AMOsHoSqjThzrxidwLO52p1jRJ-ByqEB6hhelWE_I_DwuqcGsY24JwiMqqfv71OENlydrKvkTT5nD4DDn76rG6Ey0zM3Ey37NbreITDuz6bQinkQg62VyNL_B/s1600/14seleccion.png" height="358" width="640" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
Después de agregar nuestra entidad tendrá que salir como aparece en la siguiente imagen.</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhBeYZz4tr219dvxSfA1WKgeZX5VRmKfQdLxcgl2d07x9JmW0GDXgikqdGafC5avIe6rSOS_pL2H6j9n9JxUxIE9TiZ026AwZZieEJE5l9LonUY0X9GrPQkUK3CQunqt9opWVXkxrs6Y0Aj/s1600/15apareceraunapantallacomoesta.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhBeYZz4tr219dvxSfA1WKgeZX5VRmKfQdLxcgl2d07x9JmW0GDXgikqdGafC5avIe6rSOS_pL2H6j9n9JxUxIE9TiZ026AwZZieEJE5l9LonUY0X9GrPQkUK3CQunqt9opWVXkxrs6Y0Aj/s1600/15apareceraunapantallacomoesta.png" height="358" width="640" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
Otra vez seleccionaremos nuestro servicio y ahora agregaremos un nuevo "Scaffolded Item", este incluye generadores de códigos pre instalados, este creara el un controller con los métodos de "GET,PUT,POST,DELETE" para tener acceso o modificar los datos de nuestra base de datos.</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj7BFGsoXMYzNy4u2MEUGEPTjuLZ3gZfnHtFwHBV-akgSQcgUApqr74JTZjv_9RkBNxpq7qAmWj-pMiLjHeXv7N43SgTRQRAl-xG0UYi9rjQwwmuppuBR0Ivv6GWvWSM7Gbcd13B4FSMIX3/s1600/16newsca.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj7BFGsoXMYzNy4u2MEUGEPTjuLZ3gZfnHtFwHBV-akgSQcgUApqr74JTZjv_9RkBNxpq7qAmWj-pMiLjHeXv7N43SgTRQRAl-xG0UYi9rjQwwmuppuBR0Ivv6GWvWSM7Gbcd13B4FSMIX3/s1600/16newsca.png" height="358" width="640" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
Seleccionamos "Web Api Controller with actions, using Entity Framework" y presionamos Add.</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEicW_1otruIKbjLhgh3lC2fz7rAMjsdJDrtJW__3DQA2WFRsd4NIFlk7wJ8MhQwPm-E1CDCuHJyqM4PddsNcJlAwe_0aV8GNOkZnGzYyUPx9haiwpGvXH1oHKMnxYH9ImFTsiwcHEkUSW4q/s1600/17webapicontroller.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEicW_1otruIKbjLhgh3lC2fz7rAMjsdJDrtJW__3DQA2WFRsd4NIFlk7wJ8MhQwPm-E1CDCuHJyqM4PddsNcJlAwe_0aV8GNOkZnGzYyUPx9haiwpGvXH1oHKMnxYH9ImFTsiwcHEkUSW4q/s1600/17webapicontroller.png" height="358" width="640" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
Ingresamos el nombre de nuestro controller, seleccionamos el model antes creado y el data context. y presionamos Add.</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEit8nA3Lgp-lykK2g9CQYNR5arxDNqR3UGZWqNmxqBKBod8OoTMYcEQTQzp6mcqqWbAUGXK3Sbr5I9PQ8UA1FI0R18wDSpnM1mB84KE4EF3BiEqx6POr9k7LyI21BLUhVtvqL_J4bn3eibO/s1600/18addcontroller.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEit8nA3Lgp-lykK2g9CQYNR5arxDNqR3UGZWqNmxqBKBod8OoTMYcEQTQzp6mcqqWbAUGXK3Sbr5I9PQ8UA1FI0R18wDSpnM1mB84KE4EF3BiEqx6POr9k7LyI21BLUhVtvqL_J4bn3eibO/s1600/18addcontroller.png" height="358" width="640" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
estos son los nuevos métodos que se crearon automáticamente al agregar el "Scaffolded Item".</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgP8-tWGn7MWpW1Hhn270-FT8laValRt0GvfpQ1AZZ8OVgW3MrDTDs-lMKr3H7Mt-56kbCnChCfLmkFkV_WlK67KcOM5Gy61FH4SdaeXyYerBjDXdhNXjwIKQk_eJfzdGzVMwbCsGHtB0ks/s1600/19GetPutPostDelete.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgP8-tWGn7MWpW1Hhn270-FT8laValRt0GvfpQ1AZZ8OVgW3MrDTDs-lMKr3H7Mt-56kbCnChCfLmkFkV_WlK67KcOM5Gy61FH4SdaeXyYerBjDXdhNXjwIKQk_eJfzdGzVMwbCsGHtB0ks/s1600/19GetPutPostDelete.png" height="358" width="640" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
Vamos a verificar que nuestro servicio este funcionando perfectamente, lo seleccionamos damos click derecho y vamos a la opción View y seleccionamos "View in Browser" en mi caso aparece el navegador google chrome ya que es mi navegador predeterminado.</div>
<div class="separator" style="clear: both; text-align: center;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjbIrj_mik7NIu_nYfCpcLgOuFBqgO-mZMXpX_kRU3GUOQqlxpggBTMu-PoDfEJUkMVOsJr9i_Jcu-hwJDJba6gUxxCMB7GNgH0xOOtKXY-BFlXvwaXHtVoEuhl9Ly05qWhWQbTwNUrG0dE/s1600/20view.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjbIrj_mik7NIu_nYfCpcLgOuFBqgO-mZMXpX_kRU3GUOQqlxpggBTMu-PoDfEJUkMVOsJr9i_Jcu-hwJDJba6gUxxCMB7GNgH0xOOtKXY-BFlXvwaXHtVoEuhl9Ly05qWhWQbTwNUrG0dE/s1600/20view.png" height="358" width="640" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
Nos tendrá que aparecer en el navegador como en la siguiente imagen.</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEitvCIOW5dB8155LlmCSdsfTiOKDbTJa852TJ7TDyqFPhksnrFCVt24vNeKwSM1m5_GvrujWz_wJj74L6aP_rUJszm9lUdHqH9bFwJ8cZq4JiSJ15ynyqsiBptkT53eeaL67Qhh2of-n6Lf/s1600/21apareceraesto.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEitvCIOW5dB8155LlmCSdsfTiOKDbTJa852TJ7TDyqFPhksnrFCVt24vNeKwSM1m5_GvrujWz_wJj74L6aP_rUJszm9lUdHqH9bFwJ8cZq4JiSJ15ynyqsiBptkT53eeaL67Qhh2of-n6Lf/s1600/21apareceraesto.png" height="358" width="640" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
Verificamos que nuestro servicio esta accediendo a los datos, en la barra de direcciones agregamos la siguiente dirección http://localhost:50001/api/Datos_Usuarios, con esta dirección obtendremos todos los datos de la base de datos en xml o en Json, o si necesitamos un usuario en especifico pasaremos el Id del usuario en la url por ejemplo quedaría así para obtener los datos del usuario con Id = 1, http://localhost:50001/api/Datos_Usuarios/1.</div>
<div class="separator" style="clear: both; text-align: left;">
A continuación insertare los ejemplos .</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjWaurJLbrkdRcqu_RpUMOghD51ezIjrqlb8MgLheJiWcpNZWqzA09emQjaIfWDkHJVxFxxKSk9gY9XR1mUc1pFcM5JQe-2GwU7gKrmIKNFKvnJRgOu9uZdwWbTglqGnHSqh9xHQGezUFyW/s1600/22datosusuarios.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjWaurJLbrkdRcqu_RpUMOghD51ezIjrqlb8MgLheJiWcpNZWqzA09emQjaIfWDkHJVxFxxKSk9gY9XR1mUc1pFcM5JQe-2GwU7gKrmIKNFKvnJRgOu9uZdwWbTglqGnHSqh9xHQGezUFyW/s1600/22datosusuarios.png" height="358" width="640" /></a></div>
<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhmpRQA7wGcyomsDNet1e7Qd691yhP3lbeZ6Dv2lsk5hYNFzF05BxhDC0LhjEgqA9fugVGSgFCVKS269qPzTQmD8hIsNujqREF0GPpD3cXeTknhIcFhMMiKS0GfMGXemr1mtZzIDYBrk5TV/s1600/23datosusuariosfiltro.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhmpRQA7wGcyomsDNet1e7Qd691yhP3lbeZ6Dv2lsk5hYNFzF05BxhDC0LhjEgqA9fugVGSgFCVKS269qPzTQmD8hIsNujqREF0GPpD3cXeTknhIcFhMMiKS0GfMGXemr1mtZzIDYBrk5TV/s1600/23datosusuariosfiltro.png" height="358" width="640" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
Ahora si comenzaremos con la interfaz de nuestra aplicación donde utilizaremos nuestros Web Service antes creados.</div>
<div class="separator" style="clear: both; text-align: left;">
*Primero Agregaremos un ListView donde mostraremos todos los usuarios de nuestra base de datos.</div>
<div class="separator" style="clear: both; text-align: left;">
*Agregaremos nuestros campos donde insertaremos usuarios nuevos a nuestra base de datos.</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEibzH8Ai2tsKuvdsApHmOOJ97cw7mmIud8IASDTcDjyGBiukp45tZ0f9kk8D8Dnpr4k_ZNL77bufTxIzpx0cGzsMPUWCCu0sVrnhnPYhrUzrXb3O4Cefvg54iWfomNHgeKC7qyjg3ujxTEo/s1600/24PantallaPrincipal.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEibzH8Ai2tsKuvdsApHmOOJ97cw7mmIud8IASDTcDjyGBiukp45tZ0f9kk8D8Dnpr4k_ZNL77bufTxIzpx0cGzsMPUWCCu0sVrnhnPYhrUzrXb3O4Cefvg54iWfomNHgeKC7qyjg3ujxTEo/s1600/24PantallaPrincipal.png" height="358" width="640" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
A continuacion pondre el codigo que utilizamos en la aplicacion.</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<pre class="brush: csharp">using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace ServiciosRest
{
public sealed partial class MainPage : Page
{
//Declaramos la Url del servidor al que vamos a acceder.
private const string serverurl = "http://localhost:50001";
//Declaramos un HttpCliet ;
private HttpClient client = null;
// Declaramos la lista donde llenaremos los datos .
List &ltDatos_Usuarios&gt datos_usuarios = new List &ltDatos_Usuarios&gt();
public MainPage()
{
this.InitializeComponent();
//Inicializamos la variable de cliente
this.client = new HttpClient();
this.client.BaseAddress = new Uri(serverurl);
this.client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
GetDataasync();
}
//En este metodo obtendremos todos los datos de la base de datos
public async Task GetDataasync()
{
try
{
//Obtenemos los datos
var response = await this.client.GetAsync("api/Datos_Usuarios");
if(response.IsSuccessStatusCode)
{
//leemos los datos y los agregamos a una lista y los agregamos a nuestro listview
var customerdata = await response.Content.ReadAsAsync &ltIEnumerable &ltDatos_Usuarios&gt&gt();
this.datos_usuarios = customerdata as List &ltDatos_Usuarios>
listview.Items.Clear();
foreach (Datos_Usuarios x in datos_usuarios)
{
listview.Items.Add(" " + x.Nombre + " " + x.Paterno + " " + x.Materno + " " + " " + x.Telefono + " " + x.Email + " " + x.Direccion + " "+ x.Edad.ToString());
}
}
else
{
}
}
catch
{
}
}
public async void SaveAsync()
{
//llenamos nuestra entidad con los datos que estan en los textbox
Datos_Usuarios datos = new Datos_Usuarios();
datos.Nombre = txtnombre.Text;
datos.Paterno = txtpaterno.Text;
datos.Materno = txtmaterno.Text;
datos.Telefono = txttelefono.Text;
datos.Email = txtmail.Text;
datos.Direccion = txtdireccion.Text;
datos.Edad = Convert.ToDouble(txtedad.Text);
try
{
//Ingresamos los datos a nuestra base de datos y actualizamos el listview
var response = await this.client.PostAsJsonAsync("api/Datos_Usuarios", datos);
if (response.IsSuccessStatusCode)
{
if (response.IsSuccessStatusCode)
{
GetDataasync();
}
}
}
catch
{
}
}
private void btnguardar_Click(object sender, RoutedEventArgs e)
{
//llamamos el metodo de guardar y limpiamos los campos.
SaveAsync();
txtnombre.Text = "";
txtpaterno.Text = "";
txtmaterno.Text = "";
txttelefono.Text = "";
txtmail.Text = "";
txtdireccion.Text = "";
txtedad.Text = "";
}
//Entidad de Datos_Usuarios
public class Datos_Usuarios
{
public int Id_Persona { get; set; }
public string Nombre { get; set; }
public string Paterno { get; set; }
public string Materno { get; set; }
public string Telefono { get; set; }
public string Email { get; set; }
public string Direccion { get; set; }
public double Edad { get; set; }
}
}
}</pre>
Esto es todo de este ejemplo espero y les halla ayudado.Rickyhttp://www.blogger.com/profile/08848939336739916405noreply@blogger.com0tag:blogger.com,1999:blog-4108938236884491316.post-44115436087674315562014-02-26T15:47:00.000-08:002014-03-05T21:15:58.375-08:00Comunicacion Arduino y Windows 8.1 Mediante BluetoothEste es un pequeño ejemplo de comunicación de arduino con una aplicación windows 8.1 a través del bluetooth donde manipularemos un led y servomotor enviando datos al arduino para que realice el evento requerido y recibiendo un mensaje en la aplicación del evento que se esta realizando en el arduino.<br />
<br />
<b>Software y materiales utilizados</b><br />
<b><br /></b>
Visual Studio 2013.<br />
Visual Micro.<br />
Arduino Leonardo.<br />
Bluetooth shield for arduino.<br />
Micro Servo 9g SG90.<br />
Led.<br />
<br />
A continuación mostrare una captura de pantalla de la aplicación, y daré una breve explicación de los elementos que se agregaron y su funcionamiento.<br />
<br />
*Botón Buscar: para realizar la busqueda del dispositivo bleutooth.<br />
*Botón Cancelar: para cancelar la conexión antes de que se conecte con el dispositivo.<br />
*Botón Desconectar: para desconectar la conexión con el dispositivo.<br />
*TextBlock Excepciones: para mostrar cualquier problema que halla durante la conexión.<br />
*Boton Led: donde encenderá y apagara el led.<br />
*TextBlock Estado Led; donde mostrara el estado del led si esta encendido o apagado.<br />
*Boton Motor: para mover el servo.<br />
*TextBlock Estado Motor: mostrara el estado del motor hacia donde esta girando<br />
<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEimcKsQx_2vtpWi-qNUrx_j0EmSxl6cyk2aKvDjkzjsS1n2xoMQotIAemY05Ogzx6VQYLaXTWmOaWM_XYyGgf9k3mbipJNy42L_OKzGe4qJ_gZ373eEtDvobSl7VOG-_Zii1wpu9OkjfNc2/s1600/Pantalla+Principal.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEimcKsQx_2vtpWi-qNUrx_j0EmSxl6cyk2aKvDjkzjsS1n2xoMQotIAemY05Ogzx6VQYLaXTWmOaWM_XYyGgf9k3mbipJNy42L_OKzGe4qJ_gZ373eEtDvobSl7VOG-_Zii1wpu9OkjfNc2/s1600/Pantalla+Principal.png" height="356" width="640" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
Aqui dejo como va conectado el circuito utilizado.</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh82iACxp-hGQRtbPipHMWV5FLWrbpNmzyOHMvyVcbARQ4sfXSixsE0cRMaiXMFaY998o5qsUwK89y5xk-P-USfvQ3Quq6W9rrifYQITYg_EzD6S4_-uIU7GB432rYWKC0bNwFmS-B_IHGq/s1600/circuito.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh82iACxp-hGQRtbPipHMWV5FLWrbpNmzyOHMvyVcbARQ4sfXSixsE0cRMaiXMFaY998o5qsUwK89y5xk-P-USfvQ3Quq6W9rrifYQITYg_EzD6S4_-uIU7GB432rYWKC0bNwFmS-B_IHGq/s1600/circuito.png" height="322" width="640" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<a name='more'></a><br /><br />
<div class="separator" style="clear: both; text-align: left;">
Aqui dejare el sketch de arduino :</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<pre class="brush: csharp">//Librerias
#include &ltservo .h=""&gt
#include "SoftwareSerial.h"
//Variables
Servo myservo;
int Luz = 13;
const int TX_BT = 10;
const int RX_BT = 11;
SoftwareSerial BluetoothSerial(TX_BT, RX_BT);
void setup() {
// put your setup code here, to run once:
pinMode(Luz, OUTPUT);
Serial.begin(9600);
Serial.println("Serial Iniciado");
BluetoothSerial.begin(9600);
Serial.println("Bluetooth Iniciado");
}
void loop() {
// put your main code here, to run repeatedly:
LeerBluetooth();
}
//Metodo para recibir el mensaje enviado desde nuestra aplicacion
void LeerBluetooth()
{
if (BluetoothSerial.available())
{
int commandSize = (int) BluetoothSerial.read();
char command[commandSize];
int commandPos = 0;
while (commandPos < commandSize)
{
if (BluetoothSerial.available())
{
command[commandPos] = (char) BluetoothSerial.read();
commandPos++;
}
}
command[commandPos] = 0;
Eventos(command);
}
}
//En este metodo se procesa el mensaje
//y dependiendo del mensaje enviado desde la aplicacion
//realiza una funcion
void Eventos(char* message)
{
Serial.println(message);
if ((String) message == "Encender_Luz")
{
digitalWrite(Luz, HIGH);
EnviarMensaje("Luz Encendida");
}
if ((String) message == "Apagar_Luz")
{
digitalWrite(Luz, LOW);
EnviarMensaje("Luz Apagada");
}
if ((String) message == "Mover_Motor")
{
Mover180();
EnviarMensaje("Servo a 180 Grados");
delay(2000);
Mover0();
EnviarMensaje("Servo a 0 Grados");
delay(2000);
}
myservo.detach();
}
//Envia mensaje a la aplicacion del proceso que esta realizando en el arduino
void EnviarMensaje(char* message)
{
Serial.print("> ");
Serial.println(message);
int messageLen = strlen(message);
if (messageLen < 256)
{
BluetoothSerial.write(messageLen);
BluetoothSerial.print(message);
}
}
//Metodos para mover los servos
void Mover180()
{
myservo.attach(12);
myservo.write(180);
delay(15);
}
void Mover0()
{
myservo.attach(12);
myservo.write(0);
delay(15);
}
</pre>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both;">
<br /></div>
<div class="separator" style="clear: both;">
Ahora pasaremos al código para desarrollar la aplicación para lo que crearemos una clase llamada ConexionBluetooth. Esta clase es la encargada de buscar los dispositivos disponibles, realizar la conexión con el dispositivo, enviar y recibir mensaje con el arduino a través del bluetooth. </div>
<div class="separator" style="clear: both;">
El código es el siguiente :</div>
<div class="separator" style="clear: both;">
<br /></div>
<pre class="brush: csharp">//librerias
using System;
using System.Threading.Tasks;
using Windows.Devices.Bluetooth.Rfcomm;
using Windows.Devices.Enumeration;
using Windows.Foundation;
using Windows.Networking.Sockets;
using Windows.Storage.Streams;
using Windows.UI.Popups;
namespace BluetoothArduino
{
public class ConexionBluetooth
{
#region Eventos
//Declaramos el delegado del cambio de estado del bluetooth
public delegate void AddOnStateChangedDelegate(object sender, BluetoothConnectionState state);
public event AddOnStateChangedDelegate StateChanged;
private void OnStateChangedEvent(object sender, BluetoothConnectionState state)
{
if (StateChanged != null)
StateChanged(sender, state);
}
//Aqui declararemos el delegado de las exepciones
public delegate void AddOnExceptionOccuredDelegate(object sender, Exception ex);
public event AddOnExceptionOccuredDelegate ExceptionOccured;
private void OnExceptionOccuredEvent(object sender, Exception ex)
{
if (ExceptionOccured != null)
ExceptionOccured(sender, ex);
}
//En este delegado recibira el mensaje enviado desde el arduino
public delegate void AddOnMessageReceivedDelegate(object sender, string message);
public event AddOnMessageReceivedDelegate MessageReceived;
private void OnMessageReceivedEvent(object sender, string message)
{
if (MessageReceived != null)
MessageReceived(sender, message);
}
#endregion
#region Variables
//Declaramos nuestras Variables
private IAsyncOperation&ltrfcommdeviceservice&gt connectService;
private IAsyncAction connectAction;
private RfcommDeviceService rfcommService;
private StreamSocket socket;
private DataReader reader;
private DataWriter writer;
private BluetoothConnectionState _State;
public BluetoothConnectionState State
{
get { return _State; }
set { _State = value; OnStateChangedEvent(this, value); }
}
#endregion
#region Lifecycle
//En esta metodo se muestran los dispositivos que sean del tipo SerialPort en un PopupMenu
public async Task EnumerateDevicesAsync(Rect invokerRect)
{
this.State = BluetoothConnectionState.Enumerating;
//seleccionamos todos los dispositivos disponibles
var serviceInfoCollection = await DeviceInformation.FindAllAsync(RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort));
//Creamos el PopupMenu en el que se mostraran los dispositivos
PopupMenu menu = new PopupMenu();
//Añadimos los dispositivos encontrados al PopupMenu
foreach (var serviceInfo in serviceInfoCollection)
menu.Commands.Add(new UICommand(serviceInfo.Name, new UICommandInvokedHandler(ConnectToServiceAsync), serviceInfo));
//Seleccionamos el dispositvo con el que nos queremos comunicar
var result = await menu.ShowForSelectionAsync(invokerRect);
//Si no se pudo conectar al dispositivo se cambia el estado de la conexion a desconectado
if (result == null)
this.State = BluetoothConnectionState.Disconnected;
}
//Metodo que nos dara la conexion al dispositivo seleccionado
private async void ConnectToServiceAsync(IUICommand command)
{
//Se obtiene el Id del dispositivo seleccionado
DeviceInformation serviceInfo = (DeviceInformation)command.Id;
//el estado de la conexion se pondra conectando
this.State = BluetoothConnectionState.Connecting;
try
{
//Inicializa el servicio del dispositivo RFCOMM de Bluetooth de destino
connectService = RfcommDeviceService.FromIdAsync(serviceInfo.Id);
rfcommService = await connectService;
if (rfcommService != null)
{
//Se inicializa el socket
socket = new StreamSocket();
connectAction = socket.ConnectAsync(rfcommService.ConnectionHostName, rfcommService.ConnectionServiceName, SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication);
//Puedes Cancelar la conexion
await connectAction;
//Se inicializan las variables que envian y reciben los mensajes
writer = new DataWriter(socket.OutputStream);
reader = new DataReader(socket.InputStream);
Task listen = ListenForMessagesAsync();
//se cambia el estado de conexion del bluetooth a conectado
this.State = BluetoothConnectionState.Connected;
}
else
OnExceptionOccuredEvent(this, new Exception("No se pudo connectar al servicio.\n Verifca que 'bluetooth.rfcomm' capabilityes es declarado con la funcion de tipo 'name:serialPort' en Package.appxmanifest."));
}
catch (TaskCanceledException)
{
this.State = BluetoothConnectionState.Disconnected;
}
catch (Exception ex)
{
this.State = BluetoothConnectionState.Disconnected;
OnExceptionOccuredEvent(this, ex);
}
}
//Cancelar la conexion
public void AbortConnection()
{
if (connectService != null && connectService.Status == AsyncStatus.Started)
connectService.Cancel();
if (connectAction != null && connectAction.Status == AsyncStatus.Started)
connectAction.Cancel();
}
//Terminar la conexion con el dispositivo
public void Disconnect()
{
//dejamos variables en null
if (reader != null)
reader = null;
if (writer != null)
{
writer.DetachStream();
writer = null;
}
if (socket != null)
{
socket.Dispose();
socket = null;
}
if (rfcommService != null)
rfcommService = null;
this.State = BluetoothConnectionState.Disconnected;
}
#endregion
#region Enviar y Recivir
//Metodo para enviar los mensajes al arduino
public async Task&ltuint&gt SendMessageAsync(string message)
{
//Declaramos variable para ver tamaño del mensaje
uint sentMessageSize = 0;
if (writer != null)
{
//obtenemos el tamaño del string y lo convertimos en bytes y lo enviamos
uint messageSize = writer.MeasureString(message);
writer.WriteByte((byte)messageSize);
sentMessageSize = writer.WriteString(message);
await writer.StoreAsync();
}
return sentMessageSize;
}
private async Task ListenForMessagesAsync()
{
while (reader != null)
{
try
{
uint sizeFieldCount = await reader.LoadAsync(1);
if (sizeFieldCount != 1)
{
// el socket se cierra antes de que se puedan leer los datos
return;
}
// Leer el mensaje
uint messageLength = reader.ReadByte();
uint actualMessageLength = await reader.LoadAsync(messageLength);
if (messageLength != actualMessageLength)
{
// el socket se cierra antes de que se puedan leer los datos
return;
}
// mensaje leido y asignado a la variable message
string message = reader.ReadString(actualMessageLength);
// Se ejecuta el evento y retorna el mensaje
OnMessageReceivedEvent(this, message);
}
catch (Exception ex)
{
if (reader != null)
OnExceptionOccuredEvent(this, ex);
}
}
}
#endregion
}
//Tipos de estados de la conexion
public enum BluetoothConnectionState
{
Disconnected,
Connected,
Enumerating,
Connecting
}
}
}
</pre>
<div class="separator" style="clear: both; font-family: 'Times New Roman'; white-space: normal;">
Importante agregar en Package.appxmanifest la siguientes Capabilities :</div>
<pre class="brush: csharp">&ltCapabilities&gt
&ltm2:DeviceCapability Name="bluetooth.rfcomm"&gt
&ltm2:Device Id="any"&gt
&ltm2:Function Type="name:serialPort"/&agt
&lt/m2:Device&gt
&lt/m2:DeviceCapability&gt
&lt/Capabilities&gt
</pre>
<div class="separator" style="clear: both;">
<br /></div>
<div class="separator" style="clear: both;">
Se debe de agregar la librería TCD.Controls.dll que viene agregada en el proyecto , ahora el código del MainPage que es el siguiente :</div>
<div class="separator" style="clear: both;">
<br /></div>
<pre class="brush: java">using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using TCD.Controls;
namespace BluetoothArduino
{
public sealed partial class MainPage : Page
{
//Hacemos instancia de la clase
private ConexionBluetooth conexion = new ConexionBluetooth();
// bandera que usaremos para saber el estado de la luz
int banderaLuz = 0;
public MainPage()
{
this.InitializeComponent();
//declaramos nuestros eventos
conexion.ExceptionOccured += delegate(object sender, Exception ex) { txtconsola.Text = ex.Message + "\n"; };
conexion.MessageReceived += connectionManager_MessageReceived;
conexion.StateChanged += connectionManager_StateChanged;
conexion.State = BluetoothConnectionState.Disconnected;
}
protected override void OnNavigatedFrom(Windows.UI.Xaml.Navigation.NavigationEventArgs e)
{
conexion.Disconnect();
base.OnNavigatedFrom(e);
progress.Visibility = Visibility.Collapsed;
}
//Evento para habilitar o desahbilitar los botones segun la conexion
private void connectionManager_StateChanged(object sender, BluetoothConnectionState state)
{
progress.IsIndeterminate = (state == BluetoothConnectionState.Connecting);
btncancelar.IsEnabled = (state == BluetoothConnectionState.Connecting);
btndesconectar.IsEnabled = (state == BluetoothConnectionState.Connected);
}
//Evento donde se recibe el mensaje enviado desde el arduino y los mostrara en los textblock de estados
//dependiendo del mensaje enviado
private async void connectionManager_MessageReceived(object sender, string message)
{
if (message == "Luz Encendida")
{
txtled.Text = message;
}
else if (message == "Luz Apagada")
{
txtled.Text = message;
}
else if (message == "Servo a 180 Grados")
{
txtmotor.Text = message;
}
else if (message == "Servo a 0 Grados")
{
txtmotor.Text = message;
}
}
//Boton de buscar muestra la lista de dispositivos encontrados solo es seleccionarlo para comenzar la conexion
private async void Button_Click_1(object sender, RoutedEventArgs e)
{
await conexion.EnumerateDevicesAsync((sender as Button).GetElementRect());
progress.Visibility = Visibility.Visible;
}
//Boton Cancelar cancela la conexion al bluetooth
private void btncancelar_Click(object sender, RoutedEventArgs e)
{
conexion.AbortConnection();
progress.Visibility = Visibility.Collapsed;
}
//Boton Desconectar
//desconecta la conexion con el bluetooth
private void btndesconectar_Click(object sender, RoutedEventArgs e)
{
conexion.Disconnect();
progress.Visibility = Visibility.Collapsed;
}
//Boton Led Envia Mensaje al arduino
private async void btnled_Click(object sender, RoutedEventArgs e)
{
if (banderaLuz == 0)
{
var res = await conexion.SendMessageAsync("Encender_Luz");
banderaLuz = 1;
}
else if (banderaLuz == 1)
{
var res = await conexion.SendMessageAsync("Apagar_Luz");
banderaLuz = 0;
}
}
//Envia Mensaje al arduino para mover el motor
private async void Button_Click(object sender, RoutedEventArgs e)
{
var res = await conexion.SendMessageAsync("Mover_Motor");
}
}
}
}
</pre>
Esto es todo de este ejemplo, esperen nuevas entradas.
Les dejo el link para su descarga:
<a href="https://github.com/ricky3c/Windows-8.1---Arduino">https://github.com/ricky3c/Windows-8.1---Arduino</a>
<br />
<div class="separator" style="clear: both;">
<br /></div>
<div class="separator" style="clear: both;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<br /></div>
Rickyhttp://www.blogger.com/profile/08848939336739916405noreply@blogger.com1