using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net; using System.Web.Mvc; using System.Web.UI; using AutoMapper; using DR.FV2016.Service.Interfaces; using DR.FV2016.Service.Models; using DR.FV2016.Web.Helpers; using DR.FV2016.Web.Models.Candidate; using DRCMSRedesign.Contracts; namespace DR.FV2016.Web.Controllers { public class CandidateController : Controller { private readonly ICompositeCandidateService _candidateService; private readonly IMatchService _matchService; private readonly IArticleService _articleService; public CandidateController(ICompositeCandidateService candidateService, IMatchService matchService, IArticleService articleService) { if (candidateService == null) throw new ArgumentNullException("candidateService"); if (matchService == null) throw new ArgumentNullException("matchService"); if(articleService == null) throw new ArgumentNullException("articleService"); _candidateService = candidateService; _matchService = matchService; _articleService = articleService; } [OutputCache(Location = OutputCacheLocation.Downstream, Duration = 180)] public ActionResult Candidate(int id) { if (id <= 0) return HttpNotFound(); var candidate = _candidateService.GetCandidate(id); if(candidate == null) throw new NullReferenceException("candidateid"); int numberOfQuestions = Int32.Parse(ConfigurationManager.AppSettings["CandidateTestQuestionCount"]); var candidateAnswersValid = candidate.Answers.Count() == numberOfQuestions; var model = Mapper.Map(_articleService.GetWebCmsArticle("/kandidater")); Mapper.Map(candidate, model); model.IsResponsive = true; SearchableHelper.EnsureUrn(model, "urn:dr:valg2015:kandidater:" + candidate.Id); model.CanonicalLink = string.Format("http://www.dr.dk{0}", candidate.CandidatePageUrl); if (!candidateAnswersValid) return View(model); var questions = _matchService.GetQuestions().ToList(); model.QuestionsAndAnswersViewModel.NumberOfQuestions = numberOfQuestions; if (!questions.Any()) return View(model); try { var questionsAndAnswers = new List(); foreach (var question in questions) { var answer = candidate.Answers.First(q => q.QuestionId == question.Id); questionsAndAnswers.Add(new QuestionAndAnswer { QuestionId = question.Id, QuestionTitle = question.Title, Question = question.Text, Answer = WebUtility.HtmlDecode(answer.Text), AnswerValue = answer.AnswerIndex, }); } model.QuestionsAndAnswersViewModel.QuestionsAndAnswers = questionsAndAnswers; } catch (Exception) { return View(model); } return View(model); } [OutputCache(Location = OutputCacheLocation.Downstream, Duration = 360)] public ActionResult ImageById(int id) { var candidate = _candidateService.GetCandidate(id); if (candidate == null || string.IsNullOrEmpty(candidate.ImageUrl)) return HttpNotFound(); if (candidate.IsPartyLeader) candidate.ImageUrl = string.Format("http://www.dr.dk{0}", candidate.ImageUrl); return Redirect(candidate.ImageUrl); } } }