using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using NuGet.Protocol.Plugins; using System.Diagnostics; using System.Net.Mail; using System.Net; using System.Reflection; using System.Text; using VirtualTask.Models; using X.PagedList; using Humanizer; using System.Numerics; using System.Reflection.Metadata; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc.RazorPages; using NuGet.Common; using System.Security.Policy; namespace VirtualTask.Controllers { public class RegistrazioniController : Controller { string apiUrl = string.Empty; string urlBase = string.Empty; string token = string.Empty; string tenant = string.Empty; string errMes = string.Empty; string admin = string.Empty; string urlConfirm = string.Empty; HttpClient client; private readonly IConfiguration _configuration; private readonly IHttpContextAccessor _context; public RegistrazioniController(IConfiguration configuration, IHttpContextAccessor context) { client = new HttpClient(); _configuration = configuration; var key = _configuration["ApplicationInsights:rootUrlApi"]; apiUrl = key; _context = context; var request = _context.HttpContext.Request; urlConfirm=_configuration["ApplicationInsights:rootUrl"]; } #region INDEX public IActionResult Index(string searchString, int? page = 1) { SessionHelper helper = new SessionHelper(this); urlBase = apiUrl + "RegistrazioniList"; admin = helper.GetStringValue("admin"); ViewBag.Admin = admin; Uri baseAddress = new Uri(urlBase); client = new HttpClient(); client.BaseAddress = baseAddress; List modelList = new List(); HttpResponseMessage response = client.GetAsync(baseAddress).Result; if (response.IsSuccessStatusCode) { string data = response.Content.ReadAsStringAsync().Result; modelList = JsonConvert.DeserializeObject>(data); if (!string.IsNullOrEmpty(searchString)) { modelList = modelList.Where(s => s.cognome.ToUpper().Contains(searchString.ToUpper())).ToList(); ViewData["CurrentFilter"] = searchString; } else { ViewData["CurrentFilter"] = null; } if (page != null && page < 1) { page = 1; } var pageSize = 10; var shortLinks = modelList .OrderByDescending(s => s.id) .ToPagedList(page ?? 1, pageSize); return View(shortLinks); } else { errMes = response.Content.ReadAsStringAsync().Result; helper.SetStringValue("errMsg", errMes); return RedirectToAction("Error"); } } #endregion INDEX #region CREATE public IActionResult Create() { return View(); } [HttpPost] public IActionResult Create(Registrazione model) { SessionHelper helper = new SessionHelper(this); if (ModelState.IsValid) { string tokenMail = RandomString(10); model.token = tokenMail; bool bAziPres = false; bool privacy1=false; bAziPres = checkAziendaPresente(model.azienda); if (bAziPres) { ModelState.AddModelError("azienda", "Azienda presente in archivio. Inserire un valore diverso."); } bool bEmail = model.email.Equals(model.emailConf); if (!bEmail) { ModelState.AddModelError("email", "I campi Email e Conferma Email devono essere uguali"); } if(model.privacy1==false) { ModelState.AddModelError("privacy1", "E' necessario accettare la privacy"); privacy1 = true; } if (!bAziPres && bEmail && !privacy1) { urlBase = apiUrl + "registrazioni/add"; Uri baseAddress = new Uri(urlBase); client = new HttpClient(); client.BaseAddress = baseAddress; string data = JsonConvert.SerializeObject(model); StringContent content = new StringContent(data, Encoding.UTF8, "application/json"); HttpResponseMessage response = client.PostAsync(baseAddress, content).Result; if (response.IsSuccessStatusCode) { //mando mail avvenuta richiesta string message = getMailText(model.cognome, tokenMail, model.email); string subject = _configuration["ApplicationInsights:subjectMail"]; bool esito = MailSent(model.email, subject, message); return RedirectToAction("RegistrazioneOk"); } else { errMes = response.Content.ReadAsStringAsync().Result; helper.SetStringValue("errMsg", errMes); return RedirectToAction("Error"); } } else { return View("Create", model); } } else { foreach (var Elemento in ModelState.Values) { foreach (var Errore in Elemento.Errors) { string ErroreRilevato = Errore.ErrorMessage; } } return View("Create", model); } } public IActionResult RegistrazioneOk() { return View(); } public async Task ConfirmEmail(string Token, string Email) { SessionHelper helper = new SessionHelper(this); urlBase = apiUrl + "RegistrazioniList"; admin = helper.GetStringValue("admin"); ViewBag.Admin = admin; Uri baseAddress = new Uri(urlBase); client = new HttpClient(); client.BaseAddress = baseAddress; List modelList = new List(); HttpResponseMessage response = client.GetAsync(baseAddress).Result; if (response.IsSuccessStatusCode) { string data = response.Content.ReadAsStringAsync().Result; modelList = JsonConvert.DeserializeObject>(data); var reg=modelList.Where(t=>t.email.Equals(Email)&& t.token.Equals(Token)).ToList(); var trovato = reg.First(); UpdRegistrazione(trovato); //mando mail riepilogo dati registrazione string message = getMailTextRiepilogo(trovato); string subject= _configuration["ApplicationInsights:subjectMailRiepilogo"]; bool esito = MailSent(trovato.email, subject, message); return RedirectToAction("RegistrazioneFinished"); } else { errMes = response.Content.ReadAsStringAsync().Result; helper.SetStringValue("errMsg", errMes); return RedirectToAction("Error"); } } public IActionResult RegistrazioneFinished() { return View(); } #endregion CREATE #region DETAILS public IActionResult Details(int id) { SessionHelper helper = new SessionHelper(this); urlBase = apiUrl + "registrazioniList"; //urlBase = "http://10.0.0.187:8000/api/Polo/RegistrazioniList"; Uri baseAddress = new Uri(urlBase); client = new HttpClient(); client.BaseAddress = baseAddress; admin = helper.GetStringValue("admin"); ViewBag.Admin = admin; Registrazione reg = new Registrazione(); List modelList = new List(); HttpResponseMessage response = client.GetAsync(baseAddress).Result; if (response.IsSuccessStatusCode) { string data = response.Content.ReadAsStringAsync().Result; modelList = JsonConvert.DeserializeObject>(data); reg = modelList.Where(x => x.id == id).First(); } else { errMes = response.Content.ReadAsStringAsync().Result; helper.SetStringValue("errMsg", errMes); return RedirectToAction("Error"); } return View(reg); } #endregion DETAILS #region EDIT public IActionResult Edit(int id) { SessionHelper helper = new SessionHelper(this); //token = helper.GetStringValue("tok"); //apiUrl = helper.GetStringValue("apiUrl"); //urlBase = apiUrl + "chiusureVtList"; //urlBase = "http://10.0.0.187:8000/api/Polo/RegistrazioniList"; urlBase = apiUrl + "registrazioniList"; //urlBase = urlBase + "?token=" + token; Uri baseAddress = new Uri(urlBase); client = new HttpClient(); client.BaseAddress = baseAddress; admin = helper.GetStringValue("admin"); ViewBag.Admin = admin; Registrazione reg = new Registrazione(); List modelList = new List(); HttpResponseMessage response = client.GetAsync(baseAddress).Result; if (response.IsSuccessStatusCode) { string data = response.Content.ReadAsStringAsync().Result; modelList = JsonConvert.DeserializeObject>(data); reg = modelList.Where(x => x.id == id).First(); } else { errMes = response.Content.ReadAsStringAsync().Result; helper.SetStringValue("errMsg", errMes); return RedirectToAction("Error"); } return View(reg); } [HttpPost] public IActionResult Edit(Registrazione model) { SessionHelper helper = new SessionHelper(this); //token = helper.GetStringValue("tok"); //tenant = helper.GetStringValue("tenant"); //if (string.IsNullOrEmpty(token)) //{ // return RedirectToAction("Index", "Login"); //} model.azienda = tenant; //apiUrl = helper.GetStringValue("apiUrl"); //urlBase = apiUrl + "registrazioni/mod"; urlBase = apiUrl + "http://10.0.0.187:8000/api/Polo/registrazioni/mod"; //urlBase = urlBase + "?token=" + token; Uri baseAddress = new Uri(urlBase); client = new HttpClient(); client.BaseAddress = baseAddress; admin = helper.GetStringValue("admin"); ViewBag.Admin = admin; string data = JsonConvert.SerializeObject(model); StringContent content = new StringContent(data, Encoding.UTF8, "application/json"); HttpResponseMessage response = client.PostAsync(baseAddress, content).Result; if (response.IsSuccessStatusCode) { return RedirectToAction("Index"); } else { errMes = response.Content.ReadAsStringAsync().Result; helper.SetStringValue("errMsg", errMes); return RedirectToAction("Error"); } } #endregion EDIT #region DELETE [HttpGet] public IActionResult Delete(int id) { SessionHelper helper = new SessionHelper(this); //token = helper.GetStringValue("tok"); //apiUrl = helper.GetStringValue("apiUrl"); //urlBase = apiUrl + "chiusureVtList"; urlBase = "http://10.0.0.187:8000/api/Polo/RegistrazioniList"; //urlBase = urlBase + "?token=" + token; Uri baseAddress = new Uri(urlBase); client = new HttpClient(); client.BaseAddress = baseAddress; admin = helper.GetStringValue("admin"); ViewBag.Admin = admin; Registrazione reg = new Registrazione(); List modelList = new List(); HttpResponseMessage response = client.GetAsync(baseAddress).Result; if (response.IsSuccessStatusCode) { string data = response.Content.ReadAsStringAsync().Result; modelList = JsonConvert.DeserializeObject>(data); reg = modelList.Where(x => x.id.Equals(id)).First(); return View(reg); } else { errMes = response.Content.ReadAsStringAsync().Result; helper.SetStringValue("errMsg", errMes); return RedirectToAction("Error"); } } [HttpPost, ActionName("DeleteConfirmed")] public IActionResult DeleteConfirmed(int id) { SessionHelper helper = new SessionHelper(this); //token = helper.GetStringValue("tok"); //apiUrl = helper.GetStringValue("apiUrl"); urlBase = /*apiUrl + */"http://10.0.0.187:8000/api/Polo/Registrazioni/del?" + "id=" + id /*+ "&"*/; //urlBase = urlBase + "token=" + token; Uri baseAddress = new Uri(urlBase); client = new HttpClient(); client.BaseAddress = baseAddress; admin = helper.GetStringValue("admin"); ViewBag.Admin = admin; string data = JsonConvert.SerializeObject(id); StringContent content = new StringContent(data, Encoding.UTF8, "application/json"); HttpResponseMessage response = client.PostAsync(baseAddress, content).Result; if (response.IsSuccessStatusCode) { return RedirectToAction("Index"); } else { errMes = response.Content.ReadAsStringAsync().Result; helper.SetStringValue("errMsg", errMes); return RedirectToAction("Error"); } } #endregion DELETE [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { SessionHelper helper = new SessionHelper(this); string e = helper.GetStringValue("errMsg"); return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier, ErrMsg = e }); } private bool checkAziendaPresente(string azienda) { bool trovato = false; bool bAziPres = false; //urlBase = "http://10.0.0.187:8000/api/Polo/AziendePresentiList"; urlBase = apiUrl + "AziendePresentiList"; Uri baseAddress = new Uri(urlBase); client = new HttpClient(); client.BaseAddress = baseAddress; List modelList = new List(); HttpResponseMessage response = client.GetAsync(baseAddress).Result; if (response.IsSuccessStatusCode) { string data = response.Content.ReadAsStringAsync().Result; modelList = JsonConvert.DeserializeObject>(data); foreach(AziendaPres a in modelList) { if(!string.IsNullOrEmpty(a.tccodazi) && a.tccodazi.Trim().Equals(azienda)) trovato = true; } bAziPres = trovato; } return bAziPres; } private bool MailSent(string receiver, string subject, string message) { //REMEMBER per una mail gmail bisogna andare nelle impostazioni //e impostare "Accesso app meno sicure" a ON bool sent = false; string senderMail = _configuration["ApplicationInsights:mittenteMail"]; string senderName = _configuration["ApplicationInsights:nomeMail"]; string pwdMail = _configuration["ApplicationInsights:pwdMail"]; //string message = getMailText(nome, tokenMail, receiver); var senderEmail = new MailAddress(senderMail, senderName); var receiverEmail = new MailAddress(receiver, "Receiver"); var password = pwdMail; var sub = subject; var body = message; var smtp = new SmtpClient { Host = "smtp.gmail.com", Port = 587, EnableSsl = true, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential(senderEmail.Address, password) }; using (var mess = new MailMessage(senderEmail, receiverEmail) { Subject = subject, Body = body, IsBodyHtml = true }) { smtp.Send(mess); } return sent; } private string getMailText(string nome,string tokenEmail, string emailReg) { string txt = string.Empty; StringBuilder sb=new StringBuilder(); sb.Append(urlConfirm); sb.Append("/Registrazioni/ConfirmEmail"); sb.Append("?Token="); sb.Append(tokenEmail); sb.Append("&Email="); sb.Append(emailReg); string url = sb.ToString(); txt = string.Format("Gentile sig. {0}
Grazie per essersi registrato. Per completare la registrazione fare click al link: Conferma", nome, url) ; //txt = "titolo contenuto
contenuto mail di registrazione"; return txt; } private string getMailTextRiepilogo(Registrazione r) { string txt = string.Empty; StringBuilder sb = new StringBuilder(); sb.Append(string.Format("Gentile sig. {0}
", r.cognome)); sb.Append("Le confermiamo il completamento della procedura di registrazione
"); sb.Append("Di seguito il riepilogo della sua registrazione:
"); sb.Append(string.Format("Nome: {0}
", !string.IsNullOrEmpty(r.nome)?r.nome:string.Empty)); sb.Append(string.Format("Cognome: {0}
", !string.IsNullOrEmpty(r.cognome) ? r.cognome : string.Empty)); sb.Append(string.Format("Telefono: {0}
", !string.IsNullOrEmpty(r.telefono) ? r.telefono : string.Empty)); sb.Append(string.Format("Cellulare: {0}
", !string.IsNullOrEmpty(r.cellulare) ? r.cellulare : string.Empty)); sb.Append(string.Format("Email: {0}
", !string.IsNullOrEmpty(r.email) ? r.email : string.Empty)); sb.Append(string.Format("Azienda: {0}
", !string.IsNullOrEmpty(r.azienda) ? r.azienda : string.Empty)); sb.Append(string.Format("Città: {0}
", !string.IsNullOrEmpty(r.citta) ? r.citta : string.Empty)); sb.Append(string.Format("Provincia: {0}
", !string.IsNullOrEmpty(r.provincia) ? r.provincia : string.Empty)); sb.Append(string.Format("Nazione: {0}
", !string.IsNullOrEmpty(r.nazione) ? r.nazione : string.Empty)); sb.Append(string.Format("Username: {0}
", !string.IsNullOrEmpty(r.username) ? r.username : string.Empty)); sb.Append(string.Format("Password: {0}
", !string.IsNullOrEmpty(r.passwd) ? r.passwd : string.Empty)); txt = sb.ToString(); return txt; } private static Random random = new Random(); public static string RandomString(int length) { const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; return new string(Enumerable.Repeat(chars, length) .Select(s => s[random.Next(s.Length)]).ToArray()); } public bool UpdRegistrazione(Registrazione model) { bool upd=false; model.attivato = "S"; urlBase = apiUrl + "registrazioni/mod"; Uri baseAddress = new Uri(urlBase); client = new HttpClient(); client.BaseAddress = baseAddress; string data = JsonConvert.SerializeObject(model); StringContent content = new StringContent(data, Encoding.UTF8, "application/json"); HttpResponseMessage response = client.PostAsync(baseAddress, content).Result; if (response.IsSuccessStatusCode) { upd = true; } return upd; } } }