From 874ec9912b07a99a1062015a6ec8e9f287e0483b Mon Sep 17 00:00:00 2001 From: Eusebio Gomez Date: Fri, 16 Jun 2017 00:28:15 -0400 Subject: [PATCH 01/23] Create README.md --- projects/tutorial_ASP.NET_2017/README.md | 181 +++++++++++++++++++++++ 1 file changed, 181 insertions(+) create mode 100644 projects/tutorial_ASP.NET_2017/README.md diff --git a/projects/tutorial_ASP.NET_2017/README.md b/projects/tutorial_ASP.NET_2017/README.md new file mode 100644 index 0000000..9464451 --- /dev/null +++ b/projects/tutorial_ASP.NET_2017/README.md @@ -0,0 +1,181 @@ +# ASP.NET Web REST Framework + +## Introduction + +This tutorial is based on **Lab06** for its implementation in the **ASP.NET Web Framework**. We will use the **classes** previously defined on **Lab06** and then we will adapt them to the **ASP.NET Web Framework** + +For this project, we will use **[Microsoft Visual Studio Community 2017][1]** as our **IDE** + +## Before start coding + +### Work enviroment setup + +* First [download][1] and install **Microsoft Visual Studio Community 2017** in your prefered platform +* Make sure you enabled the **ASP.NET Web App Development** package when installing the IDE +* [Download][2] all the contents in **introsde/lab06/Examples/.../ehealth** from **Lab06** to your home directory + +### Create an ASP.NET Web Application template + +* When you already downloaded and installed **Microsoft Visual Studio Community 2017** open it and go to **New Project** on the **home page**. A new window will pop up +* Look at the leftmost column and deploy the **▼Templates** section +* Look for and then deploy the **▼Visual C#** section +* In the **Visual C#** content area, look for and then deploy the **▼Windows** section +* In the **Windows** area, look for and select the **Web** option +* In the middle section of the **New Project** window, select **ASP.NET Web Application (.NET Framework)** +* Choose a project name and path and then press **Accept**. At the end of this step, we will be successfully created our **ASP.NET Web Framework** template + +## Developing + +### Adding objects to the project: Classes + +* Once the project is created, look at the rightmost upperside column, and then select and right-click on the **▼Models** section +* Go to **Add** and then select **Class**. A new **Add new element** window will pop up +* In the center area of the **Add new element** window, select **Class** +* Choose **PersonCR** as name and press **Accept**. A new class called **PersonCR.cs** will be added to our project. The class **PersonCR.cs** is a **ASP.NET** implementation of the **PersonCollectionResource.java** file in **introsde/lab06/Examples/.../ehealth/resources/** +* Choose **HealthProfile** as name and press **Accept**. A new class called **HealthProfile.cs** will be added to our project. The class **HealthProfile.cs** is a **ASP.NET** implementation of the **HealthProfileResource.java** file in **introsde/lab06/Examples/.../ehealth/resources/** +* Choose **PersonController** as name and press **Accept**. A new class called **PersonController.cs** will be added to our project. The class **PersonController.cs** is a **ASP.NET** implementation of the **PersonResource.java** file in **introsde/lab06/Examples/.../ehealth/resources/**. The code in **PersonController.cs** determines the way we interact with the **classes** from the front-end + +### Classes contents: PersonCR.cs + +* The content in **PersonCR.cs** look like this: +```C# +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; +using lab06.Models; + +namespace lab06.Models +{ + public class PersonCR + { + public string firstname; + public string lastname; + public HealthProfile hProfile; + public string birthdate; + public long personId; + + public PersonCR(long personId, string fname, string lname, string birthdate, HealthProfile hp) + { + this.personId = personId; + this.firstname = fname; + this.lastname = lname; + this.birthdate = birthdate; + this.hProfile = new HealthProfile(); + } + + public PersonCR() + { + this.firstname = "Pinco"; + this.lastname = "Pallino"; + this.hProfile = new HealthProfile(); + this.personId = 1; + this.birthdate = "24/02/1998"; + } + } +} +``` + +### Classes contents: HealthProfile.cs + +* The content in **HealthProfile.cs** look like this: +```C# +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; + +namespace lab06.Models +{ + public class HealthProfile + { + private double weight; // in kg + private double height; // in m + + public HealthProfile(double weight, double height) + { + this.weight = weight; + this.height = height; + } + + public HealthProfile() + { + this.weight = 85.5; + this.height = 1.72; + } + + + } +} +``` +### Classes contents: PersonController.cs + +* **GET /api/person:** +```C# +public IEnumerable GetAllPersons() + { + return persona; + } +``` + +* **GET /api/person/{personId}:** +```C# +public IHttpActionResult GetPersonid(int id) +{ + var pers = persona.FirstOrDefault((p) => p.personId == id); + if (pers == null) + { + return NotFound(); + } + return Ok(pers); +} +``` + +* **GET /api/person/{personId}/health-profile:** +```C# + [Route("api/person/{perId}/health-profile")] + public IHttpActionResult Get(long perId) + { + var pers = persona.FirstOrDefault((p) => p.personId == perId); + + + if (pers == null) + { + return NotFound(); + + } + + return Ok(pers.hProfile); + } + +``` + +* **POST /api/person:** +```C# + +``` + +* **PUT /api/person/{personId}:** +```C# + +``` + +* **DELETE /api/person/{personId}:** +```C# + +``` + +* **PersonController.cs** entire content: +```C# + +``` + +## Finishing + +* To test our API, just click on the **▶ Play** button located in the toolbar +* We can test specific options like **GET /api/person/{personId}/health-profile** by typing **/api/person/{personId}/health-profile** next to the address in the browser address field. Example: http://localhost:50528/api/person/1/health-profile + +This document was made by Eusebio Gomez and Gabriel Pastore on June 2017 + +[1]:https://www.visualstudio.com/vs/community/ +[2]:https://github.com/eu1793/introsde/tree/master/lab06/Examples/src/introsde/rest/ehealth From 511317fe26b087afb090522887ebf66b3498383e Mon Sep 17 00:00:00 2001 From: Eusebio Gomez Date: Fri, 16 Jun 2017 01:42:56 -0400 Subject: [PATCH 02/23] Create s.s --- projects/tutorial_ASP.NET_2017/source/Models/s.s | 1 + 1 file changed, 1 insertion(+) create mode 100644 projects/tutorial_ASP.NET_2017/source/Models/s.s diff --git a/projects/tutorial_ASP.NET_2017/source/Models/s.s b/projects/tutorial_ASP.NET_2017/source/Models/s.s new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/projects/tutorial_ASP.NET_2017/source/Models/s.s @@ -0,0 +1 @@ + From 3b2e0f1070db1bd53509ee226a8ed42a44aa9089 Mon Sep 17 00:00:00 2001 From: Eusebio Gomez Date: Fri, 16 Jun 2017 01:43:27 -0400 Subject: [PATCH 03/23] Add files via upload --- .../source/Models/AccountViewModels.cs | 112 ++++++++++++++++++ .../source/Models/HealthProfile.cs | 52 ++++++++ .../source/Models/IdentityModels.cs | 33 ++++++ .../source/Models/ManageViewModels.cs | 86 ++++++++++++++ .../source/Models/PersonCR.cs | 98 +++++++++++++++ 5 files changed, 381 insertions(+) create mode 100644 projects/tutorial_ASP.NET_2017/source/Models/AccountViewModels.cs create mode 100644 projects/tutorial_ASP.NET_2017/source/Models/HealthProfile.cs create mode 100644 projects/tutorial_ASP.NET_2017/source/Models/IdentityModels.cs create mode 100644 projects/tutorial_ASP.NET_2017/source/Models/ManageViewModels.cs create mode 100644 projects/tutorial_ASP.NET_2017/source/Models/PersonCR.cs diff --git a/projects/tutorial_ASP.NET_2017/source/Models/AccountViewModels.cs b/projects/tutorial_ASP.NET_2017/source/Models/AccountViewModels.cs new file mode 100644 index 0000000..5f80f87 --- /dev/null +++ b/projects/tutorial_ASP.NET_2017/source/Models/AccountViewModels.cs @@ -0,0 +1,112 @@ +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; + +namespace lab06.Models +{ + public class ExternalLoginConfirmationViewModel + { + [Required] + [Display(Name = "Correo electrónico")] + public string Email { get; set; } + } + + public class ExternalLoginListViewModel + { + public string ReturnUrl { get; set; } + } + + public class SendCodeViewModel + { + public string SelectedProvider { get; set; } + public ICollection Providers { get; set; } + public string ReturnUrl { get; set; } + public bool RememberMe { get; set; } + } + + public class VerifyCodeViewModel + { + [Required] + public string Provider { get; set; } + + [Required] + [Display(Name = "Código")] + public string Code { get; set; } + public string ReturnUrl { get; set; } + + [Display(Name = "¿Recordar este explorador?")] + public bool RememberBrowser { get; set; } + + public bool RememberMe { get; set; } + } + + public class ForgotViewModel + { + [Required] + [Display(Name = "Correo electrónico")] + public string Email { get; set; } + } + + public class LoginViewModel + { + [Required] + [Display(Name = "Correo electrónico")] + [EmailAddress] + public string Email { get; set; } + + [Required] + [DataType(DataType.Password)] + [Display(Name = "Contraseña")] + public string Password { get; set; } + + [Display(Name = "¿Recordar cuenta?")] + public bool RememberMe { get; set; } + } + + public class RegisterViewModel + { + [Required] + [EmailAddress] + [Display(Name = "Correo electrónico")] + public string Email { get; set; } + + [Required] + [StringLength(100, ErrorMessage = "El número de caracteres de {0} debe ser al menos {2}.", MinimumLength = 6)] + [DataType(DataType.Password)] + [Display(Name = "Contraseña")] + public string Password { get; set; } + + [DataType(DataType.Password)] + [Display(Name = "Confirmar contraseña")] + [Compare("Password", ErrorMessage = "La contraseña y la contraseña de confirmación no coinciden.")] + public string ConfirmPassword { get; set; } + } + + public class ResetPasswordViewModel + { + [Required] + [EmailAddress] + [Display(Name = "Correo electrónico")] + public string Email { get; set; } + + [Required] + [StringLength(100, ErrorMessage = "El número de caracteres de {0} debe ser al menos {2}.", MinimumLength = 6)] + [DataType(DataType.Password)] + [Display(Name = "Contraseña")] + public string Password { get; set; } + + [DataType(DataType.Password)] + [Display(Name = "Confirmar contraseña")] + [Compare("Password", ErrorMessage = "La contraseña y la contraseña de confirmación no coinciden.")] + public string ConfirmPassword { get; set; } + + public string Code { get; set; } + } + + public class ForgotPasswordViewModel + { + [Required] + [EmailAddress] + [Display(Name = "Correo electrónico")] + public string Email { get; set; } + } +} diff --git a/projects/tutorial_ASP.NET_2017/source/Models/HealthProfile.cs b/projects/tutorial_ASP.NET_2017/source/Models/HealthProfile.cs new file mode 100644 index 0000000..396eac9 --- /dev/null +++ b/projects/tutorial_ASP.NET_2017/source/Models/HealthProfile.cs @@ -0,0 +1,52 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; + +namespace lab06.Models +{ + public class HealthProfile + { + public double weight; // in kg + public double height; // in m + + public HealthProfile(double weight, double height) + { + this.weight = weight; + this.height = height; + } + + public HealthProfile() + { + this.weight = 85.5; + this.height = 1.72; + } + + public void setWeight(double weight) + { + this.weight = weight; + } + + public double getHeight() + { + return height; + } + + public void setHeight(double height) + { + this.height = height; + } + + public double getBMI() + { + return this.weight / (Math.Pow(this.height, 2)); + } + + public String toString() + { + return "{" + this.height + "," + this.weight + "," + this.getBMI() + "," + "}"; + } + + + } +} \ No newline at end of file diff --git a/projects/tutorial_ASP.NET_2017/source/Models/IdentityModels.cs b/projects/tutorial_ASP.NET_2017/source/Models/IdentityModels.cs new file mode 100644 index 0000000..af673ad --- /dev/null +++ b/projects/tutorial_ASP.NET_2017/source/Models/IdentityModels.cs @@ -0,0 +1,33 @@ +using System.Data.Entity; +using System.Security.Claims; +using System.Threading.Tasks; +using Microsoft.AspNet.Identity; +using Microsoft.AspNet.Identity.EntityFramework; + +namespace lab06.Models +{ + // Puede agregar datos del perfil del usuario agregando más propiedades a la clase ApplicationUser. Para más información, visite http://go.microsoft.com/fwlink/?LinkID=317594. + public class ApplicationUser : IdentityUser + { + public async Task GenerateUserIdentityAsync(UserManager manager) + { + // Tenga en cuenta que el valor de authenticationType debe coincidir con el definido en CookieAuthenticationOptions.AuthenticationType + var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); + // Agregar aquí notificaciones personalizadas de usuario + return userIdentity; + } + } + + public class ApplicationDbContext : IdentityDbContext + { + public ApplicationDbContext() + : base("DefaultConnection", throwIfV1Schema: false) + { + } + + public static ApplicationDbContext Create() + { + return new ApplicationDbContext(); + } + } +} \ No newline at end of file diff --git a/projects/tutorial_ASP.NET_2017/source/Models/ManageViewModels.cs b/projects/tutorial_ASP.NET_2017/source/Models/ManageViewModels.cs new file mode 100644 index 0000000..9673162 --- /dev/null +++ b/projects/tutorial_ASP.NET_2017/source/Models/ManageViewModels.cs @@ -0,0 +1,86 @@ +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using Microsoft.AspNet.Identity; +using Microsoft.Owin.Security; + +namespace lab06.Models +{ + public class IndexViewModel + { + public bool HasPassword { get; set; } + public IList Logins { get; set; } + public string PhoneNumber { get; set; } + public bool TwoFactor { get; set; } + public bool BrowserRemembered { get; set; } + } + + public class ManageLoginsViewModel + { + public IList CurrentLogins { get; set; } + public IList OtherLogins { get; set; } + } + + public class FactorViewModel + { + public string Purpose { get; set; } + } + + public class SetPasswordViewModel + { + [Required] + [StringLength(100, ErrorMessage = "{0} debe tener al menos {2} caracteres de longitud.", MinimumLength = 6)] + [DataType(DataType.Password)] + [Display(Name = "Contraseña nueva")] + public string NewPassword { get; set; } + + [DataType(DataType.Password)] + [Display(Name = "Confirme la contraseña nueva")] + [Compare("NewPassword", ErrorMessage = "La contraseña nueva y la contraseña de confirmación no coinciden.")] + public string ConfirmPassword { get; set; } + } + + public class ChangePasswordViewModel + { + [Required] + [DataType(DataType.Password)] + [Display(Name = "Contraseña actual")] + public string OldPassword { get; set; } + + [Required] + [StringLength(100, ErrorMessage = "{0} debe tener al menos {2} caracteres de longitud.", MinimumLength = 6)] + [DataType(DataType.Password)] + [Display(Name = "Contraseña nueva")] + public string NewPassword { get; set; } + + [DataType(DataType.Password)] + [Display(Name = "Confirme la contraseña nueva")] + [Compare("NewPassword", ErrorMessage = "La contraseña nueva y la contraseña de confirmación no coinciden.")] + public string ConfirmPassword { get; set; } + } + + public class AddPhoneNumberViewModel + { + [Required] + [Phone] + [Display(Name = "Número de teléfono")] + public string Number { get; set; } + } + + public class VerifyPhoneNumberViewModel + { + [Required] + [Display(Name = "Código")] + public string Code { get; set; } + + [Required] + [Phone] + [Display(Name = "Número de teléfono")] + public string PhoneNumber { get; set; } + } + + public class ConfigureTwoFactorViewModel + { + public string SelectedProvider { get; set; } + public ICollection Providers { get; set; } + } +} \ No newline at end of file diff --git a/projects/tutorial_ASP.NET_2017/source/Models/PersonCR.cs b/projects/tutorial_ASP.NET_2017/source/Models/PersonCR.cs new file mode 100644 index 0000000..337ccad --- /dev/null +++ b/projects/tutorial_ASP.NET_2017/source/Models/PersonCR.cs @@ -0,0 +1,98 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; +using lab06.Models; + +namespace lab06.Models +{ + public class PersonCR + { + public string firstname; + public string lastname; + public HealthProfile hProfile; + public string birthdate; + public long personId; + + public PersonCR(long personId, String fname, String lname, String birthdate, HealthProfile hp) + { + this.setPersonId(personId); + this.setFirstname(fname); + this.setLastname(lname); + this.setBirthdate(birthdate); + this.hProfile = hp; + } + + public PersonCR(long personId, String fname, String lname, String birthdate) + { + this.setPersonId(personId); + this.setFirstname(fname); + this.setLastname(lname); + this.setBirthdate(birthdate); + this.hProfile = new HealthProfile(); + } + + public PersonCR() + { + this.firstname = "Pinco"; + this.lastname = "Pallino"; + + HealthProfile hp = new HealthProfile(); + + this.hProfile = hp; + // setting personId to a random number between 1 and 9999 + Random rnd = new Random(); + int nro = rnd.Next(9999); + //this.personId =nro; // Solution to Exercise #01-1d + this.personId = 1; + this.birthdate = "11/11/2011"; + } + public void delete() + { + + } + + public String getFirstname() + { + return firstname; + } + public void setFirstname(String firstname) + { + this.firstname = firstname; + } + public String getLastname() + { + return lastname; + } + public void setLastname(String lastname) + { + this.lastname = lastname; + } + public HealthProfile getHProfile() + { + return hProfile; + } + public void setHProfile(HealthProfile hProfile) + { + this.hProfile = hProfile; + } + public String getBirthdate() + { + return birthdate; + } + public void setBirthdate(String birthdate) + { + this.birthdate = birthdate; + } + public long getPersonId() + { + return personId; + } + public void setPersonId(long personId) + { + this.personId = personId; + } + + + } +} \ No newline at end of file From 8b1b4b54cb3470bfe20540b27242821359e6ca2e Mon Sep 17 00:00:00 2001 From: Eusebio Gomez Date: Fri, 16 Jun 2017 01:43:51 -0400 Subject: [PATCH 04/23] Delete s.s --- projects/tutorial_ASP.NET_2017/source/Models/s.s | 1 - 1 file changed, 1 deletion(-) delete mode 100644 projects/tutorial_ASP.NET_2017/source/Models/s.s diff --git a/projects/tutorial_ASP.NET_2017/source/Models/s.s b/projects/tutorial_ASP.NET_2017/source/Models/s.s deleted file mode 100644 index 8b13789..0000000 --- a/projects/tutorial_ASP.NET_2017/source/Models/s.s +++ /dev/null @@ -1 +0,0 @@ - From 5d23becfff0de555895f6f1f0314771e1e46843b Mon Sep 17 00:00:00 2001 From: Eusebio Gomez Date: Fri, 16 Jun 2017 01:44:21 -0400 Subject: [PATCH 05/23] Create s.s --- projects/tutorial_ASP.NET_2017/source/Controller/s.s | 1 + 1 file changed, 1 insertion(+) create mode 100644 projects/tutorial_ASP.NET_2017/source/Controller/s.s diff --git a/projects/tutorial_ASP.NET_2017/source/Controller/s.s b/projects/tutorial_ASP.NET_2017/source/Controller/s.s new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/projects/tutorial_ASP.NET_2017/source/Controller/s.s @@ -0,0 +1 @@ + From 3e04a15884db6081dac68cd30f94b84cb59ada53 Mon Sep 17 00:00:00 2001 From: Eusebio Gomez Date: Fri, 16 Jun 2017 01:44:46 -0400 Subject: [PATCH 06/23] Add files via upload --- .../source/Controller/AccountController.cs | 485 ++++++++++++++++++ .../source/Controller/HealthPController.cs | 13 + .../source/Controller/HomeController.cs | 30 ++ .../source/Controller/ManageController.cs | 389 ++++++++++++++ .../source/Controller/PersonController.cs | 99 ++++ 5 files changed, 1016 insertions(+) create mode 100644 projects/tutorial_ASP.NET_2017/source/Controller/AccountController.cs create mode 100644 projects/tutorial_ASP.NET_2017/source/Controller/HealthPController.cs create mode 100644 projects/tutorial_ASP.NET_2017/source/Controller/HomeController.cs create mode 100644 projects/tutorial_ASP.NET_2017/source/Controller/ManageController.cs create mode 100644 projects/tutorial_ASP.NET_2017/source/Controller/PersonController.cs diff --git a/projects/tutorial_ASP.NET_2017/source/Controller/AccountController.cs b/projects/tutorial_ASP.NET_2017/source/Controller/AccountController.cs new file mode 100644 index 0000000..199a67d --- /dev/null +++ b/projects/tutorial_ASP.NET_2017/source/Controller/AccountController.cs @@ -0,0 +1,485 @@ +using System; +using System.Globalization; +using System.Linq; +using System.Security.Claims; +using System.Threading.Tasks; +using System.Web; +using System.Web.Mvc; +using Microsoft.AspNet.Identity; +using Microsoft.AspNet.Identity.Owin; +using Microsoft.Owin.Security; +using lab06.Models; + +namespace lab06.Controllers +{ + [Authorize] + public class AccountController : Controller + { + private ApplicationSignInManager _signInManager; + private ApplicationUserManager _userManager; + + public AccountController() + { + } + + public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager ) + { + UserManager = userManager; + SignInManager = signInManager; + } + + public ApplicationSignInManager SignInManager + { + get + { + return _signInManager ?? HttpContext.GetOwinContext().Get(); + } + private set + { + _signInManager = value; + } + } + + public ApplicationUserManager UserManager + { + get + { + return _userManager ?? HttpContext.GetOwinContext().GetUserManager(); + } + private set + { + _userManager = value; + } + } + + // + // GET: /Account/Login + [AllowAnonymous] + public ActionResult Login(string returnUrl) + { + ViewBag.ReturnUrl = returnUrl; + return View(); + } + + // + // POST: /Account/Login + [HttpPost] + [AllowAnonymous] + [ValidateAntiForgeryToken] + public async Task Login(LoginViewModel model, string returnUrl) + { + if (!ModelState.IsValid) + { + return View(model); + } + + // No cuenta los errores de inicio de sesión para el bloqueo de la cuenta + // Para permitir que los errores de contraseña desencadenen el bloqueo de la cuenta, cambie a shouldLockout: true + var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false); + switch (result) + { + case SignInStatus.Success: + return RedirectToLocal(returnUrl); + case SignInStatus.LockedOut: + return View("Lockout"); + case SignInStatus.RequiresVerification: + return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }); + case SignInStatus.Failure: + default: + ModelState.AddModelError("", "Intento de inicio de sesión no válido."); + return View(model); + } + } + + // + // GET: /Account/VerifyCode + [AllowAnonymous] + public async Task VerifyCode(string provider, string returnUrl, bool rememberMe) + { + // Requerir que el usuario haya iniciado sesión con nombre de usuario y contraseña o inicio de sesión externo + if (!await SignInManager.HasBeenVerifiedAsync()) + { + return View("Error"); + } + return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe }); + } + + // + // POST: /Account/VerifyCode + [HttpPost] + [AllowAnonymous] + [ValidateAntiForgeryToken] + public async Task VerifyCode(VerifyCodeViewModel model) + { + if (!ModelState.IsValid) + { + return View(model); + } + + // El código siguiente protege de los ataques por fuerza bruta a los códigos de dos factores. + // Si un usuario introduce códigos incorrectos durante un intervalo especificado de tiempo, la cuenta del usuario + // se bloqueará durante un período de tiempo especificado. + // Puede configurar el bloqueo de la cuenta en IdentityConfig + var result = await SignInManager.TwoFactorSignInAsync(model.Provider, model.Code, isPersistent: model.RememberMe, rememberBrowser: model.RememberBrowser); + switch (result) + { + case SignInStatus.Success: + return RedirectToLocal(model.ReturnUrl); + case SignInStatus.LockedOut: + return View("Lockout"); + case SignInStatus.Failure: + default: + ModelState.AddModelError("", "Código no válido."); + return View(model); + } + } + + // + // GET: /Account/Register + [AllowAnonymous] + public ActionResult Register() + { + return View(); + } + + // + // POST: /Account/Register + [HttpPost] + [AllowAnonymous] + [ValidateAntiForgeryToken] + public async Task Register(RegisterViewModel model) + { + if (ModelState.IsValid) + { + var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; + var result = await UserManager.CreateAsync(user, model.Password); + if (result.Succeeded) + { + await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false); + + // Para obtener más información sobre cómo habilitar la confirmación de cuenta y el restablecimiento de contraseña, visite http://go.microsoft.com/fwlink/?LinkID=320771 + // Enviar correo electrónico con este vínculo + // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); + // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); + // await UserManager.SendEmailAsync(user.Id, "Confirmar cuenta", "Para confirmar la cuenta, haga clic aquí"); + + return RedirectToAction("Index", "Home"); + } + AddErrors(result); + } + + // Si llegamos a este punto, es que se ha producido un error y volvemos a mostrar el formulario + return View(model); + } + + // + // GET: /Account/ConfirmEmail + [AllowAnonymous] + public async Task ConfirmEmail(string userId, string code) + { + if (userId == null || code == null) + { + return View("Error"); + } + var result = await UserManager.ConfirmEmailAsync(userId, code); + return View(result.Succeeded ? "ConfirmEmail" : "Error"); + } + + // + // GET: /Account/ForgotPassword + [AllowAnonymous] + public ActionResult ForgotPassword() + { + return View(); + } + + // + // POST: /Account/ForgotPassword + [HttpPost] + [AllowAnonymous] + [ValidateAntiForgeryToken] + public async Task ForgotPassword(ForgotPasswordViewModel model) + { + if (ModelState.IsValid) + { + var user = await UserManager.FindByNameAsync(model.Email); + if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id))) + { + // No revelar que el usuario no existe o que no está confirmado + return View("ForgotPasswordConfirmation"); + } + + // Para obtener más información sobre cómo habilitar la confirmación de cuenta y el restablecimiento de contraseña, visite http://go.microsoft.com/fwlink/?LinkID=320771 + // Enviar correo electrónico con este vínculo + // string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id); + // var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); + // await UserManager.SendEmailAsync(user.Id, "Restablecer contraseña", "Para restablecer la contraseña, haga clic aquí"); + // return RedirectToAction("ForgotPasswordConfirmation", "Account"); + } + + // Si llegamos a este punto, es que se ha producido un error y volvemos a mostrar el formulario + return View(model); + } + + // + // GET: /Account/ForgotPasswordConfirmation + [AllowAnonymous] + public ActionResult ForgotPasswordConfirmation() + { + return View(); + } + + // + // GET: /Account/ResetPassword + [AllowAnonymous] + public ActionResult ResetPassword(string code) + { + return code == null ? View("Error") : View(); + } + + // + // POST: /Account/ResetPassword + [HttpPost] + [AllowAnonymous] + [ValidateAntiForgeryToken] + public async Task ResetPassword(ResetPasswordViewModel model) + { + if (!ModelState.IsValid) + { + return View(model); + } + var user = await UserManager.FindByNameAsync(model.Email); + if (user == null) + { + // No revelar que el usuario no existe + return RedirectToAction("ResetPasswordConfirmation", "Account"); + } + var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password); + if (result.Succeeded) + { + return RedirectToAction("ResetPasswordConfirmation", "Account"); + } + AddErrors(result); + return View(); + } + + // + // GET: /Account/ResetPasswordConfirmation + [AllowAnonymous] + public ActionResult ResetPasswordConfirmation() + { + return View(); + } + + // + // POST: /Account/ExternalLogin + [HttpPost] + [AllowAnonymous] + [ValidateAntiForgeryToken] + public ActionResult ExternalLogin(string provider, string returnUrl) + { + // Solicitar redireccionamiento al proveedor de inicio de sesión externo + return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl })); + } + + // + // GET: /Account/SendCode + [AllowAnonymous] + public async Task SendCode(string returnUrl, bool rememberMe) + { + var userId = await SignInManager.GetVerifiedUserIdAsync(); + if (userId == null) + { + return View("Error"); + } + var userFactors = await UserManager.GetValidTwoFactorProvidersAsync(userId); + var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList(); + return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe }); + } + + // + // POST: /Account/SendCode + [HttpPost] + [AllowAnonymous] + [ValidateAntiForgeryToken] + public async Task SendCode(SendCodeViewModel model) + { + if (!ModelState.IsValid) + { + return View(); + } + + // Generar el token y enviarlo + if (!await SignInManager.SendTwoFactorCodeAsync(model.SelectedProvider)) + { + return View("Error"); + } + return RedirectToAction("VerifyCode", new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe }); + } + + // + // GET: /Account/ExternalLoginCallback + [AllowAnonymous] + public async Task ExternalLoginCallback(string returnUrl) + { + var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(); + if (loginInfo == null) + { + return RedirectToAction("Login"); + } + + // Si el usuario ya tiene un inicio de sesión, iniciar sesión del usuario con este proveedor de inicio de sesión externo + var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false); + switch (result) + { + case SignInStatus.Success: + return RedirectToLocal(returnUrl); + case SignInStatus.LockedOut: + return View("Lockout"); + case SignInStatus.RequiresVerification: + return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false }); + case SignInStatus.Failure: + default: + // Si el usuario no tiene ninguna cuenta, solicitar que cree una + ViewBag.ReturnUrl = returnUrl; + ViewBag.LoginProvider = loginInfo.Login.LoginProvider; + return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email }); + } + } + + // + // POST: /Account/ExternalLoginConfirmation + [HttpPost] + [AllowAnonymous] + [ValidateAntiForgeryToken] + public async Task ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) + { + if (User.Identity.IsAuthenticated) + { + return RedirectToAction("Index", "Manage"); + } + + if (ModelState.IsValid) + { + // Obtener datos del usuario del proveedor de inicio de sesión externo + var info = await AuthenticationManager.GetExternalLoginInfoAsync(); + if (info == null) + { + return View("ExternalLoginFailure"); + } + var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; + var result = await UserManager.CreateAsync(user); + if (result.Succeeded) + { + result = await UserManager.AddLoginAsync(user.Id, info.Login); + if (result.Succeeded) + { + await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); + return RedirectToLocal(returnUrl); + } + } + AddErrors(result); + } + + ViewBag.ReturnUrl = returnUrl; + return View(model); + } + + // + // POST: /Account/LogOff + [HttpPost] + [ValidateAntiForgeryToken] + public ActionResult LogOff() + { + AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie); + return RedirectToAction("Index", "Home"); + } + + // + // GET: /Account/ExternalLoginFailure + [AllowAnonymous] + public ActionResult ExternalLoginFailure() + { + return View(); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + if (_userManager != null) + { + _userManager.Dispose(); + _userManager = null; + } + + if (_signInManager != null) + { + _signInManager.Dispose(); + _signInManager = null; + } + } + + base.Dispose(disposing); + } + + #region Aplicaciones auxiliares + // Se usa para la protección XSRF al agregar inicios de sesión externos + private const string XsrfKey = "XsrfId"; + + private IAuthenticationManager AuthenticationManager + { + get + { + return HttpContext.GetOwinContext().Authentication; + } + } + + private void AddErrors(IdentityResult result) + { + foreach (var error in result.Errors) + { + ModelState.AddModelError("", error); + } + } + + private ActionResult RedirectToLocal(string returnUrl) + { + if (Url.IsLocalUrl(returnUrl)) + { + return Redirect(returnUrl); + } + return RedirectToAction("Index", "Home"); + } + + internal class ChallengeResult : HttpUnauthorizedResult + { + public ChallengeResult(string provider, string redirectUri) + : this(provider, redirectUri, null) + { + } + + public ChallengeResult(string provider, string redirectUri, string userId) + { + LoginProvider = provider; + RedirectUri = redirectUri; + UserId = userId; + } + + public string LoginProvider { get; set; } + public string RedirectUri { get; set; } + public string UserId { get; set; } + + public override void ExecuteResult(ControllerContext context) + { + var properties = new AuthenticationProperties { RedirectUri = RedirectUri }; + if (UserId != null) + { + properties.Dictionary[XsrfKey] = UserId; + } + context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider); + } + } + #endregion + } +} \ No newline at end of file diff --git a/projects/tutorial_ASP.NET_2017/source/Controller/HealthPController.cs b/projects/tutorial_ASP.NET_2017/source/Controller/HealthPController.cs new file mode 100644 index 0000000..c941701 --- /dev/null +++ b/projects/tutorial_ASP.NET_2017/source/Controller/HealthPController.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Web.Http; + +namespace lab06.Controllers +{ + public class HealthPController : ApiController + { + } +} diff --git a/projects/tutorial_ASP.NET_2017/source/Controller/HomeController.cs b/projects/tutorial_ASP.NET_2017/source/Controller/HomeController.cs new file mode 100644 index 0000000..7b3a85d --- /dev/null +++ b/projects/tutorial_ASP.NET_2017/source/Controller/HomeController.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; +using System.Web.Mvc; + +namespace lab06.Controllers +{ + public class HomeController : Controller + { + public ActionResult Index() + { + return View(); + } + + public ActionResult About() + { + ViewBag.Message = "Your application description page."; + + return View(); + } + + public ActionResult Contact() + { + ViewBag.Message = "Your contact page."; + + return View(); + } + } +} \ No newline at end of file diff --git a/projects/tutorial_ASP.NET_2017/source/Controller/ManageController.cs b/projects/tutorial_ASP.NET_2017/source/Controller/ManageController.cs new file mode 100644 index 0000000..8b9e1ac --- /dev/null +++ b/projects/tutorial_ASP.NET_2017/source/Controller/ManageController.cs @@ -0,0 +1,389 @@ +using System; +using System.Linq; +using System.Threading.Tasks; +using System.Web; +using System.Web.Mvc; +using Microsoft.AspNet.Identity; +using Microsoft.AspNet.Identity.Owin; +using Microsoft.Owin.Security; +using lab06.Models; + +namespace lab06.Controllers +{ + [Authorize] + public class ManageController : Controller + { + private ApplicationSignInManager _signInManager; + private ApplicationUserManager _userManager; + + public ManageController() + { + } + + public ManageController(ApplicationUserManager userManager, ApplicationSignInManager signInManager) + { + UserManager = userManager; + SignInManager = signInManager; + } + + public ApplicationSignInManager SignInManager + { + get + { + return _signInManager ?? HttpContext.GetOwinContext().Get(); + } + private set + { + _signInManager = value; + } + } + + public ApplicationUserManager UserManager + { + get + { + return _userManager ?? HttpContext.GetOwinContext().GetUserManager(); + } + private set + { + _userManager = value; + } + } + + // + // GET: /Manage/Index + public async Task Index(ManageMessageId? message) + { + ViewBag.StatusMessage = + message == ManageMessageId.ChangePasswordSuccess ? "Su contraseña se ha cambiado." + : message == ManageMessageId.SetPasswordSuccess ? "Su contraseña se ha establecido." + : message == ManageMessageId.SetTwoFactorSuccess ? "Su proveedor de autenticación de dos factores se ha establecido." + : message == ManageMessageId.Error ? "Se ha producido un error." + : message == ManageMessageId.AddPhoneSuccess ? "Se ha agregado su número de teléfono." + : message == ManageMessageId.RemovePhoneSuccess ? "Se ha quitado su número de teléfono." + : ""; + + var userId = User.Identity.GetUserId(); + var model = new IndexViewModel + { + HasPassword = HasPassword(), + PhoneNumber = await UserManager.GetPhoneNumberAsync(userId), + TwoFactor = await UserManager.GetTwoFactorEnabledAsync(userId), + Logins = await UserManager.GetLoginsAsync(userId), + BrowserRemembered = await AuthenticationManager.TwoFactorBrowserRememberedAsync(userId) + }; + return View(model); + } + + // + // POST: /Manage/RemoveLogin + [HttpPost] + [ValidateAntiForgeryToken] + public async Task RemoveLogin(string loginProvider, string providerKey) + { + ManageMessageId? message; + var result = await UserManager.RemoveLoginAsync(User.Identity.GetUserId(), new UserLoginInfo(loginProvider, providerKey)); + if (result.Succeeded) + { + var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); + if (user != null) + { + await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); + } + message = ManageMessageId.RemoveLoginSuccess; + } + else + { + message = ManageMessageId.Error; + } + return RedirectToAction("ManageLogins", new { Message = message }); + } + + // + // GET: /Manage/AddPhoneNumber + public ActionResult AddPhoneNumber() + { + return View(); + } + + // + // POST: /Manage/AddPhoneNumber + [HttpPost] + [ValidateAntiForgeryToken] + public async Task AddPhoneNumber(AddPhoneNumberViewModel model) + { + if (!ModelState.IsValid) + { + return View(model); + } + // Generar el token y enviarlo + var code = await UserManager.GenerateChangePhoneNumberTokenAsync(User.Identity.GetUserId(), model.Number); + if (UserManager.SmsService != null) + { + var message = new IdentityMessage + { + Destination = model.Number, + Body = "Su código de seguridad es: " + code + }; + await UserManager.SmsService.SendAsync(message); + } + return RedirectToAction("VerifyPhoneNumber", new { PhoneNumber = model.Number }); + } + + // + // POST: /Manage/EnableTwoFactorAuthentication + [HttpPost] + [ValidateAntiForgeryToken] + public async Task EnableTwoFactorAuthentication() + { + await UserManager.SetTwoFactorEnabledAsync(User.Identity.GetUserId(), true); + var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); + if (user != null) + { + await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); + } + return RedirectToAction("Index", "Manage"); + } + + // + // POST: /Manage/DisableTwoFactorAuthentication + [HttpPost] + [ValidateAntiForgeryToken] + public async Task DisableTwoFactorAuthentication() + { + await UserManager.SetTwoFactorEnabledAsync(User.Identity.GetUserId(), false); + var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); + if (user != null) + { + await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); + } + return RedirectToAction("Index", "Manage"); + } + + // + // GET: /Manage/VerifyPhoneNumber + public async Task VerifyPhoneNumber(string phoneNumber) + { + var code = await UserManager.GenerateChangePhoneNumberTokenAsync(User.Identity.GetUserId(), phoneNumber); + // Enviar un SMS a través del proveedor de SMS para verificar el número de teléfono + return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber }); + } + + // + // POST: /Manage/VerifyPhoneNumber + [HttpPost] + [ValidateAntiForgeryToken] + public async Task VerifyPhoneNumber(VerifyPhoneNumberViewModel model) + { + if (!ModelState.IsValid) + { + return View(model); + } + var result = await UserManager.ChangePhoneNumberAsync(User.Identity.GetUserId(), model.PhoneNumber, model.Code); + if (result.Succeeded) + { + var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); + if (user != null) + { + await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); + } + return RedirectToAction("Index", new { Message = ManageMessageId.AddPhoneSuccess }); + } + // Si llegamos a este punto, es que se ha producido un error, volvemos a mostrar el formulario + ModelState.AddModelError("", "No se ha podido comprobar el teléfono"); + return View(model); + } + + // + // POST: /Manage/RemovePhoneNumber + [HttpPost] + [ValidateAntiForgeryToken] + public async Task RemovePhoneNumber() + { + var result = await UserManager.SetPhoneNumberAsync(User.Identity.GetUserId(), null); + if (!result.Succeeded) + { + return RedirectToAction("Index", new { Message = ManageMessageId.Error }); + } + var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); + if (user != null) + { + await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); + } + return RedirectToAction("Index", new { Message = ManageMessageId.RemovePhoneSuccess }); + } + + // + // GET: /Manage/ChangePassword + public ActionResult ChangePassword() + { + return View(); + } + + // + // POST: /Manage/ChangePassword + [HttpPost] + [ValidateAntiForgeryToken] + public async Task ChangePassword(ChangePasswordViewModel model) + { + if (!ModelState.IsValid) + { + return View(model); + } + var result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword); + if (result.Succeeded) + { + var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); + if (user != null) + { + await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); + } + return RedirectToAction("Index", new { Message = ManageMessageId.ChangePasswordSuccess }); + } + AddErrors(result); + return View(model); + } + + // + // GET: /Manage/SetPassword + public ActionResult SetPassword() + { + return View(); + } + + // + // POST: /Manage/SetPassword + [HttpPost] + [ValidateAntiForgeryToken] + public async Task SetPassword(SetPasswordViewModel model) + { + if (ModelState.IsValid) + { + var result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword); + if (result.Succeeded) + { + var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); + if (user != null) + { + await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); + } + return RedirectToAction("Index", new { Message = ManageMessageId.SetPasswordSuccess }); + } + AddErrors(result); + } + + // Si llegamos a este punto, es que se ha producido un error, volvemos a mostrar el formulario + return View(model); + } + + // + // GET: /Manage/ManageLogins + public async Task ManageLogins(ManageMessageId? message) + { + ViewBag.StatusMessage = + message == ManageMessageId.RemoveLoginSuccess ? "Se ha quitado el inicio de sesión externo." + : message == ManageMessageId.Error ? "Se ha producido un error." + : ""; + var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); + if (user == null) + { + return View("Error"); + } + var userLogins = await UserManager.GetLoginsAsync(User.Identity.GetUserId()); + var otherLogins = AuthenticationManager.GetExternalAuthenticationTypes().Where(auth => userLogins.All(ul => auth.AuthenticationType != ul.LoginProvider)).ToList(); + ViewBag.ShowRemoveButton = user.PasswordHash != null || userLogins.Count > 1; + return View(new ManageLoginsViewModel + { + CurrentLogins = userLogins, + OtherLogins = otherLogins + }); + } + + // + // POST: /Manage/LinkLogin + [HttpPost] + [ValidateAntiForgeryToken] + public ActionResult LinkLogin(string provider) + { + // Solicitar la redirección al proveedor de inicio de sesión externo para vincular un inicio de sesión para el usuario actual + return new AccountController.ChallengeResult(provider, Url.Action("LinkLoginCallback", "Manage"), User.Identity.GetUserId()); + } + + // + // GET: /Manage/LinkLoginCallback + public async Task LinkLoginCallback() + { + var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(XsrfKey, User.Identity.GetUserId()); + if (loginInfo == null) + { + return RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error }); + } + var result = await UserManager.AddLoginAsync(User.Identity.GetUserId(), loginInfo.Login); + return result.Succeeded ? RedirectToAction("ManageLogins") : RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error }); + } + + protected override void Dispose(bool disposing) + { + if (disposing && _userManager != null) + { + _userManager.Dispose(); + _userManager = null; + } + + base.Dispose(disposing); + } + +#region Aplicaciones auxiliares + // Se usan para protección XSRF al agregar inicios de sesión externos + private const string XsrfKey = "XsrfId"; + + private IAuthenticationManager AuthenticationManager + { + get + { + return HttpContext.GetOwinContext().Authentication; + } + } + + private void AddErrors(IdentityResult result) + { + foreach (var error in result.Errors) + { + ModelState.AddModelError("", error); + } + } + + private bool HasPassword() + { + var user = UserManager.FindById(User.Identity.GetUserId()); + if (user != null) + { + return user.PasswordHash != null; + } + return false; + } + + private bool HasPhoneNumber() + { + var user = UserManager.FindById(User.Identity.GetUserId()); + if (user != null) + { + return user.PhoneNumber != null; + } + return false; + } + + public enum ManageMessageId + { + AddPhoneSuccess, + ChangePasswordSuccess, + SetTwoFactorSuccess, + SetPasswordSuccess, + RemoveLoginSuccess, + RemovePhoneSuccess, + Error + } + +#endregion + } +} \ No newline at end of file diff --git a/projects/tutorial_ASP.NET_2017/source/Controller/PersonController.cs b/projects/tutorial_ASP.NET_2017/source/Controller/PersonController.cs new file mode 100644 index 0000000..b41c538 --- /dev/null +++ b/projects/tutorial_ASP.NET_2017/source/Controller/PersonController.cs @@ -0,0 +1,99 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Web.Http; +using lab06.Models; + +namespace lab06.Models +{ + public class PersonController : ApiController + { + public PersonCR[] persona = new PersonCR[] + { + new PersonCR() + } ; + + + + + // GET: api/Person + public IEnumerable GetAllPersons() + { + + return persona; + } + + // GET: api/Person/5 + public IHttpActionResult GetPersonid(int id) + { + var pers = persona.FirstOrDefault((p) => p.personId == id); + if (pers == null) + { + return NotFound(); + } + return Ok(pers); + } + + [Route("api/person/{perId}/health-profile")] + public IHttpActionResult Get(long perId) + { + var pers = persona.FirstOrDefault((p) => p.personId == perId); + + + if (pers == null) + { + return NotFound(); + + } + + return Ok(pers.hProfile); + } + + // POST: api/Person + /* public void Post([FromBody]string value) + { + PersonCR persona = new PersonCR; + + }*/ + + // POST: api/Person + public void Post(PersonCR pers) + { + Array.Resize(ref persona, persona.Length + 1); + persona[persona.Length-1] = new PersonCR(pers.personId,pers.firstname,pers.lastname,pers.birthdate); + + + + } + + + // PUT: api/Person/5 + public void Put(int id, PersonCR perso) + { + var pers = persona.FirstOrDefault((p) => p.personId == id); + + + if (pers == null) + { + + } + else + { + pers.firstname = perso.firstname; + pers.lastname = perso.lastname; + pers.birthdate = perso.birthdate; + + + } + } + + // DELETE: api/Person/5 + public void Delete(int id) + { + Array.Clear(persona, id, 1); + + } + } +} From ebf202324d0770c0770af2eb54be1aea469a7fb3 Mon Sep 17 00:00:00 2001 From: Eusebio Gomez Date: Fri, 16 Jun 2017 01:45:08 -0400 Subject: [PATCH 07/23] Delete s.s --- projects/tutorial_ASP.NET_2017/source/Controller/s.s | 1 - 1 file changed, 1 deletion(-) delete mode 100644 projects/tutorial_ASP.NET_2017/source/Controller/s.s diff --git a/projects/tutorial_ASP.NET_2017/source/Controller/s.s b/projects/tutorial_ASP.NET_2017/source/Controller/s.s deleted file mode 100644 index 8b13789..0000000 --- a/projects/tutorial_ASP.NET_2017/source/Controller/s.s +++ /dev/null @@ -1 +0,0 @@ - From e2dae975545eebff82c0fef68a4d35a6af939b6d Mon Sep 17 00:00:00 2001 From: Eusebio Gomez Date: Fri, 16 Jun 2017 01:53:08 -0400 Subject: [PATCH 08/23] Update README.md --- projects/tutorial_ASP.NET_2017/README.md | 109 +++++++++++++++++++---- 1 file changed, 92 insertions(+), 17 deletions(-) diff --git a/projects/tutorial_ASP.NET_2017/README.md b/projects/tutorial_ASP.NET_2017/README.md index 9464451..3481c4f 100644 --- a/projects/tutorial_ASP.NET_2017/README.md +++ b/projects/tutorial_ASP.NET_2017/README.md @@ -133,41 +133,116 @@ public IHttpActionResult GetPersonid(int id) * **GET /api/person/{personId}/health-profile:** ```C# - [Route("api/person/{perId}/health-profile")] - public IHttpActionResult Get(long perId) - { - var pers = persona.FirstOrDefault((p) => p.personId == perId); - - - if (pers == null) - { - return NotFound(); - - } - - return Ok(pers.hProfile); - } +public IHttpActionResult Get(long perId) +{ + var pers = persona.FirstOrDefault((p) => p.personId == perId); + if (pers == null) + { + return NotFound(); + } + return Ok(pers.hProfile); +} ``` * **POST /api/person:** ```C# - +public void Post(PersonCR pers) +{ + Array.Resize(ref persona, persona.Length + 1); + persona[persona.Length-1] = new PersonCR(pers.personId,pers.firstname,pers.lastname,pers.birthdate); +} ``` * **PUT /api/person/{personId}:** ```C# - +public void Put(int id, PersonCR perso) +{ + var pers = persona.FirstOrDefault((p) => p.personId == id); + if (pers != null) + { + pers.firstname = perso.firstname; + pers.lastname = perso.lastname; + pers.birthdate = perso.birthdate; + } +} ``` * **DELETE /api/person/{personId}:** ```C# - +public void Delete(int id) +{ + Array.Clear(persona, id, 1); +} ``` * **PersonController.cs** entire content: ```C# +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Web.Http; +using lab06.Models; +namespace lab06.Models +{ + public class PersonController : ApiController + { + public PersonCR[] persona = new PersonCR[] + { + new PersonCR() + } + + public IEnumerable GetAllPersons() + { + return persona; + } + + public IHttpActionResult GetPersonid(int id) + { + var pers = persona.FirstOrDefault((p) => p.personId == id); + if (pers == null) + { + return NotFound(); + } + return Ok(pers); + } + + public IHttpActionResult Get(long perId) + { + var pers = persona.FirstOrDefault((p) => p.personId == perId); + if (pers == null) + { + return NotFound(); + } + return Ok(pers.hProfile); + } + + public void Post(PersonCR pers) + { + Array.Resize(ref persona, persona.Length + 1); + persona[persona.Length-1] = new PersonCR(pers.personId,pers.firstname,pers.lastname,pers.birthdate); + } + + public void Put(int id, PersonCR perso) + { + var pers = persona.FirstOrDefault((p) => p.personId == id); + if (pers != null) + { + pers.firstname = perso.firstname; + pers.lastname = perso.lastname; + pers.birthdate = perso.birthdate; + } + } + + public void Delete(int id) + { + Array.Clear(persona, id, 1); + } + } +} ``` ## Finishing From 46bdd73a0d60b284d3635f4c9515c957181e71dd Mon Sep 17 00:00:00 2001 From: Eusebio Gomez Date: Fri, 16 Jun 2017 01:54:25 -0400 Subject: [PATCH 09/23] Update README.md --- projects/tutorial_ASP.NET_2017/README.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/projects/tutorial_ASP.NET_2017/README.md b/projects/tutorial_ASP.NET_2017/README.md index 3481c4f..22669e3 100644 --- a/projects/tutorial_ASP.NET_2017/README.md +++ b/projects/tutorial_ASP.NET_2017/README.md @@ -193,12 +193,12 @@ namespace lab06.Models public PersonCR[] persona = new PersonCR[] { new PersonCR() - } + }; public IEnumerable GetAllPersons() { return persona; - } + }; public IHttpActionResult GetPersonid(int id) { @@ -208,7 +208,7 @@ namespace lab06.Models return NotFound(); } return Ok(pers); - } + }; public IHttpActionResult Get(long perId) { @@ -218,13 +218,13 @@ namespace lab06.Models return NotFound(); } return Ok(pers.hProfile); - } + }; public void Post(PersonCR pers) { Array.Resize(ref persona, persona.Length + 1); persona[persona.Length-1] = new PersonCR(pers.personId,pers.firstname,pers.lastname,pers.birthdate); - } + }; public void Put(int id, PersonCR perso) { @@ -235,12 +235,12 @@ namespace lab06.Models pers.lastname = perso.lastname; pers.birthdate = perso.birthdate; } - } + }; public void Delete(int id) { Array.Clear(persona, id, 1); - } + }; } } ``` From 16369abe7c63208490485a41f5be0a0483b472d8 Mon Sep 17 00:00:00 2001 From: Eusebio Gomez Date: Fri, 16 Jun 2017 01:55:40 -0400 Subject: [PATCH 10/23] Update PersonController.cs --- .../source/Controller/PersonController.cs | 64 +++++-------------- 1 file changed, 15 insertions(+), 49 deletions(-) diff --git a/projects/tutorial_ASP.NET_2017/source/Controller/PersonController.cs b/projects/tutorial_ASP.NET_2017/source/Controller/PersonController.cs index b41c538..0174ee6 100644 --- a/projects/tutorial_ASP.NET_2017/source/Controller/PersonController.cs +++ b/projects/tutorial_ASP.NET_2017/source/Controller/PersonController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Net; @@ -11,21 +11,15 @@ namespace lab06.Models public class PersonController : ApiController { public PersonCR[] persona = new PersonCR[] - { - new PersonCR() - } ; - - - + { + new PersonCR() + }; - // GET: api/Person public IEnumerable GetAllPersons() - { - + { return persona; - } - - // GET: api/Person/5 + }; + public IHttpActionResult GetPersonid(int id) { var pers = persona.FirstOrDefault((p) => p.personId == id); @@ -34,66 +28,38 @@ public IHttpActionResult GetPersonid(int id) return NotFound(); } return Ok(pers); - } + }; - [Route("api/person/{perId}/health-profile")] public IHttpActionResult Get(long perId) { var pers = persona.FirstOrDefault((p) => p.personId == perId); - - if (pers == null) { return NotFound(); - } - return Ok(pers.hProfile); - } - - // POST: api/Person - /* public void Post([FromBody]string value) - { - PersonCR persona = new PersonCR; - - }*/ + }; - // POST: api/Person - public void Post(PersonCR pers) + public void Post(PersonCR pers) { Array.Resize(ref persona, persona.Length + 1); persona[persona.Length-1] = new PersonCR(pers.personId,pers.firstname,pers.lastname,pers.birthdate); - - - - } + }; - - // PUT: api/Person/5 public void Put(int id, PersonCR perso) { var pers = persona.FirstOrDefault((p) => p.personId == id); - - - if (pers == null) - { - - } - else + if (pers != null) { pers.firstname = perso.firstname; pers.lastname = perso.lastname; pers.birthdate = perso.birthdate; - - } - } - - // DELETE: api/Person/5 + }; + public void Delete(int id) { Array.Clear(persona, id, 1); - - } + }; } } From 7d6730f3f1fc3669bf6dc071f95191c2d88e0df7 Mon Sep 17 00:00:00 2001 From: Eusebio Gomez Date: Fri, 16 Jun 2017 01:56:06 -0400 Subject: [PATCH 11/23] Delete AccountController.cs --- .../source/Controller/AccountController.cs | 485 ------------------ 1 file changed, 485 deletions(-) delete mode 100644 projects/tutorial_ASP.NET_2017/source/Controller/AccountController.cs diff --git a/projects/tutorial_ASP.NET_2017/source/Controller/AccountController.cs b/projects/tutorial_ASP.NET_2017/source/Controller/AccountController.cs deleted file mode 100644 index 199a67d..0000000 --- a/projects/tutorial_ASP.NET_2017/source/Controller/AccountController.cs +++ /dev/null @@ -1,485 +0,0 @@ -using System; -using System.Globalization; -using System.Linq; -using System.Security.Claims; -using System.Threading.Tasks; -using System.Web; -using System.Web.Mvc; -using Microsoft.AspNet.Identity; -using Microsoft.AspNet.Identity.Owin; -using Microsoft.Owin.Security; -using lab06.Models; - -namespace lab06.Controllers -{ - [Authorize] - public class AccountController : Controller - { - private ApplicationSignInManager _signInManager; - private ApplicationUserManager _userManager; - - public AccountController() - { - } - - public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager ) - { - UserManager = userManager; - SignInManager = signInManager; - } - - public ApplicationSignInManager SignInManager - { - get - { - return _signInManager ?? HttpContext.GetOwinContext().Get(); - } - private set - { - _signInManager = value; - } - } - - public ApplicationUserManager UserManager - { - get - { - return _userManager ?? HttpContext.GetOwinContext().GetUserManager(); - } - private set - { - _userManager = value; - } - } - - // - // GET: /Account/Login - [AllowAnonymous] - public ActionResult Login(string returnUrl) - { - ViewBag.ReturnUrl = returnUrl; - return View(); - } - - // - // POST: /Account/Login - [HttpPost] - [AllowAnonymous] - [ValidateAntiForgeryToken] - public async Task Login(LoginViewModel model, string returnUrl) - { - if (!ModelState.IsValid) - { - return View(model); - } - - // No cuenta los errores de inicio de sesión para el bloqueo de la cuenta - // Para permitir que los errores de contraseña desencadenen el bloqueo de la cuenta, cambie a shouldLockout: true - var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false); - switch (result) - { - case SignInStatus.Success: - return RedirectToLocal(returnUrl); - case SignInStatus.LockedOut: - return View("Lockout"); - case SignInStatus.RequiresVerification: - return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }); - case SignInStatus.Failure: - default: - ModelState.AddModelError("", "Intento de inicio de sesión no válido."); - return View(model); - } - } - - // - // GET: /Account/VerifyCode - [AllowAnonymous] - public async Task VerifyCode(string provider, string returnUrl, bool rememberMe) - { - // Requerir que el usuario haya iniciado sesión con nombre de usuario y contraseña o inicio de sesión externo - if (!await SignInManager.HasBeenVerifiedAsync()) - { - return View("Error"); - } - return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe }); - } - - // - // POST: /Account/VerifyCode - [HttpPost] - [AllowAnonymous] - [ValidateAntiForgeryToken] - public async Task VerifyCode(VerifyCodeViewModel model) - { - if (!ModelState.IsValid) - { - return View(model); - } - - // El código siguiente protege de los ataques por fuerza bruta a los códigos de dos factores. - // Si un usuario introduce códigos incorrectos durante un intervalo especificado de tiempo, la cuenta del usuario - // se bloqueará durante un período de tiempo especificado. - // Puede configurar el bloqueo de la cuenta en IdentityConfig - var result = await SignInManager.TwoFactorSignInAsync(model.Provider, model.Code, isPersistent: model.RememberMe, rememberBrowser: model.RememberBrowser); - switch (result) - { - case SignInStatus.Success: - return RedirectToLocal(model.ReturnUrl); - case SignInStatus.LockedOut: - return View("Lockout"); - case SignInStatus.Failure: - default: - ModelState.AddModelError("", "Código no válido."); - return View(model); - } - } - - // - // GET: /Account/Register - [AllowAnonymous] - public ActionResult Register() - { - return View(); - } - - // - // POST: /Account/Register - [HttpPost] - [AllowAnonymous] - [ValidateAntiForgeryToken] - public async Task Register(RegisterViewModel model) - { - if (ModelState.IsValid) - { - var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; - var result = await UserManager.CreateAsync(user, model.Password); - if (result.Succeeded) - { - await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false); - - // Para obtener más información sobre cómo habilitar la confirmación de cuenta y el restablecimiento de contraseña, visite http://go.microsoft.com/fwlink/?LinkID=320771 - // Enviar correo electrónico con este vínculo - // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); - // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); - // await UserManager.SendEmailAsync(user.Id, "Confirmar cuenta", "Para confirmar la cuenta, haga clic aquí"); - - return RedirectToAction("Index", "Home"); - } - AddErrors(result); - } - - // Si llegamos a este punto, es que se ha producido un error y volvemos a mostrar el formulario - return View(model); - } - - // - // GET: /Account/ConfirmEmail - [AllowAnonymous] - public async Task ConfirmEmail(string userId, string code) - { - if (userId == null || code == null) - { - return View("Error"); - } - var result = await UserManager.ConfirmEmailAsync(userId, code); - return View(result.Succeeded ? "ConfirmEmail" : "Error"); - } - - // - // GET: /Account/ForgotPassword - [AllowAnonymous] - public ActionResult ForgotPassword() - { - return View(); - } - - // - // POST: /Account/ForgotPassword - [HttpPost] - [AllowAnonymous] - [ValidateAntiForgeryToken] - public async Task ForgotPassword(ForgotPasswordViewModel model) - { - if (ModelState.IsValid) - { - var user = await UserManager.FindByNameAsync(model.Email); - if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id))) - { - // No revelar que el usuario no existe o que no está confirmado - return View("ForgotPasswordConfirmation"); - } - - // Para obtener más información sobre cómo habilitar la confirmación de cuenta y el restablecimiento de contraseña, visite http://go.microsoft.com/fwlink/?LinkID=320771 - // Enviar correo electrónico con este vínculo - // string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id); - // var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); - // await UserManager.SendEmailAsync(user.Id, "Restablecer contraseña", "Para restablecer la contraseña, haga clic aquí"); - // return RedirectToAction("ForgotPasswordConfirmation", "Account"); - } - - // Si llegamos a este punto, es que se ha producido un error y volvemos a mostrar el formulario - return View(model); - } - - // - // GET: /Account/ForgotPasswordConfirmation - [AllowAnonymous] - public ActionResult ForgotPasswordConfirmation() - { - return View(); - } - - // - // GET: /Account/ResetPassword - [AllowAnonymous] - public ActionResult ResetPassword(string code) - { - return code == null ? View("Error") : View(); - } - - // - // POST: /Account/ResetPassword - [HttpPost] - [AllowAnonymous] - [ValidateAntiForgeryToken] - public async Task ResetPassword(ResetPasswordViewModel model) - { - if (!ModelState.IsValid) - { - return View(model); - } - var user = await UserManager.FindByNameAsync(model.Email); - if (user == null) - { - // No revelar que el usuario no existe - return RedirectToAction("ResetPasswordConfirmation", "Account"); - } - var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password); - if (result.Succeeded) - { - return RedirectToAction("ResetPasswordConfirmation", "Account"); - } - AddErrors(result); - return View(); - } - - // - // GET: /Account/ResetPasswordConfirmation - [AllowAnonymous] - public ActionResult ResetPasswordConfirmation() - { - return View(); - } - - // - // POST: /Account/ExternalLogin - [HttpPost] - [AllowAnonymous] - [ValidateAntiForgeryToken] - public ActionResult ExternalLogin(string provider, string returnUrl) - { - // Solicitar redireccionamiento al proveedor de inicio de sesión externo - return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl })); - } - - // - // GET: /Account/SendCode - [AllowAnonymous] - public async Task SendCode(string returnUrl, bool rememberMe) - { - var userId = await SignInManager.GetVerifiedUserIdAsync(); - if (userId == null) - { - return View("Error"); - } - var userFactors = await UserManager.GetValidTwoFactorProvidersAsync(userId); - var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList(); - return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe }); - } - - // - // POST: /Account/SendCode - [HttpPost] - [AllowAnonymous] - [ValidateAntiForgeryToken] - public async Task SendCode(SendCodeViewModel model) - { - if (!ModelState.IsValid) - { - return View(); - } - - // Generar el token y enviarlo - if (!await SignInManager.SendTwoFactorCodeAsync(model.SelectedProvider)) - { - return View("Error"); - } - return RedirectToAction("VerifyCode", new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe }); - } - - // - // GET: /Account/ExternalLoginCallback - [AllowAnonymous] - public async Task ExternalLoginCallback(string returnUrl) - { - var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(); - if (loginInfo == null) - { - return RedirectToAction("Login"); - } - - // Si el usuario ya tiene un inicio de sesión, iniciar sesión del usuario con este proveedor de inicio de sesión externo - var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false); - switch (result) - { - case SignInStatus.Success: - return RedirectToLocal(returnUrl); - case SignInStatus.LockedOut: - return View("Lockout"); - case SignInStatus.RequiresVerification: - return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false }); - case SignInStatus.Failure: - default: - // Si el usuario no tiene ninguna cuenta, solicitar que cree una - ViewBag.ReturnUrl = returnUrl; - ViewBag.LoginProvider = loginInfo.Login.LoginProvider; - return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email }); - } - } - - // - // POST: /Account/ExternalLoginConfirmation - [HttpPost] - [AllowAnonymous] - [ValidateAntiForgeryToken] - public async Task ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) - { - if (User.Identity.IsAuthenticated) - { - return RedirectToAction("Index", "Manage"); - } - - if (ModelState.IsValid) - { - // Obtener datos del usuario del proveedor de inicio de sesión externo - var info = await AuthenticationManager.GetExternalLoginInfoAsync(); - if (info == null) - { - return View("ExternalLoginFailure"); - } - var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; - var result = await UserManager.CreateAsync(user); - if (result.Succeeded) - { - result = await UserManager.AddLoginAsync(user.Id, info.Login); - if (result.Succeeded) - { - await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); - return RedirectToLocal(returnUrl); - } - } - AddErrors(result); - } - - ViewBag.ReturnUrl = returnUrl; - return View(model); - } - - // - // POST: /Account/LogOff - [HttpPost] - [ValidateAntiForgeryToken] - public ActionResult LogOff() - { - AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie); - return RedirectToAction("Index", "Home"); - } - - // - // GET: /Account/ExternalLoginFailure - [AllowAnonymous] - public ActionResult ExternalLoginFailure() - { - return View(); - } - - protected override void Dispose(bool disposing) - { - if (disposing) - { - if (_userManager != null) - { - _userManager.Dispose(); - _userManager = null; - } - - if (_signInManager != null) - { - _signInManager.Dispose(); - _signInManager = null; - } - } - - base.Dispose(disposing); - } - - #region Aplicaciones auxiliares - // Se usa para la protección XSRF al agregar inicios de sesión externos - private const string XsrfKey = "XsrfId"; - - private IAuthenticationManager AuthenticationManager - { - get - { - return HttpContext.GetOwinContext().Authentication; - } - } - - private void AddErrors(IdentityResult result) - { - foreach (var error in result.Errors) - { - ModelState.AddModelError("", error); - } - } - - private ActionResult RedirectToLocal(string returnUrl) - { - if (Url.IsLocalUrl(returnUrl)) - { - return Redirect(returnUrl); - } - return RedirectToAction("Index", "Home"); - } - - internal class ChallengeResult : HttpUnauthorizedResult - { - public ChallengeResult(string provider, string redirectUri) - : this(provider, redirectUri, null) - { - } - - public ChallengeResult(string provider, string redirectUri, string userId) - { - LoginProvider = provider; - RedirectUri = redirectUri; - UserId = userId; - } - - public string LoginProvider { get; set; } - public string RedirectUri { get; set; } - public string UserId { get; set; } - - public override void ExecuteResult(ControllerContext context) - { - var properties = new AuthenticationProperties { RedirectUri = RedirectUri }; - if (UserId != null) - { - properties.Dictionary[XsrfKey] = UserId; - } - context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider); - } - } - #endregion - } -} \ No newline at end of file From e1b73fec1127f16f0b70d59e768057e93fcd8075 Mon Sep 17 00:00:00 2001 From: Eusebio Gomez Date: Fri, 16 Jun 2017 01:56:12 -0400 Subject: [PATCH 12/23] Delete HealthPController.cs --- .../source/Controller/HealthPController.cs | 13 ------------- 1 file changed, 13 deletions(-) delete mode 100644 projects/tutorial_ASP.NET_2017/source/Controller/HealthPController.cs diff --git a/projects/tutorial_ASP.NET_2017/source/Controller/HealthPController.cs b/projects/tutorial_ASP.NET_2017/source/Controller/HealthPController.cs deleted file mode 100644 index c941701..0000000 --- a/projects/tutorial_ASP.NET_2017/source/Controller/HealthPController.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Web.Http; - -namespace lab06.Controllers -{ - public class HealthPController : ApiController - { - } -} From 25f88dcf1166e928665c8f60800fe37f1397a721 Mon Sep 17 00:00:00 2001 From: Eusebio Gomez Date: Fri, 16 Jun 2017 01:56:20 -0400 Subject: [PATCH 13/23] Delete HomeController.cs --- .../source/Controller/HomeController.cs | 30 ------------------- 1 file changed, 30 deletions(-) delete mode 100644 projects/tutorial_ASP.NET_2017/source/Controller/HomeController.cs diff --git a/projects/tutorial_ASP.NET_2017/source/Controller/HomeController.cs b/projects/tutorial_ASP.NET_2017/source/Controller/HomeController.cs deleted file mode 100644 index 7b3a85d..0000000 --- a/projects/tutorial_ASP.NET_2017/source/Controller/HomeController.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; -using System.Web.Mvc; - -namespace lab06.Controllers -{ - public class HomeController : Controller - { - public ActionResult Index() - { - return View(); - } - - public ActionResult About() - { - ViewBag.Message = "Your application description page."; - - return View(); - } - - public ActionResult Contact() - { - ViewBag.Message = "Your contact page."; - - return View(); - } - } -} \ No newline at end of file From 473cfb9f892808f2943dbf6c586ca110920ab275 Mon Sep 17 00:00:00 2001 From: Eusebio Gomez Date: Fri, 16 Jun 2017 01:56:27 -0400 Subject: [PATCH 14/23] Delete ManageController.cs --- .../source/Controller/ManageController.cs | 389 ------------------ 1 file changed, 389 deletions(-) delete mode 100644 projects/tutorial_ASP.NET_2017/source/Controller/ManageController.cs diff --git a/projects/tutorial_ASP.NET_2017/source/Controller/ManageController.cs b/projects/tutorial_ASP.NET_2017/source/Controller/ManageController.cs deleted file mode 100644 index 8b9e1ac..0000000 --- a/projects/tutorial_ASP.NET_2017/source/Controller/ManageController.cs +++ /dev/null @@ -1,389 +0,0 @@ -using System; -using System.Linq; -using System.Threading.Tasks; -using System.Web; -using System.Web.Mvc; -using Microsoft.AspNet.Identity; -using Microsoft.AspNet.Identity.Owin; -using Microsoft.Owin.Security; -using lab06.Models; - -namespace lab06.Controllers -{ - [Authorize] - public class ManageController : Controller - { - private ApplicationSignInManager _signInManager; - private ApplicationUserManager _userManager; - - public ManageController() - { - } - - public ManageController(ApplicationUserManager userManager, ApplicationSignInManager signInManager) - { - UserManager = userManager; - SignInManager = signInManager; - } - - public ApplicationSignInManager SignInManager - { - get - { - return _signInManager ?? HttpContext.GetOwinContext().Get(); - } - private set - { - _signInManager = value; - } - } - - public ApplicationUserManager UserManager - { - get - { - return _userManager ?? HttpContext.GetOwinContext().GetUserManager(); - } - private set - { - _userManager = value; - } - } - - // - // GET: /Manage/Index - public async Task Index(ManageMessageId? message) - { - ViewBag.StatusMessage = - message == ManageMessageId.ChangePasswordSuccess ? "Su contraseña se ha cambiado." - : message == ManageMessageId.SetPasswordSuccess ? "Su contraseña se ha establecido." - : message == ManageMessageId.SetTwoFactorSuccess ? "Su proveedor de autenticación de dos factores se ha establecido." - : message == ManageMessageId.Error ? "Se ha producido un error." - : message == ManageMessageId.AddPhoneSuccess ? "Se ha agregado su número de teléfono." - : message == ManageMessageId.RemovePhoneSuccess ? "Se ha quitado su número de teléfono." - : ""; - - var userId = User.Identity.GetUserId(); - var model = new IndexViewModel - { - HasPassword = HasPassword(), - PhoneNumber = await UserManager.GetPhoneNumberAsync(userId), - TwoFactor = await UserManager.GetTwoFactorEnabledAsync(userId), - Logins = await UserManager.GetLoginsAsync(userId), - BrowserRemembered = await AuthenticationManager.TwoFactorBrowserRememberedAsync(userId) - }; - return View(model); - } - - // - // POST: /Manage/RemoveLogin - [HttpPost] - [ValidateAntiForgeryToken] - public async Task RemoveLogin(string loginProvider, string providerKey) - { - ManageMessageId? message; - var result = await UserManager.RemoveLoginAsync(User.Identity.GetUserId(), new UserLoginInfo(loginProvider, providerKey)); - if (result.Succeeded) - { - var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); - if (user != null) - { - await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); - } - message = ManageMessageId.RemoveLoginSuccess; - } - else - { - message = ManageMessageId.Error; - } - return RedirectToAction("ManageLogins", new { Message = message }); - } - - // - // GET: /Manage/AddPhoneNumber - public ActionResult AddPhoneNumber() - { - return View(); - } - - // - // POST: /Manage/AddPhoneNumber - [HttpPost] - [ValidateAntiForgeryToken] - public async Task AddPhoneNumber(AddPhoneNumberViewModel model) - { - if (!ModelState.IsValid) - { - return View(model); - } - // Generar el token y enviarlo - var code = await UserManager.GenerateChangePhoneNumberTokenAsync(User.Identity.GetUserId(), model.Number); - if (UserManager.SmsService != null) - { - var message = new IdentityMessage - { - Destination = model.Number, - Body = "Su código de seguridad es: " + code - }; - await UserManager.SmsService.SendAsync(message); - } - return RedirectToAction("VerifyPhoneNumber", new { PhoneNumber = model.Number }); - } - - // - // POST: /Manage/EnableTwoFactorAuthentication - [HttpPost] - [ValidateAntiForgeryToken] - public async Task EnableTwoFactorAuthentication() - { - await UserManager.SetTwoFactorEnabledAsync(User.Identity.GetUserId(), true); - var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); - if (user != null) - { - await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); - } - return RedirectToAction("Index", "Manage"); - } - - // - // POST: /Manage/DisableTwoFactorAuthentication - [HttpPost] - [ValidateAntiForgeryToken] - public async Task DisableTwoFactorAuthentication() - { - await UserManager.SetTwoFactorEnabledAsync(User.Identity.GetUserId(), false); - var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); - if (user != null) - { - await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); - } - return RedirectToAction("Index", "Manage"); - } - - // - // GET: /Manage/VerifyPhoneNumber - public async Task VerifyPhoneNumber(string phoneNumber) - { - var code = await UserManager.GenerateChangePhoneNumberTokenAsync(User.Identity.GetUserId(), phoneNumber); - // Enviar un SMS a través del proveedor de SMS para verificar el número de teléfono - return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber }); - } - - // - // POST: /Manage/VerifyPhoneNumber - [HttpPost] - [ValidateAntiForgeryToken] - public async Task VerifyPhoneNumber(VerifyPhoneNumberViewModel model) - { - if (!ModelState.IsValid) - { - return View(model); - } - var result = await UserManager.ChangePhoneNumberAsync(User.Identity.GetUserId(), model.PhoneNumber, model.Code); - if (result.Succeeded) - { - var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); - if (user != null) - { - await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); - } - return RedirectToAction("Index", new { Message = ManageMessageId.AddPhoneSuccess }); - } - // Si llegamos a este punto, es que se ha producido un error, volvemos a mostrar el formulario - ModelState.AddModelError("", "No se ha podido comprobar el teléfono"); - return View(model); - } - - // - // POST: /Manage/RemovePhoneNumber - [HttpPost] - [ValidateAntiForgeryToken] - public async Task RemovePhoneNumber() - { - var result = await UserManager.SetPhoneNumberAsync(User.Identity.GetUserId(), null); - if (!result.Succeeded) - { - return RedirectToAction("Index", new { Message = ManageMessageId.Error }); - } - var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); - if (user != null) - { - await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); - } - return RedirectToAction("Index", new { Message = ManageMessageId.RemovePhoneSuccess }); - } - - // - // GET: /Manage/ChangePassword - public ActionResult ChangePassword() - { - return View(); - } - - // - // POST: /Manage/ChangePassword - [HttpPost] - [ValidateAntiForgeryToken] - public async Task ChangePassword(ChangePasswordViewModel model) - { - if (!ModelState.IsValid) - { - return View(model); - } - var result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword); - if (result.Succeeded) - { - var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); - if (user != null) - { - await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); - } - return RedirectToAction("Index", new { Message = ManageMessageId.ChangePasswordSuccess }); - } - AddErrors(result); - return View(model); - } - - // - // GET: /Manage/SetPassword - public ActionResult SetPassword() - { - return View(); - } - - // - // POST: /Manage/SetPassword - [HttpPost] - [ValidateAntiForgeryToken] - public async Task SetPassword(SetPasswordViewModel model) - { - if (ModelState.IsValid) - { - var result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword); - if (result.Succeeded) - { - var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); - if (user != null) - { - await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); - } - return RedirectToAction("Index", new { Message = ManageMessageId.SetPasswordSuccess }); - } - AddErrors(result); - } - - // Si llegamos a este punto, es que se ha producido un error, volvemos a mostrar el formulario - return View(model); - } - - // - // GET: /Manage/ManageLogins - public async Task ManageLogins(ManageMessageId? message) - { - ViewBag.StatusMessage = - message == ManageMessageId.RemoveLoginSuccess ? "Se ha quitado el inicio de sesión externo." - : message == ManageMessageId.Error ? "Se ha producido un error." - : ""; - var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); - if (user == null) - { - return View("Error"); - } - var userLogins = await UserManager.GetLoginsAsync(User.Identity.GetUserId()); - var otherLogins = AuthenticationManager.GetExternalAuthenticationTypes().Where(auth => userLogins.All(ul => auth.AuthenticationType != ul.LoginProvider)).ToList(); - ViewBag.ShowRemoveButton = user.PasswordHash != null || userLogins.Count > 1; - return View(new ManageLoginsViewModel - { - CurrentLogins = userLogins, - OtherLogins = otherLogins - }); - } - - // - // POST: /Manage/LinkLogin - [HttpPost] - [ValidateAntiForgeryToken] - public ActionResult LinkLogin(string provider) - { - // Solicitar la redirección al proveedor de inicio de sesión externo para vincular un inicio de sesión para el usuario actual - return new AccountController.ChallengeResult(provider, Url.Action("LinkLoginCallback", "Manage"), User.Identity.GetUserId()); - } - - // - // GET: /Manage/LinkLoginCallback - public async Task LinkLoginCallback() - { - var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(XsrfKey, User.Identity.GetUserId()); - if (loginInfo == null) - { - return RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error }); - } - var result = await UserManager.AddLoginAsync(User.Identity.GetUserId(), loginInfo.Login); - return result.Succeeded ? RedirectToAction("ManageLogins") : RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error }); - } - - protected override void Dispose(bool disposing) - { - if (disposing && _userManager != null) - { - _userManager.Dispose(); - _userManager = null; - } - - base.Dispose(disposing); - } - -#region Aplicaciones auxiliares - // Se usan para protección XSRF al agregar inicios de sesión externos - private const string XsrfKey = "XsrfId"; - - private IAuthenticationManager AuthenticationManager - { - get - { - return HttpContext.GetOwinContext().Authentication; - } - } - - private void AddErrors(IdentityResult result) - { - foreach (var error in result.Errors) - { - ModelState.AddModelError("", error); - } - } - - private bool HasPassword() - { - var user = UserManager.FindById(User.Identity.GetUserId()); - if (user != null) - { - return user.PasswordHash != null; - } - return false; - } - - private bool HasPhoneNumber() - { - var user = UserManager.FindById(User.Identity.GetUserId()); - if (user != null) - { - return user.PhoneNumber != null; - } - return false; - } - - public enum ManageMessageId - { - AddPhoneSuccess, - ChangePasswordSuccess, - SetTwoFactorSuccess, - SetPasswordSuccess, - RemoveLoginSuccess, - RemovePhoneSuccess, - Error - } - -#endregion - } -} \ No newline at end of file From a071192f0e72a3db3c27974cfffc8f6133426138 Mon Sep 17 00:00:00 2001 From: Eusebio Gomez Date: Fri, 16 Jun 2017 01:56:38 -0400 Subject: [PATCH 15/23] Delete AccountViewModels.cs --- .../source/Models/AccountViewModels.cs | 112 ------------------ 1 file changed, 112 deletions(-) delete mode 100644 projects/tutorial_ASP.NET_2017/source/Models/AccountViewModels.cs diff --git a/projects/tutorial_ASP.NET_2017/source/Models/AccountViewModels.cs b/projects/tutorial_ASP.NET_2017/source/Models/AccountViewModels.cs deleted file mode 100644 index 5f80f87..0000000 --- a/projects/tutorial_ASP.NET_2017/source/Models/AccountViewModels.cs +++ /dev/null @@ -1,112 +0,0 @@ -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; - -namespace lab06.Models -{ - public class ExternalLoginConfirmationViewModel - { - [Required] - [Display(Name = "Correo electrónico")] - public string Email { get; set; } - } - - public class ExternalLoginListViewModel - { - public string ReturnUrl { get; set; } - } - - public class SendCodeViewModel - { - public string SelectedProvider { get; set; } - public ICollection Providers { get; set; } - public string ReturnUrl { get; set; } - public bool RememberMe { get; set; } - } - - public class VerifyCodeViewModel - { - [Required] - public string Provider { get; set; } - - [Required] - [Display(Name = "Código")] - public string Code { get; set; } - public string ReturnUrl { get; set; } - - [Display(Name = "¿Recordar este explorador?")] - public bool RememberBrowser { get; set; } - - public bool RememberMe { get; set; } - } - - public class ForgotViewModel - { - [Required] - [Display(Name = "Correo electrónico")] - public string Email { get; set; } - } - - public class LoginViewModel - { - [Required] - [Display(Name = "Correo electrónico")] - [EmailAddress] - public string Email { get; set; } - - [Required] - [DataType(DataType.Password)] - [Display(Name = "Contraseña")] - public string Password { get; set; } - - [Display(Name = "¿Recordar cuenta?")] - public bool RememberMe { get; set; } - } - - public class RegisterViewModel - { - [Required] - [EmailAddress] - [Display(Name = "Correo electrónico")] - public string Email { get; set; } - - [Required] - [StringLength(100, ErrorMessage = "El número de caracteres de {0} debe ser al menos {2}.", MinimumLength = 6)] - [DataType(DataType.Password)] - [Display(Name = "Contraseña")] - public string Password { get; set; } - - [DataType(DataType.Password)] - [Display(Name = "Confirmar contraseña")] - [Compare("Password", ErrorMessage = "La contraseña y la contraseña de confirmación no coinciden.")] - public string ConfirmPassword { get; set; } - } - - public class ResetPasswordViewModel - { - [Required] - [EmailAddress] - [Display(Name = "Correo electrónico")] - public string Email { get; set; } - - [Required] - [StringLength(100, ErrorMessage = "El número de caracteres de {0} debe ser al menos {2}.", MinimumLength = 6)] - [DataType(DataType.Password)] - [Display(Name = "Contraseña")] - public string Password { get; set; } - - [DataType(DataType.Password)] - [Display(Name = "Confirmar contraseña")] - [Compare("Password", ErrorMessage = "La contraseña y la contraseña de confirmación no coinciden.")] - public string ConfirmPassword { get; set; } - - public string Code { get; set; } - } - - public class ForgotPasswordViewModel - { - [Required] - [EmailAddress] - [Display(Name = "Correo electrónico")] - public string Email { get; set; } - } -} From e4231a285e464e721bbe1b81ade4bb4a785c87d7 Mon Sep 17 00:00:00 2001 From: Eusebio Gomez Date: Fri, 16 Jun 2017 01:58:12 -0400 Subject: [PATCH 16/23] Update HealthProfile.cs --- .../tutorial_ASP.NET_2017/source/Models/HealthProfile.cs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/projects/tutorial_ASP.NET_2017/source/Models/HealthProfile.cs b/projects/tutorial_ASP.NET_2017/source/Models/HealthProfile.cs index 396eac9..e426127 100644 --- a/projects/tutorial_ASP.NET_2017/source/Models/HealthProfile.cs +++ b/projects/tutorial_ASP.NET_2017/source/Models/HealthProfile.cs @@ -46,7 +46,6 @@ public String toString() { return "{" + this.height + "," + this.weight + "," + this.getBMI() + "," + "}"; } - - + } -} \ No newline at end of file +} From 821d814fd9bf67952a52f96bfb014a0d5a04a8bb Mon Sep 17 00:00:00 2001 From: Eusebio Gomez Date: Fri, 16 Jun 2017 01:58:32 -0400 Subject: [PATCH 17/23] Delete IdentityModels.cs --- .../source/Models/IdentityModels.cs | 33 ------------------- 1 file changed, 33 deletions(-) delete mode 100644 projects/tutorial_ASP.NET_2017/source/Models/IdentityModels.cs diff --git a/projects/tutorial_ASP.NET_2017/source/Models/IdentityModels.cs b/projects/tutorial_ASP.NET_2017/source/Models/IdentityModels.cs deleted file mode 100644 index af673ad..0000000 --- a/projects/tutorial_ASP.NET_2017/source/Models/IdentityModels.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System.Data.Entity; -using System.Security.Claims; -using System.Threading.Tasks; -using Microsoft.AspNet.Identity; -using Microsoft.AspNet.Identity.EntityFramework; - -namespace lab06.Models -{ - // Puede agregar datos del perfil del usuario agregando más propiedades a la clase ApplicationUser. Para más información, visite http://go.microsoft.com/fwlink/?LinkID=317594. - public class ApplicationUser : IdentityUser - { - public async Task GenerateUserIdentityAsync(UserManager manager) - { - // Tenga en cuenta que el valor de authenticationType debe coincidir con el definido en CookieAuthenticationOptions.AuthenticationType - var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); - // Agregar aquí notificaciones personalizadas de usuario - return userIdentity; - } - } - - public class ApplicationDbContext : IdentityDbContext - { - public ApplicationDbContext() - : base("DefaultConnection", throwIfV1Schema: false) - { - } - - public static ApplicationDbContext Create() - { - return new ApplicationDbContext(); - } - } -} \ No newline at end of file From d7809811cb55aa4467242895da3b101c94e1a774 Mon Sep 17 00:00:00 2001 From: Eusebio Gomez Date: Fri, 16 Jun 2017 01:58:39 -0400 Subject: [PATCH 18/23] Delete ManageViewModels.cs --- .../source/Models/ManageViewModels.cs | 86 ------------------- 1 file changed, 86 deletions(-) delete mode 100644 projects/tutorial_ASP.NET_2017/source/Models/ManageViewModels.cs diff --git a/projects/tutorial_ASP.NET_2017/source/Models/ManageViewModels.cs b/projects/tutorial_ASP.NET_2017/source/Models/ManageViewModels.cs deleted file mode 100644 index 9673162..0000000 --- a/projects/tutorial_ASP.NET_2017/source/Models/ManageViewModels.cs +++ /dev/null @@ -1,86 +0,0 @@ -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using Microsoft.AspNet.Identity; -using Microsoft.Owin.Security; - -namespace lab06.Models -{ - public class IndexViewModel - { - public bool HasPassword { get; set; } - public IList Logins { get; set; } - public string PhoneNumber { get; set; } - public bool TwoFactor { get; set; } - public bool BrowserRemembered { get; set; } - } - - public class ManageLoginsViewModel - { - public IList CurrentLogins { get; set; } - public IList OtherLogins { get; set; } - } - - public class FactorViewModel - { - public string Purpose { get; set; } - } - - public class SetPasswordViewModel - { - [Required] - [StringLength(100, ErrorMessage = "{0} debe tener al menos {2} caracteres de longitud.", MinimumLength = 6)] - [DataType(DataType.Password)] - [Display(Name = "Contraseña nueva")] - public string NewPassword { get; set; } - - [DataType(DataType.Password)] - [Display(Name = "Confirme la contraseña nueva")] - [Compare("NewPassword", ErrorMessage = "La contraseña nueva y la contraseña de confirmación no coinciden.")] - public string ConfirmPassword { get; set; } - } - - public class ChangePasswordViewModel - { - [Required] - [DataType(DataType.Password)] - [Display(Name = "Contraseña actual")] - public string OldPassword { get; set; } - - [Required] - [StringLength(100, ErrorMessage = "{0} debe tener al menos {2} caracteres de longitud.", MinimumLength = 6)] - [DataType(DataType.Password)] - [Display(Name = "Contraseña nueva")] - public string NewPassword { get; set; } - - [DataType(DataType.Password)] - [Display(Name = "Confirme la contraseña nueva")] - [Compare("NewPassword", ErrorMessage = "La contraseña nueva y la contraseña de confirmación no coinciden.")] - public string ConfirmPassword { get; set; } - } - - public class AddPhoneNumberViewModel - { - [Required] - [Phone] - [Display(Name = "Número de teléfono")] - public string Number { get; set; } - } - - public class VerifyPhoneNumberViewModel - { - [Required] - [Display(Name = "Código")] - public string Code { get; set; } - - [Required] - [Phone] - [Display(Name = "Número de teléfono")] - public string PhoneNumber { get; set; } - } - - public class ConfigureTwoFactorViewModel - { - public string SelectedProvider { get; set; } - public ICollection Providers { get; set; } - } -} \ No newline at end of file From c1450d6301452cbb51f16eab0486094ff9cbae0e Mon Sep 17 00:00:00 2001 From: Eusebio Gomez Date: Fri, 16 Jun 2017 02:01:58 -0400 Subject: [PATCH 19/23] Update PersonController.cs --- .../source/Controller/PersonController.cs | 128 +++++++++++------- 1 file changed, 82 insertions(+), 46 deletions(-) diff --git a/projects/tutorial_ASP.NET_2017/source/Controller/PersonController.cs b/projects/tutorial_ASP.NET_2017/source/Controller/PersonController.cs index 0174ee6..84ab289 100644 --- a/projects/tutorial_ASP.NET_2017/source/Controller/PersonController.cs +++ b/projects/tutorial_ASP.NET_2017/source/Controller/PersonController.cs @@ -1,65 +1,101 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Net; -using System.Net.Http; -using System.Web.Http; +using System.Web; using lab06.Models; namespace lab06.Models { - public class PersonController : ApiController + public class PersonCR { - public PersonCR[] persona = new PersonCR[] - { - new PersonCR() - }; + public string firstname; + public string lastname; + public HealthProfile hProfile; + public string birthdate; + public long personId; - public IEnumerable GetAllPersons() - { - return persona; - }; - - public IHttpActionResult GetPersonid(int id) + public PersonCR(long personId, String fname, String lname, String birthdate, HealthProfile hp) { - var pers = persona.FirstOrDefault((p) => p.personId == id); - if (pers == null) - { - return NotFound(); - } - return Ok(pers); - }; + this.setPersonId(personId); + this.setFirstname(fname); + this.setLastname(lname); + this.setBirthdate(birthdate); + this.hProfile = hp; + } - public IHttpActionResult Get(long perId) + public PersonCR(long personId, String fname, String lname, String birthdate) { - var pers = persona.FirstOrDefault((p) => p.personId == perId); - if (pers == null) - { - return NotFound(); - } - return Ok(pers.hProfile); - }; + this.setPersonId(personId); + this.setFirstname(fname); + this.setLastname(lname); + this.setBirthdate(birthdate); + this.hProfile = new HealthProfile(); + } - public void Post(PersonCR pers) + public PersonCR() { - Array.Resize(ref persona, persona.Length + 1); - persona[persona.Length-1] = new PersonCR(pers.personId,pers.firstname,pers.lastname,pers.birthdate); - }; - - public void Put(int id, PersonCR perso) + this.firstname = "Pinco"; + this.lastname = "Pallino"; + HealthProfile hp = new HealthProfile(); + this.hProfile = hp; + + // setting personId to a random number between 1 and 9999 + Random rnd = new Random(); + int nro = rnd.Next(9999); + this.personId = nro; + + this.birthdate = "11/11/2011"; + } + + public String getFirstname() + { + return firstname; + } + + public void setFirstname(String firstname) { - var pers = persona.FirstOrDefault((p) => p.personId == id); - if (pers != null) - { - pers.firstname = perso.firstname; - pers.lastname = perso.lastname; - pers.birthdate = perso.birthdate; - } - }; + this.firstname = firstname; + } - public void Delete(int id) + public String getLastname() { - Array.Clear(persona, id, 1); - }; + return lastname; + } + + public void setLastname(String lastname) + { + this.lastname = lastname; + } + + public HealthProfile getHProfile() + { + return hProfile; + } + + public void setHProfile(HealthProfile hProfile) + { + this.hProfile = hProfile; + } + + public String getBirthdate() + { + return birthdate; + } + + public void setBirthdate(String birthdate) + { + this.birthdate = birthdate; + } + + public long getPersonId() + { + return personId; + } + + public void setPersonId(long personId) + { + this.personId = personId; + } + } } From 5e19222ce83fc7c9fe005031d5a0b5f13a02963c Mon Sep 17 00:00:00 2001 From: Eusebio Gomez Date: Fri, 16 Jun 2017 02:02:03 -0400 Subject: [PATCH 20/23] Update README.md --- projects/tutorial_ASP.NET_2017/README.md | 112 ++++++++++++++++++++--- 1 file changed, 101 insertions(+), 11 deletions(-) diff --git a/projects/tutorial_ASP.NET_2017/README.md b/projects/tutorial_ASP.NET_2017/README.md index 22669e3..7e06008 100644 --- a/projects/tutorial_ASP.NET_2017/README.md +++ b/projects/tutorial_ASP.NET_2017/README.md @@ -55,12 +55,21 @@ namespace lab06.Models public string birthdate; public long personId; - public PersonCR(long personId, string fname, string lname, string birthdate, HealthProfile hp) + public PersonCR(long personId, String fname, String lname, String birthdate, HealthProfile hp) { - this.personId = personId; - this.firstname = fname; - this.lastname = lname; - this.birthdate = birthdate; + this.setPersonId(personId); + this.setFirstname(fname); + this.setLastname(lname); + this.setBirthdate(birthdate); + this.hProfile = hp; + } + + public PersonCR(long personId, String fname, String lname, String birthdate) + { + this.setPersonId(personId); + this.setFirstname(fname); + this.setLastname(lname); + this.setBirthdate(birthdate); this.hProfile = new HealthProfile(); } @@ -68,10 +77,67 @@ namespace lab06.Models { this.firstname = "Pinco"; this.lastname = "Pallino"; - this.hProfile = new HealthProfile(); - this.personId = 1; - this.birthdate = "24/02/1998"; + HealthProfile hp = new HealthProfile(); + this.hProfile = hp; + + // setting personId to a random number between 1 and 9999 + Random rnd = new Random(); + int nro = rnd.Next(9999); + this.personId = nro; + + this.birthdate = "11/11/2011"; + } + + public String getFirstname() + { + return firstname; + } + + public void setFirstname(String firstname) + { + this.firstname = firstname; + } + + public String getLastname() + { + return lastname; } + + public void setLastname(String lastname) + { + this.lastname = lastname; + } + + public HealthProfile getHProfile() + { + return hProfile; + } + + public void setHProfile(HealthProfile hProfile) + { + this.hProfile = hProfile; + } + + public String getBirthdate() + { + return birthdate; + } + + public void setBirthdate(String birthdate) + { + this.birthdate = birthdate; + } + + public long getPersonId() + { + return personId; + } + + public void setPersonId(long personId) + { + this.personId = personId; + } + } } ``` @@ -89,8 +155,8 @@ namespace lab06.Models { public class HealthProfile { - private double weight; // in kg - private double height; // in m + public double weight; // in kg + public double height; // in m public HealthProfile(double weight, double height) { @@ -104,7 +170,31 @@ namespace lab06.Models this.height = 1.72; } - + public void setWeight(double weight) + { + this.weight = weight; + } + + public double getHeight() + { + return height; + } + + public void setHeight(double height) + { + this.height = height; + } + + public double getBMI() + { + return this.weight / (Math.Pow(this.height, 2)); + } + + public String toString() + { + return "{" + this.height + "," + this.weight + "," + this.getBMI() + "," + "}"; + } + } } ``` From 8e1211242e5fe27e61d04edbfdefc4a58e6dcd95 Mon Sep 17 00:00:00 2001 From: Eusebio Gomez Date: Fri, 16 Jun 2017 02:02:46 -0400 Subject: [PATCH 21/23] Update README.md --- projects/tutorial_ASP.NET_2017/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/projects/tutorial_ASP.NET_2017/README.md b/projects/tutorial_ASP.NET_2017/README.md index 7e06008..26a46b8 100644 --- a/projects/tutorial_ASP.NET_2017/README.md +++ b/projects/tutorial_ASP.NET_2017/README.md @@ -331,6 +331,7 @@ namespace lab06.Models { Array.Clear(persona, id, 1); }; + } } ``` From 44a2fad18575f44f0d4220972b4d610d3d8d8bfe Mon Sep 17 00:00:00 2001 From: Eusebio Gomez Date: Fri, 16 Jun 2017 02:04:18 -0400 Subject: [PATCH 22/23] Update PersonController.cs --- .../source/Controller/PersonController.cs | 127 +++++++----------- 1 file changed, 46 insertions(+), 81 deletions(-) diff --git a/projects/tutorial_ASP.NET_2017/source/Controller/PersonController.cs b/projects/tutorial_ASP.NET_2017/source/Controller/PersonController.cs index 84ab289..4671f52 100644 --- a/projects/tutorial_ASP.NET_2017/source/Controller/PersonController.cs +++ b/projects/tutorial_ASP.NET_2017/source/Controller/PersonController.cs @@ -1,101 +1,66 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Web; +using System.Net; +using System.Net.Http; +using System.Web.Http; using lab06.Models; namespace lab06.Models { - public class PersonCR + public class PersonController : ApiController { - public string firstname; - public string lastname; - public HealthProfile hProfile; - public string birthdate; - public long personId; - - public PersonCR(long personId, String fname, String lname, String birthdate, HealthProfile hp) - { - this.setPersonId(personId); - this.setFirstname(fname); - this.setLastname(lname); - this.setBirthdate(birthdate); - this.hProfile = hp; - } - - public PersonCR(long personId, String fname, String lname, String birthdate) + public PersonCR[] persona = new PersonCR[] { - this.setPersonId(personId); - this.setFirstname(fname); - this.setLastname(lname); - this.setBirthdate(birthdate); - this.hProfile = new HealthProfile(); - } + new PersonCR() + }; - public PersonCR() - { - this.firstname = "Pinco"; - this.lastname = "Pallino"; - HealthProfile hp = new HealthProfile(); - this.hProfile = hp; - - // setting personId to a random number between 1 and 9999 - Random rnd = new Random(); - int nro = rnd.Next(9999); - this.personId = nro; - - this.birthdate = "11/11/2011"; - } - - public String getFirstname() - { - return firstname; - } - - public void setFirstname(String firstname) - { - this.firstname = firstname; - } - - public String getLastname() - { - return lastname; - } + public IEnumerable GetAllPersons() + { + return persona; + }; - public void setLastname(String lastname) + public IHttpActionResult GetPersonid(int id) { - this.lastname = lastname; - } - - public HealthProfile getHProfile() - { - return hProfile; - } - - public void setHProfile(HealthProfile hProfile) + var pers = persona.FirstOrDefault((p) => p.personId == id); + if (pers == null) + { + return NotFound(); + } + return Ok(pers); + }; + + public IHttpActionResult Get(long perId) { - this.hProfile = hProfile; - } - - public String getBirthdate() + var pers = persona.FirstOrDefault((p) => p.personId == perId); + if (pers == null) + { + return NotFound(); + } + return Ok(pers.hProfile); + }; + + public void Post(PersonCR pers) { - return birthdate; - } - - public void setBirthdate(String birthdate) + Array.Resize(ref persona, persona.Length + 1); + persona[persona.Length-1] = new PersonCR(pers.personId,pers.firstname,pers.lastname,pers.birthdate); + }; + + public void Put(int id, PersonCR perso) { - this.birthdate = birthdate; - } + var pers = persona.FirstOrDefault((p) => p.personId == id); + if (pers != null) + { + pers.firstname = perso.firstname; + pers.lastname = perso.lastname; + pers.birthdate = perso.birthdate; + } + }; - public long getPersonId() + public void Delete(int id) { - return personId; - } + Array.Clear(persona, id, 1); + }; - public void setPersonId(long personId) - { - this.personId = personId; - } - } } From bbbd06f5e26f4d79d6fe5402e219aa5cd71270c1 Mon Sep 17 00:00:00 2001 From: Eusebio Gomez Date: Fri, 16 Jun 2017 02:05:59 -0400 Subject: [PATCH 23/23] Update PersonCR.cs --- .../source/Models/PersonCR.cs | 27 ++++++++++--------- 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/projects/tutorial_ASP.NET_2017/source/Models/PersonCR.cs b/projects/tutorial_ASP.NET_2017/source/Models/PersonCR.cs index 337ccad..84ab289 100644 --- a/projects/tutorial_ASP.NET_2017/source/Models/PersonCR.cs +++ b/projects/tutorial_ASP.NET_2017/source/Models/PersonCR.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Web; @@ -36,63 +36,66 @@ public PersonCR() { this.firstname = "Pinco"; this.lastname = "Pallino"; - HealthProfile hp = new HealthProfile(); - this.hProfile = hp; + // setting personId to a random number between 1 and 9999 Random rnd = new Random(); int nro = rnd.Next(9999); - //this.personId =nro; // Solution to Exercise #01-1d - this.personId = 1; - this.birthdate = "11/11/2011"; - } - public void delete() - { + this.personId = nro; + this.birthdate = "11/11/2011"; } - + public String getFirstname() { return firstname; } + public void setFirstname(String firstname) { this.firstname = firstname; } + public String getLastname() { return lastname; } + public void setLastname(String lastname) { this.lastname = lastname; } + public HealthProfile getHProfile() { return hProfile; } + public void setHProfile(HealthProfile hProfile) { this.hProfile = hProfile; } + public String getBirthdate() { return birthdate; } + public void setBirthdate(String birthdate) { this.birthdate = birthdate; } + public long getPersonId() { return personId; } + public void setPersonId(long personId) { this.personId = personId; } - } -} \ No newline at end of file +}