Javier Gómez López [email protected] ; Francisca Rosales Gómez [email protected]
INTEGRACION DE SOLUCIONES - uv.mx
Transcript of INTEGRACION DE SOLUCIONES - uv.mx
![Page 1: INTEGRACION DE SOLUCIONES - uv.mx](https://reader036.fdocumento.com/reader036/viewer/2022070402/62c0306b8898b83eed392838/html5/thumbnails/1.jpg)
Facultad de Estadística e Informática
INTEGRACION DE SOLUCIONES
![Page 2: INTEGRACION DE SOLUCIONES - uv.mx](https://reader036.fdocumento.com/reader036/viewer/2022070402/62c0306b8898b83eed392838/html5/thumbnails/2.jpg)
Facultad de Estadística e Informática
Servicios Web RESTful
▪ Práctica. Creando una aplicación Web y una Web API para acceder a una base de datos.
![Page 3: INTEGRACION DE SOLUCIONES - uv.mx](https://reader036.fdocumento.com/reader036/viewer/2022070402/62c0306b8898b83eed392838/html5/thumbnails/3.jpg)
Facultad de Estadística e Informática
▪ Práctica. Creando una aplicación Web y una Web API:
✓ Página HTML: MVC ASP.NET
✓Manejo de solicitudes AJAX y retorno de datos JSON: ASP
.NET Web API
✓ Enlazar los elementos HTML a los datos JSON: jQuery
✓Base de datos: Entity Framework
Servicios Web RESTful
![Page 4: INTEGRACION DE SOLUCIONES - uv.mx](https://reader036.fdocumento.com/reader036/viewer/2022070402/62c0306b8898b83eed392838/html5/thumbnails/4.jpg)
Facultad de Estadística e Informática
Creación del proyecto
![Page 5: INTEGRACION DE SOLUCIONES - uv.mx](https://reader036.fdocumento.com/reader036/viewer/2022070402/62c0306b8898b83eed392838/html5/thumbnails/5.jpg)
Facultad de Estadística e Informática
![Page 6: INTEGRACION DE SOLUCIONES - uv.mx](https://reader036.fdocumento.com/reader036/viewer/2022070402/62c0306b8898b83eed392838/html5/thumbnails/6.jpg)
Facultad de Estadística e Informática
![Page 7: INTEGRACION DE SOLUCIONES - uv.mx](https://reader036.fdocumento.com/reader036/viewer/2022070402/62c0306b8898b83eed392838/html5/thumbnails/7.jpg)
MODELOS
![Page 8: INTEGRACION DE SOLUCIONES - uv.mx](https://reader036.fdocumento.com/reader036/viewer/2022070402/62c0306b8898b83eed392838/html5/thumbnails/8.jpg)
Facultad de Estadística e Informática
Creación de Modelos
•Author
•Book
![Page 9: INTEGRACION DE SOLUCIONES - uv.mx](https://reader036.fdocumento.com/reader036/viewer/2022070402/62c0306b8898b83eed392838/html5/thumbnails/9.jpg)
Facultad de Estadística e Informática
Creación de la clase Author
namespace BookService.Models{
public class Author{
public int Id { get; set; }[Required]public string Name { get; set; }
}}
![Page 10: INTEGRACION DE SOLUCIONES - uv.mx](https://reader036.fdocumento.com/reader036/viewer/2022070402/62c0306b8898b83eed392838/html5/thumbnails/10.jpg)
Facultad de Estadística e Informática
Creación de la clase Booknamespace BookService.Models{
public class Book{
public int Id { get; set; }[Required]public string Title { get; set; }public int Year { get; set; }public decimal Price { get; set; }public string Genre { get; set; }
// Llave foráneapublic int AuthorId { get; set; }// Propiedad para navegar al autor relacionadopublic Author Author { get; set; }
}}
![Page 11: INTEGRACION DE SOLUCIONES - uv.mx](https://reader036.fdocumento.com/reader036/viewer/2022070402/62c0306b8898b83eed392838/html5/thumbnails/11.jpg)
CONTROLADORES
![Page 12: INTEGRACION DE SOLUCIONES - uv.mx](https://reader036.fdocumento.com/reader036/viewer/2022070402/62c0306b8898b83eed392838/html5/thumbnails/12.jpg)
Facultad de Estadística e Informática
Eliminar Controlador ejemplo
Eliminar
![Page 13: INTEGRACION DE SOLUCIONES - uv.mx](https://reader036.fdocumento.com/reader036/viewer/2022070402/62c0306b8898b83eed392838/html5/thumbnails/13.jpg)
COMPILAR el proyecto para reflejar las clases del Modelo
![Page 14: INTEGRACION DE SOLUCIONES - uv.mx](https://reader036.fdocumento.com/reader036/viewer/2022070402/62c0306b8898b83eed392838/html5/thumbnails/14.jpg)
Facultad de Estadística e Informática
Agregar Controladores
![Page 15: INTEGRACION DE SOLUCIONES - uv.mx](https://reader036.fdocumento.com/reader036/viewer/2022070402/62c0306b8898b83eed392838/html5/thumbnails/15.jpg)
Facultad de Estadística e Informática
Agregando controladores
![Page 16: INTEGRACION DE SOLUCIONES - uv.mx](https://reader036.fdocumento.com/reader036/viewer/2022070402/62c0306b8898b83eed392838/html5/thumbnails/16.jpg)
Facultad de Estadística e Informática
Agregando controladores
![Page 17: INTEGRACION DE SOLUCIONES - uv.mx](https://reader036.fdocumento.com/reader036/viewer/2022070402/62c0306b8898b83eed392838/html5/thumbnails/17.jpg)
Facultad de Estadística e Informática
Agregando controladores
Compilar el proyecto nuevamente
![Page 18: INTEGRACION DE SOLUCIONES - uv.mx](https://reader036.fdocumento.com/reader036/viewer/2022070402/62c0306b8898b83eed392838/html5/thumbnails/18.jpg)
Facultad de Estadística e Informática
Agregando controladores
![Page 19: INTEGRACION DE SOLUCIONES - uv.mx](https://reader036.fdocumento.com/reader036/viewer/2022070402/62c0306b8898b83eed392838/html5/thumbnails/19.jpg)
Facultad de Estadística e Informática
Creación de Base de Datos
La base de datos se creará con el enfoque “CODE-FIRST” con ENTITY FRAMEWORK:
Clases C# que corresponden a tablas en la BD.
ENTITY FRAMEWORK
Base de Datos
![Page 20: INTEGRACION DE SOLUCIONES - uv.mx](https://reader036.fdocumento.com/reader036/viewer/2022070402/62c0306b8898b83eed392838/html5/thumbnails/20.jpg)
Facultad de Estadística e Informática
Creación de Base de Datos
EntityFramework
![Page 21: INTEGRACION DE SOLUCIONES - uv.mx](https://reader036.fdocumento.com/reader036/viewer/2022070402/62c0306b8898b83eed392838/html5/thumbnails/21.jpg)
Facultad de Estadística e Informática
Usando “Code First Migrations” para inicializar la base de datos
![Page 22: INTEGRACION DE SOLUCIONES - uv.mx](https://reader036.fdocumento.com/reader036/viewer/2022070402/62c0306b8898b83eed392838/html5/thumbnails/22.jpg)
Facultad de Estadística e Informática
Usando “Code First Migrations” para inicializar la base de datos
Agregará la carpeta Migrations
![Page 23: INTEGRACION DE SOLUCIONES - uv.mx](https://reader036.fdocumento.com/reader036/viewer/2022070402/62c0306b8898b83eed392838/html5/thumbnails/23.jpg)
Facultad de Estadística e Informática
Usando “Code First Migrations” para inicializar la base de datos
![Page 24: INTEGRACION DE SOLUCIONES - uv.mx](https://reader036.fdocumento.com/reader036/viewer/2022070402/62c0306b8898b83eed392838/html5/thumbnails/24.jpg)
Facultad de Estadística e Informática
Usando “Code First Migrations” para inicializar la base de datos
✓ Se agregará la carpeta Migrations✓ Abrir el archivo configuration.cs y agregar:
using BookService.Models;
![Page 25: INTEGRACION DE SOLUCIONES - uv.mx](https://reader036.fdocumento.com/reader036/viewer/2022070402/62c0306b8898b83eed392838/html5/thumbnails/25.jpg)
Facultad de Estadística e Informática
Usando “Code FirstMigrations” para inicializar la base de datos
context.Authors.AddOrUpdate(x => x.Id,new Author() { Id = 1, Name = "Jane Austen" },new Author() { Id = 2, Name = "Charles Dickens" },new Author() { Id = 3, Name = "Miguel de Cervantes" });
context.Books.AddOrUpdate(x => x.Id,new Book(){
Id = 1,Title = "Pride and Prejudice",Year = 1813,AuthorId = 1,Price = 9.99M,Genre = "Comedy of manners"
},new Book(){
Id = 2,Title = "Northanger Abbey",Year = 1817,AuthorId = 1,Price = 12.95M,Genre = "Gothic parody"
},new Book(){
Id = 3,Title = "David Copperfield",Year = 1850,AuthorId = 2,Price = 15,Genre = "Bildungsroman"
},new Book(){
Id = 4,Title = "Don Quixote",Year = 1617,AuthorId = 3,Price = 8.95M,Genre = "Picaresque"
});
Agregar el siguiente código en el método Configuration.Seed
Archivo Configuration.cs
![Page 26: INTEGRACION DE SOLUCIONES - uv.mx](https://reader036.fdocumento.com/reader036/viewer/2022070402/62c0306b8898b83eed392838/html5/thumbnails/26.jpg)
Facultad de Estadística e Informática
Usando “Code First Migrations” para inicializar la base de datos
En la consola escribir:
Add-Migration InitialUpdate-Database
![Page 27: INTEGRACION DE SOLUCIONES - uv.mx](https://reader036.fdocumento.com/reader036/viewer/2022070402/62c0306b8898b83eed392838/html5/thumbnails/27.jpg)
Facultad de Estadística e Informática
Usando “Code First Migrations” para inicializar la base de datos
I. Ver la base de datos creada en el Explorador de Objetos de SQL Server
![Page 28: INTEGRACION DE SOLUCIONES - uv.mx](https://reader036.fdocumento.com/reader036/viewer/2022070402/62c0306b8898b83eed392838/html5/thumbnails/28.jpg)
Facultad de Estadística e Informática
Usando “Code First Migrations” para inicializar la base de datos
I. Depurar en proyecto
![Page 29: INTEGRACION DE SOLUCIONES - uv.mx](https://reader036.fdocumento.com/reader036/viewer/2022070402/62c0306b8898b83eed392838/html5/thumbnails/29.jpg)
Facultad de Estadística e Informática
Usando “Code FirstMigrations” para inicializar la base de datos
![Page 30: INTEGRACION DE SOLUCIONES - uv.mx](https://reader036.fdocumento.com/reader036/viewer/2022070402/62c0306b8898b83eed392838/html5/thumbnails/30.jpg)
Facultad de Estadística e Informática
ProyectoModelo: Es la representación del lado del servidor de
los datos en el dominio del negocio (libros y autores).
View: Es la capa de presentación (HTML)
View Model: Es un objeto JavaScript que mantiene los
modelos. Es una abstracción de código de la Interfaz de
Usuario (UI). No tiene conocimiento de la
representación HTML. Representa aspectos abstractos
de la vista tales como “una lista de libros”.
![Page 31: INTEGRACION DE SOLUCIONES - uv.mx](https://reader036.fdocumento.com/reader036/viewer/2022070402/62c0306b8898b83eed392838/html5/thumbnails/31.jpg)
Facultad de Estadística e Informática
Data Transfer Objects (DTOs)
Hasta el momento la Web API expone las entidades de la base de datos al cliente.En ocasiones deseamos cambiar la forma de los datos que son enviados al usuario, por ejemplo: ▪ Esconder propiedades que no deben visualizar▪ Omitir datos para reducir el tamaño de carga ▪ Evitar vulnerabilidad en sobre exposición de datos▪ Etcétera
![Page 32: INTEGRACION DE SOLUCIONES - uv.mx](https://reader036.fdocumento.com/reader036/viewer/2022070402/62c0306b8898b83eed392838/html5/thumbnails/32.jpg)
Facultad de Estadística e Informática
Data Transfer Objects (DTOs)
Para ello se definen Data Transfer Objects(DTOs), que definen la forma en la que los datos se enviarán a través de la red.
Agregaremos dos clases DTO al proyecto BookService.
![Page 33: INTEGRACION DE SOLUCIONES - uv.mx](https://reader036.fdocumento.com/reader036/viewer/2022070402/62c0306b8898b83eed392838/html5/thumbnails/33.jpg)
Facultad de Estadística e Informática
Data Transfer Objects (DTOs)
Models->Agregar->Clase
BookDetailDTOpublic class BookDetailDTO
{public int Id { get; set; }public string Title { get; set; }public int Year { get; set; }public decimal Price { get; set; }public string AuthorName { get; set; }public string Genre { get; set; }
}
![Page 34: INTEGRACION DE SOLUCIONES - uv.mx](https://reader036.fdocumento.com/reader036/viewer/2022070402/62c0306b8898b83eed392838/html5/thumbnails/34.jpg)
Facultad de Estadística e Informática
Data Transfer Objects (DTOs)
Models->Agregar->Clase
BookDTO public class BookDTO{
public int Id { get; set; }public string Title { get; set; }public string AuthorName { get; set; }
}
![Page 35: INTEGRACION DE SOLUCIONES - uv.mx](https://reader036.fdocumento.com/reader036/viewer/2022070402/62c0306b8898b83eed392838/html5/thumbnails/35.jpg)
Facultad de Estadística e Informática
Data Transfer Objects (DTOs)
Reemplazaremos los dos métodos GET y el método POST de la clase BooksController, con el fin de retornar los DTO creados.
![Page 36: INTEGRACION DE SOLUCIONES - uv.mx](https://reader036.fdocumento.com/reader036/viewer/2022070402/62c0306b8898b83eed392838/html5/thumbnails/36.jpg)
Facultad de Estadística e Informática
Data Transfer Objects (DTOs)
// GET: api/Bookspublic IQueryable<BookDTO> GetBooks(){
var books = from b in db.Booksselect new BookDTO(){
Id = b.Id,Title = b.Title,AuthorName = b.Author.Name
};
return books;}
![Page 37: INTEGRACION DE SOLUCIONES - uv.mx](https://reader036.fdocumento.com/reader036/viewer/2022070402/62c0306b8898b83eed392838/html5/thumbnails/37.jpg)
Facultad de Estadística e Informática
Data Transfer Objects (DTOs)// GET: api/Books/5
[ResponseType(typeof(BookDetailDTO))]public async Task<IHttpActionResult> GetBook(int id){
var book = await db.Books.Include(b => b.Author).Select(b =>new BookDetailDTO(){
Id = b.Id,Title = b.Title,Year = b.Year,Price = b.Price,AuthorName = b.Author.Name,Genre = b.Genre
}).SingleOrDefaultAsync(b => b.Id == id);if (book == null){
return NotFound();}
return Ok(book);}
![Page 38: INTEGRACION DE SOLUCIONES - uv.mx](https://reader036.fdocumento.com/reader036/viewer/2022070402/62c0306b8898b83eed392838/html5/thumbnails/38.jpg)
Facultad de Estadística e Informática
Data Transfer Objects (DTOs)// POST: api/Books
[ResponseType(typeof(Book))]public async Task<IHttpActionResult> PostBook(Book book){
if (!ModelState.IsValid){
return BadRequest(ModelState);}
db.Books.Add(book);await db.SaveChangesAsync();
// New code:// Load author namedb.Entry(book).Reference(x => x.Author).Load();
var dto = new BookDTO(){
Id = book.Id,Title = book.Title,AuthorName = book.Author.Name
};
return CreatedAtRoute("DefaultApi", new { id = book.Id }, dto);}
![Page 39: INTEGRACION DE SOLUCIONES - uv.mx](https://reader036.fdocumento.com/reader036/viewer/2022070402/62c0306b8898b83eed392838/html5/thumbnails/39.jpg)
Facultad de Estadística e Informática
Creando la Vista (HTML)
A continuación crearemos la vista usando HTML y el ViewModel con JavaScript, a través del cual:✓ Se listarán los libros existentes✓ Se mostrará el detalle de un libro✓ Se agregará un libro nuevo
![Page 40: INTEGRACION DE SOLUCIONES - uv.mx](https://reader036.fdocumento.com/reader036/viewer/2022070402/62c0306b8898b83eed392838/html5/thumbnails/40.jpg)
Facultad de Estadística e Informática
Creando la Vista (HTML)
Index.html
![Page 41: INTEGRACION DE SOLUCIONES - uv.mx](https://reader036.fdocumento.com/reader036/viewer/2022070402/62c0306b8898b83eed392838/html5/thumbnails/41.jpg)
Facultad de Estadística e Informática
Creando la Vista (HTML)
Descargar código de index.html
![Page 42: INTEGRACION DE SOLUCIONES - uv.mx](https://reader036.fdocumento.com/reader036/viewer/2022070402/62c0306b8898b83eed392838/html5/thumbnails/42.jpg)
Facultad de Estadística e Informática
Creando el ViewModelEn la carpeta Scripts del proyecto→Agregamos el archivo Javascript con el nombre app.js
![Page 43: INTEGRACION DE SOLUCIONES - uv.mx](https://reader036.fdocumento.com/reader036/viewer/2022070402/62c0306b8898b83eed392838/html5/thumbnails/43.jpg)
Facultad de Estadística e Informática
Creando el ViewModel
Descargar código de app.js
![Page 44: INTEGRACION DE SOLUCIONES - uv.mx](https://reader036.fdocumento.com/reader036/viewer/2022070402/62c0306b8898b83eed392838/html5/thumbnails/44.jpg)
Facultad de Estadística e Informática
Creación del proyecto
![Page 45: INTEGRACION DE SOLUCIONES - uv.mx](https://reader036.fdocumento.com/reader036/viewer/2022070402/62c0306b8898b83eed392838/html5/thumbnails/45.jpg)
Gracias por su atención
![Page 46: INTEGRACION DE SOLUCIONES - uv.mx](https://reader036.fdocumento.com/reader036/viewer/2022070402/62c0306b8898b83eed392838/html5/thumbnails/46.jpg)
ReferenciasASP.NET MVC 4 and the Web API. (diciembre de 2012). Jaime Kurtz. aPress. Obtenido de: http://sd.blackball.lv/library/ASP.NET_MVC_4_and_the_Web_API.pdf
REST Vs Web Services (2006). Rafael Navarro. Modelado, Diseño e Implementación de Servicios Web. Obtenido de: http://users.dsic.upv.es/~rnavarro/NewWeb/docs/RestVsWebServices.pdf
RESTful Web Services(2007). Leonard Richarson & Sam Ruby. O’Really. Obtenido de: https://www.crummy.com/writing/RESTful-Web-Services/RESTful_Web_Services.pdf
Getting Started with ASP.NET Web API 2. (2015). Mike Watson. Microsoft Docs. Obtenido de: https://docs.microsoft.com/en-us/aspnet/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api