Add device controller + DeviceDetailDTO + create section (all in Data as JSON) + delete all section from config

This commit is contained in:
Thomas Fransolet 2021-05-04 16:52:39 +02:00
parent d162b2f15d
commit 65e7c7f890
14 changed files with 424 additions and 56 deletions

View File

@ -9,7 +9,16 @@ namespace Manager.Interfaces.DTO
public string Id { get; set; }
public string Name { get; set; }
public string IpAddress { get; set; }
public string ConfigurationId { get; set; }
public bool Connected{ get; set; }
public DateTime DateCreation{ get; set; }
}
public class DeviceDetailDTO : DeviceDTO
{
public string ConnectionLevel { get; set; }
public DateTime LastConnectionLevel { get; set; }
public string BatteryLevel { get; set; }
public DateTime LastBatteryLevel { get; set; }
}
}

View File

@ -16,8 +16,8 @@ namespace Manager.Interfaces.DTO
public class GeoPointDTO
{
public int Id { get; set; }
public Dictionary<String, object> Title { get; set; } // Dictionary<string, object> with all languages
public Dictionary<String, object> Description { get; set; } // Dictionary<string, object> with all languages
public string Title { get; set; } // Dictionary<string, object> with all languages
public string Description { get; set; } // Dictionary<string, object> with all languages
public string Image { get; set; } // url to ressource id (local) or on internet
public string ImageType { get; set; } // url or ressource
public string Text { get; set; } // Dictionary<string, object> with all languages

View File

@ -4,7 +4,7 @@ using System.Text;
namespace Manager.Interfaces.DTO
{
public class MenuDTO : SectionDTO
public class MenuDTO
{
//public string Title { get; set; } // Dictionary<string, object> with all languages
public List<SectionDTO> Sections { get; set; }

View File

@ -4,7 +4,7 @@ using System.Text;
namespace Manager.Interfaces.DTO
{
public class SliderDTO : SectionDTO
public class SliderDTO
{
public List<ImageDTO> Images { get; set; }
}

View File

@ -4,7 +4,7 @@ using System.Text;
namespace Manager.Interfaces.DTO
{
public class VideoDTO : SectionDTO
public class VideoDTO
{
//public string Title { get; set; } // Dictionary<string, object> with all languages
public string Source { get; set; } // url to ressource id (local) or on internet

View File

@ -4,7 +4,7 @@ using System.Text;
namespace Manager.Interfaces.DTO
{
public class WebDTO : SectionDTO
public class WebDTO
{
//public string Title { get; set; } // Dictionary<string, object> with all languages
public string Source { get; set; } // url to ressource id (local) or on internet

View File

@ -56,6 +56,24 @@ namespace Manager.Interfaces.Models
Name = Name,
IpAddress = IpAddress,
Connected = Connected,
ConfigurationId = ConfigurationId,
DateCreation = DateCreation
};
}
public DeviceDetailDTO ToDetailDTO()
{
return new DeviceDetailDTO()
{
Id = Id,
Name = Name,
IpAddress = IpAddress,
Connected = Connected,
ConfigurationId = ConfigurationId,
ConnectionLevel = ConnectionLevel,
LastConnectionLevel = LastConnectionLevel,
BatteryLevel = BatteryLevel,
LastBatteryLevel = LastBatteryLevel,
DateCreation = DateCreation
};
}

View File

@ -30,10 +30,10 @@ namespace Manager.Interfaces.Models
{
return new MapDTO()
{
Id = Id,
/*Id = Id,
Label = Label,
Type = Type,
ImageId = ImageId,
ImageId = ImageId,*/
MapType = MapType,
Zoom = Zoom,
Points = Points.Select(p => p.ToDTO()).ToList(),

View File

@ -20,10 +20,10 @@ namespace Manager.Interfaces.Models
{
return new SliderDTO()
{
Id = Id,
/*Id = Id,
Label = Label,
Type = Type,
ImageId = ImageId,
ImageId = ImageId,*/
Images = Images.Select(p => p.ToDTO()).ToList(),
};
}

View File

@ -0,0 +1,217 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Manager.Interfaces.DTO;
using Manager.Interfaces.Models;
using Manager.Services;
using ManagerService.Service.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NSwag.Annotations;
namespace ManagerService.Controllers
{
[Authorize] // TODO Add ROLES (Roles = "Admin")
[ApiController, Route("api/[controller]")]
[OpenApiTag("Device", Description = "Device management")]
public class DeviceController : ControllerBase
{
private DeviceDatabaseService _deviceService;
private readonly ILogger<DeviceController> _logger;
public DeviceController(ILogger<DeviceController> logger, DeviceDatabaseService deviceService)
{
_logger = logger;
_deviceService = deviceService;
}
/// <summary>
/// Get a list of all devices
/// </summary>
[ProducesResponseType(typeof(List<DeviceDTO>), 200)]
[ProducesResponseType(typeof(string), 500)]
[HttpGet]
public ObjectResult Get()
{
try
{
List<Device> devices = _deviceService.GetAll();
return new OkObjectResult(devices.Select(d => d.ToDTO()));
}
catch (Exception ex)
{
return new ObjectResult(ex.Message) { StatusCode = 500 };
}
}
/// <summary>
/// Get a specific device
/// </summary>
/// <param name="id">id device</param>
[AllowAnonymous]
[ProducesResponseType(typeof(DeviceDetailDTO), 200)]
[ProducesResponseType(typeof(string), 404)]
[ProducesResponseType(typeof(string), 500)]
[HttpGet("{id}/detail")]
public ObjectResult GetDetail(string id)
{
try
{
Device device = _deviceService.GetById(id);
if (device == null)
throw new KeyNotFoundException("This device was not found");
return new OkObjectResult(device.ToDetailDTO());
}
catch (KeyNotFoundException ex)
{
return new NotFoundObjectResult(ex.Message) { };
}
catch (Exception ex)
{
return new ObjectResult(ex.Message) { StatusCode = 500 };
}
}
/// <summary>
/// Create a new device
/// </summary>
/// <param name="newRessource">New device info</param>
[ProducesResponseType(typeof(DeviceDetailDTO), 200)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 409)]
[ProducesResponseType(typeof(string), 500)]
[HttpPost]
public ObjectResult Create([FromBody] DeviceDetailDTO newDevice)
{
try
{
if (newDevice == null)
throw new ArgumentNullException("Device param is null");
// Todo add some verification ?
Device device = new Device();
device.Name = newDevice.Name;
device.IpAddress = newDevice.IpAddress;
device.Connected = newDevice.Connected;
device.ConnectionLevel = newDevice.ConnectionLevel;
device.LastConnectionLevel = newDevice.LastConnectionLevel;
device.BatteryLevel = newDevice.BatteryLevel;
device.LastBatteryLevel = newDevice.LastBatteryLevel;
device.DateCreation = DateTime.Now;
Device deviceCreated = _deviceService.Create(device);
return new OkObjectResult(deviceCreated.ToDTO());
}
catch (ArgumentNullException ex)
{
return new BadRequestObjectResult(ex.Message) { };
}
catch (InvalidOperationException ex)
{
return new ConflictObjectResult(ex.Message) { };
}
catch (Exception ex)
{
return new ObjectResult(ex.Message) { StatusCode = 500 };
}
}
/// <summary>
/// Update a device
/// </summary>
/// <param name="updatedDevice">Device to update</param>
[ProducesResponseType(typeof(DeviceDetailDTO), 200)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 404)]
[ProducesResponseType(typeof(string), 500)]
[HttpPut]
public ObjectResult Update([FromBody] DeviceDetailDTO updatedDevice)
{
try
{
if (updatedDevice == null)
throw new ArgumentNullException("Device param is null");
Device device = _deviceService.GetById(updatedDevice.Id);
if (device == null)
throw new KeyNotFoundException("Device does not exist");
// Todo add some verification ?
device.Name = updatedDevice.Name;
device.IpAddress = updatedDevice.IpAddress;
device.Connected = updatedDevice.Connected;
device.ConnectionLevel = updatedDevice.ConnectionLevel;
device.LastConnectionLevel = updatedDevice.LastConnectionLevel;
device.BatteryLevel = updatedDevice.BatteryLevel;
device.LastBatteryLevel = updatedDevice.LastBatteryLevel;
Device deviceModified = _deviceService.Update(updatedDevice.Id, device);
return new OkObjectResult(deviceModified.ToDTO());
}
catch (ArgumentNullException ex)
{
return new BadRequestObjectResult(ex.Message) { };
}
catch (KeyNotFoundException ex)
{
return new NotFoundObjectResult(ex.Message) { };
}
catch (Exception ex)
{
return new ObjectResult(ex.Message) { StatusCode = 500 };
}
}
/// <summary>
/// Delete a device
/// </summary>
/// <param name="id">Id of device to delete</param>
[ProducesResponseType(typeof(string), 202)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 404)]
[ProducesResponseType(typeof(string), 500)]
[HttpDelete("{id}")]
public ObjectResult Delete(string id)
{
try
{
if (id == null)
throw new ArgumentNullException("Device param is null");
if (!_deviceService.IsExist(id))
throw new KeyNotFoundException("Device does not exist");
_deviceService.Remove(id);
return new ObjectResult("The device has been deleted") { StatusCode = 202 };
}
catch (ArgumentNullException ex)
{
return new BadRequestObjectResult(ex.Message) { };
}
catch (KeyNotFoundException ex)
{
return new NotFoundObjectResult(ex.Message) { };
}
catch (Exception ex)
{
return new ObjectResult(ex.Message) { StatusCode = 500 };
}
}
}
}

View File

@ -77,6 +77,35 @@ namespace ManagerService.Controllers
}
}
/// <summary>
/// Delete all section from a specific configuration
/// </summary>
/// <param name="id">configuration id</param>
[ProducesResponseType(typeof(string), 202)]
[ProducesResponseType(typeof(string), 500)]
[ProducesResponseType(typeof(string), 400)]
[HttpDelete("configuration/{id}")]
public ObjectResult DeleteAllForConfiguration(string id)
{
try
{
if (id == null)
throw new ArgumentNullException("Param is null");
_sectionService.DeleteAllFromConfiguration(id);
return new ObjectResult("All section from the specified configuration has been deleted") { StatusCode = 202 };
}
catch (ArgumentNullException ex)
{
return new BadRequestObjectResult(ex.Message) { };
}
catch (Exception ex)
{
return new ObjectResult(ex.Message) { StatusCode = 500 };
}
}
/// <summary>
/// Get a list of all subsection (summary) of a specific section
/// </summary>
@ -201,19 +230,18 @@ namespace ManagerService.Controllers
section.ParentId = null;
section.Type = newSection.Type;
switch (newSection.Type) {
case SectionType.Map:
MapDTO mapDTO = new MapDTO();
mapDTO.Icon = "";
mapDTO.MapType = MapType.hybrid;
mapDTO.Zoom = 18;
List<string> languages = _configurationService.GetById(newSection.ConfigurationId).Languages;
// Preparation
Dictionary<string, object> titles = new Dictionary<string, object>();
Dictionary<string, object> descriptions = new Dictionary<string, object>();
List<string> languages = _configurationService.GetById(newSection.ConfigurationId).Languages;
foreach (var language in languages) {
switch (language.ToUpper()) {
var mapDTO = new MapDTO(); // For menu dto
var sliderDTO = new SliderDTO(); // For menu dto
foreach (var language in languages)
{
switch (language.ToUpper())
{
case "FR":
titles.Add(language, "Titre en français");
descriptions.Add(language, "Description en français");
@ -233,11 +261,18 @@ namespace ManagerService.Controllers
}
}
switch (newSection.Type) {
case SectionType.Map:
mapDTO = new MapDTO();
mapDTO.Icon = "";
mapDTO.MapType = MapType.hybrid;
mapDTO.Zoom = 18;
mapDTO.Points = new List<GeoPointDTO>() {
new GeoPointDTO() {
Id = 0,
Title = titles,
Description = descriptions,
Title = JsonConvert.SerializeObject(titles),
Description = JsonConvert.SerializeObject(descriptions),
Image = "", // TODO sample
ImageType = "url", // TODO
Latitude = "50.416639",
@ -246,36 +281,59 @@ namespace ManagerService.Controllers
}
};
section.Data = JsonConvert.SerializeObject(mapDTO); ; // Include all info from specific section as JSON
section.Data = JsonConvert.SerializeObject(mapDTO); // Include all info from specific section as JSON
break;
case SectionType.Slider:
section.Data = newSection.Data; // Include all info from specific section as JSON
sliderDTO = new SliderDTO();
ImageDTO imageDTO = new ImageDTO();
imageDTO.Title = JsonConvert.SerializeObject(titles);
imageDTO.Description = JsonConvert.SerializeObject(descriptions);
imageDTO.Source = "";
sliderDTO.Images.Add(imageDTO);
section.Data = JsonConvert.SerializeObject(sliderDTO); // Include all info from specific section as JSON
break;
case SectionType.Video:
section.Data = newSection.Data; // Include all info from specific section as JSON
VideoDTO videoDTO = new VideoDTO();
videoDTO.Source = "";
section.Data = JsonConvert.SerializeObject(videoDTO); // Include all info from specific section as JSON
break;
case SectionType.Web:
section.Data = newSection.Data; // Include all info from specific section as JSON
WebDTO webDTO = new WebDTO();
webDTO.Source = "";
section.Data = JsonConvert.SerializeObject(webDTO); // Include all info from specific section as JSON
break;
case SectionType.Menu:
section.Data = newSection.Data; // Include all info from specific section as JSON
MenuDTO menuDTO = new MenuDTO();
menuDTO.Sections = new List<SectionDTO>();
/*SectionDTO section0DTO = new SectionDTO();
section0DTO.IsSubSection = true;
section0DTO.Label = newSection.Label;
section0DTO.ImageId = newSection.ImageId;
section0DTO.ConfigurationId = newSection.ConfigurationId;
section0DTO.DateCreation = DateTime.Now;
section0DTO.ParentId = null;
section0DTO.Type = SectionType.Map;
section0DTO.Data = JsonConvert.SerializeObject(mapDTO);
SectionDTO section1DTO = new SectionDTO();
section0DTO.IsSubSection = true;
section0DTO.Label = newSection.Label;
section0DTO.ImageId = newSection.ImageId;
section0DTO.ConfigurationId = newSection.ConfigurationId;
section0DTO.DateCreation = DateTime.Now;
section0DTO.ParentId = null;
section0DTO.Type = SectionType.Slider;
section1DTO.IsSubSection = true;
section1DTO.Data = JsonConvert.SerializeObject(sliderDTO);*/
/*menuDTO.Sections.Add(section0DTO);
menuDTO.Sections.Add(section1DTO);*/
section.Data = JsonConvert.SerializeObject(menuDTO); // Include all info from specific section as JSON
break;
}
/*section.MapType = newSectionMap.MapType;
section.Zoom = newSectionMap.Zoom;
section.Icon = newSectionMap.Icon;
section.Points = newSectionMap.Points.Select(p =>
new GeoPoint() {
Id = p.Id,
Title = p.Title,
Description = p.Description,
Image = p.Image,
Text = p.Text,
Latitude = p.Latitude,
Longitude = p.Longitude
}).ToList();*/
Section sectionCreated = _sectionService.Create(section);
return new OkObjectResult(sectionCreated.ToDTO());

View File

@ -0,0 +1,60 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Manager.Interfaces.Models;
using Microsoft.Extensions.Configuration;
using MongoDB.Driver;
namespace Manager.Services
{
public class DeviceDatabaseService
{
private readonly IMongoCollection<Device> _Devices;
public DeviceDatabaseService(IConfiguration config)
{
var client = new MongoClient(config.GetConnectionString("TabletDb"));
var database = client.GetDatabase("TabletDb");
_Devices = database.GetCollection<Device>("Devices");
}
public List<Device> GetAll()
{
return _Devices.Find(d => true).ToList();
}
public List<Device> GetAllConnected()
{
return _Devices.Find(d => d.Connected).ToList();
}
public Device GetById(string id)
{
return _Devices.Find<Device>(d => d.Id == id).FirstOrDefault();
}
public bool IsExist(string id)
{
return _Devices.Find<Device>(d => d.Id == id).FirstOrDefault() != null ? true : false;
}
public Device Create(Device device)
{
_Devices.InsertOne(device);
return device;
}
public Device Update(string id, Device deviceIn)
{
_Devices.ReplaceOne(d => d.Id == id, deviceIn);
return deviceIn;
}
public void Remove(string id)
{
_Devices.DeleteOne(d => d.Id == id);
}
}
}

View File

@ -61,5 +61,10 @@ namespace Manager.Services
_Sections.DeleteOne(s => s.Id == id);
}
public void DeleteAllFromConfiguration(string configurationId)
{
_Sections.DeleteMany(s => s.ConfigurationId == configurationId);
}
}
}

View File

@ -104,6 +104,7 @@ namespace ManagerService
services.AddScoped<SectionDatabaseService>();
services.AddScoped<ConfigurationDatabaseService>();
services.AddScoped<RessourceDatabaseService>();
services.AddScoped<DeviceDatabaseService>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.