// ======================================================================== // // Copyright (C) 2017-2018 MARC CHEVALDONNE // marc.chevaldonne.free.fr // // Module : AlertController.cs // Author : Marc Chevaldonné // Creation date : 2018-02-12 // // ======================================================================== using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using AlertWebAPI.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; //using Microsoft.Azure.NotificationHubs; //using Microsoft.Azure.Mobile.Server.Config; //using Microsoft.Azure.Mobile.Server; namespace AlertWebAPI.Controllers { /// /// controller to access the "alerts" database through the web service /// [Authorize] //"authorize" does not allow anonymous use of the public methods of AlertController [Route("api/alert")] public class AlertController : Controller { /// /// context to the EntityFramework "alerts" database /// private readonly AlertDbContext context; /// /// constructor that will be automatically called by the web api when needed /// /// context to the EntityFramework database public AlertController(AlertDbContext context) { this.context = context; //fills the database with stubbed data if it is empty StubData(context); } //[Conditional("DEBUG")] private void StubData(AlertDbContext context) { if (context.AlertItems.Count() == 0) { InitializeData(context); context.SaveChanges(); } } /// /// adds three fake alerts to the database /// /// private void InitializeData(AlertDbContext context) { context.AlertItems.Add(new AlertItem { Id = new Guid("D61C83CA-1BFB-43EB-A952-C0364D77E40F"), Name = "Alert 1", Date = new DateTime(2018, 2, 4, 22, 53, 00), Decription = "une petite alerte...", Type = AlertType.Low, IsManaged = false, SignaledBy = "Dwight Schrute" }); context.AlertItems.Add(new AlertItem { Id = new Guid("9E1F9662-02C0-435C-8027-0062BAB38143"), Name = "Alert 2", Date = new DateTime(2018, 2, 4, 22, 55, 00), Decription = "une alerte...", Type = AlertType.Medium, IsManaged = false, SignaledBy = "Dwight Schrute" }); context.AlertItems.Add(new AlertItem { Id = new Guid("371E0CBC-F339-433B-8629-3C5A38DC2822"), Name = "Alert 3", Date = new DateTime(2018, 2, 4, 22, 56, 00), Decription = "une grosse alerte...", Type = AlertType.High, IsManaged = false, SignaledBy = "Dwight Schrute" }); context.AlertItems.Add(new AlertItem { Id = new Guid("79CEF2C8-4CC6-4A95-8DA8-B00DEDB5E3A8"), Name = "Alert 4", Date = new DateTime(2018, 3, 5, 17, 11, 00), Decription = "une alerte de ouf...", Type = AlertType.High, IsManaged = false, SignaledBy = "Michael Scott" }); } /// /// gets all the alerts in the database /// GET: api/ /// /// a collection of alerts [HttpGet] public IEnumerable GetAll() { return context.AlertItems.ToList(); } //the previous method could have used IActionResult as a return parameter //IActionResult allows methods to have different methods to use (NotFound, ObjectResult, BadRequest, NoContentResult, Ok...) //[HttpGet] //public IActionResult GetAll() //{ // return new ObjectResult(context.AlertItems.ToList()); //} /// /// get an alert by giving its id /// GET api//5 /// {id} indicates the part of the request representing the id /// /// the id of the alert to get /// the alert owning this id or null [HttpGet("{id}", Name = "GetAlert")] public IActionResult GetById(Guid id) { var alertItem = context.AlertItems.FirstOrDefault(alert => alert.Id == id); if(alertItem == null) { return NotFound(); } return new ObjectResult(alertItem); } /// /// a post request allows to add a new alert in the database /// POST api/ /// /// the alert to add /// [HttpPost] public IActionResult Post([FromBody]AlertItem alert) { //returns a BadRequest if the alert to add is null if (alert == null) { return BadRequest(); } //adds the alert to the database context.AlertItems.Add(alert); context.SaveChanges(); //await PushMethode(alert); //returns the route allowing to access this alert //the route is defined as "GetAlert", defined in the previous methode GetById return CreatedAtRoute("GetAlert", new { id = alert.Id }, alert); } //private async System.Threading.Tasks.Task PushMethode(AlertItem alert) //{ // //// Get the settings for the server project. // //System.Web.Http.HttpConfiguration config = this.Configuration; // //MobileAppSettingsDictionary settings = // // this.Configuration.GetMobileAppSettingsProvider().GetMobileAppSettings(); // //// Get the Notification Hubs credentials for the mobile app. // //string notificationHubName = settings.NotificationHubName; // //string notificationHubConnection = settings // // .Connections[MobileAppSettingsKeys.NotificationHubConnectionString].ConnectionString; // // Create a new Notification Hub client. // NotificationHubClient hub = NotificationHubClient // //.CreateClientFromConnectionString(notificationHubConnection, notificationHubName); // .CreateClientFromConnectionString(@"Endpoint=sb://alertsetsis.servicebus.windows.net/;SharedAccessKeyName=DefaultFullSharedAccessSignature;SharedAccessKey=T83QPDWgowEYoQYMyWvKSJte1/wMsiE8Opa0RCK8AZs=", // "alertsetsisnotificationhub"); // // Send the message so that all template registrations that contain "messageParam" // // receive the notifications. This includes APNS, GCM, WNS, and MPNS template registrations. // Dictionary templateParams = new Dictionary(); // templateParams["messageParam"] = $"new alert: {alert.Name}";//item.Text + " was added to the list."; // try // { // // Send the push notification and log the results. // var result = await hub.SendTemplateNotificationAsync(templateParams); // // Write the success result to the logs. // //config.Services.GetTraceWriter().Info(result.State.ToString()); // } // catch (System.Exception ex) // { // // Write the failure result to the logs. // //config.Services.GetTraceWriter() // // .Error(ex.Message, null, "Push.SendAsync Error"); // } //} /// /// updates an alert /// PUT api//5 /// /// the id of the alert to update /// the alert to update /// [HttpPut("{id}")] public IActionResult Put(Guid id, [FromBody]AlertItem item) { //returns a BadRequest if the alert is null or does not have the good id if (item == null || item.Id != id) { return BadRequest(); } //gets the alert in the database with the given id var alert = context.AlertItems.FirstOrDefault(a => a.Id == id); if (alert == null) { return NotFound(); } //updates the alert alert.Date = item.Date; alert.Decription = item.Decription; alert.IsManaged = item.IsManaged; alert.ManagedBy = item.ManagedBy; alert.Name = item.Name; alert.SignaledBy = item.SignaledBy; alert.Type = item.Type; context.AlertItems.Update(alert); context.SaveChanges(); return new NoContentResult(); } /// /// deletes an alert in the database /// DELETE api//5 /// /// the id of the alert to delete /// [HttpDelete("{id}")] public IActionResult Delete(Guid id) { //retrieves the alert to delete in the database var alertItem = context.AlertItems.FirstOrDefault(a => a.Id == id); if (alertItem == null) { return NotFound(); } //removes it from the database context.AlertItems.Remove(alertItem); context.SaveChanges(); return new NoContentResult(); } } }