PageRenderTime 51ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/CA_sem2/CA_sem2/Controllers/HomeController.cs

https://github.com/elennon/RAD_301
C# | 262 lines | 220 code | 21 blank | 21 comment | 49 complexity | 96674c125676496880ee352d6cf066bd MD5 | raw file
  1. using CA_sem2.DAL;
  2. using CA_sem2.Models;
  3. using Newtonsoft.Json.Linq;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Net.Http;
  9. using System.Net.Http.Headers;
  10. using System.Threading.Tasks;
  11. using System.Web;
  12. using System.Web.Mvc;
  13. using System.Xml;
  14. using System.Xml.Linq;
  15. using System.Xml.XPath;
  16. namespace CA_sem2.Controllers
  17. {
  18. public class HomeController : Controller
  19. {
  20. //TourContext db = new TourContext();
  21. private ITourRepository db;
  22. HttpClient client;
  23. public HomeController(ITourRepository repo)
  24. {
  25. db = repo;
  26. }
  27. public ActionResult Index()
  28. {
  29. //var y = db.getAllTrips();
  30. //return View(y);
  31. return View("ApiIndex");
  32. }
  33. [HttpPost]
  34. public JsonResult Create(Trip tr)
  35. {
  36. if (tr.TripName == null) return Json(new { hasError = true, message = "You must enter a name for this trip!" }, JsonRequestBehavior.AllowGet);
  37. else if (tr.StartLocation == null) return Json(new { hasError = true, message = "You must enter a start location!" }, JsonRequestBehavior.AllowGet);
  38. else if (tr.FinishLocation == null) return Json(new { hasError = true, message = "You must enter a finish location!" }, JsonRequestBehavior.AllowGet);
  39. else if (tr.StartDate.ToShortDateString() == "01/01/0001") return Json(new { hasError = true, message = "You must enter a start date!" }, JsonRequestBehavior.AllowGet);
  40. else if (tr.FinishDate.ToShortDateString() == "01/01/0001") return Json(new { hasError = true, message = "You must enter a finish date!" }, JsonRequestBehavior.AllowGet);
  41. else if (tr.StartDate > tr.FinishDate) return Json(new { hasError = true, message = "You must start before you finish!" }, JsonRequestBehavior.AllowGet);
  42. else if (tr.StartDate > DateTime.Now) return Json(new { hasError = true, message = "You must enter a date in the future!" }, JsonRequestBehavior.AllowGet);
  43. else if (tr.MinGuests == 0) return Json(new { hasError = true, message = "You must enter a minnimum number of guests!" }, JsonRequestBehavior.AllowGet);
  44. else
  45. {
  46. try
  47. {
  48. db.insertTrip(tr);
  49. return Json(new { hasError = false, message = "All went well - new trip created" }, JsonRequestBehavior.AllowGet);
  50. }
  51. catch (Exception ex)
  52. {
  53. return Json(new { hasError = true, message = "error: " + ex.Message }, JsonRequestBehavior.AllowGet);
  54. }
  55. }
  56. }
  57. public ActionResult _Create()
  58. {
  59. //return View("Create");
  60. return PartialView();
  61. }
  62. public JsonResult AddLeg(Leg lg)
  63. {
  64. var trp = db.findTrip(lg.TripId);
  65. lg.Trip = trp;
  66. if (lg.FinishDate > trp.FinishDate)
  67. {
  68. ViewBag.resultMessage = "Finish date can't be later than trip finish date";
  69. return Json(new { hasError = true, message = "Finish date can't be later than trip finish date" },
  70. JsonRequestBehavior.AllowGet);
  71. }
  72. else if (lg.FinishDate <= trp.StartDate)
  73. {
  74. ViewBag.resultMessage = "Finish date must be after trip start date";
  75. return Json(new { hasError = true, message = "Finish date can't be later than trip finish date" },
  76. JsonRequestBehavior.AllowGet);
  77. }
  78. else if (lg.FinishLocation == "" || lg.FinishLocation == null) return Json(new { hasError = true, message = "You must enter a finish location!" }, JsonRequestBehavior.AllowGet);
  79. else if (lg.FinishDate == null || lg.FinishDate.ToShortDateString() == "01/01/0001") return Json(new { hasError = true, message = "You must enter a finish date!" }, JsonRequestBehavior.AllowGet);
  80. else
  81. {
  82. try
  83. {
  84. db.insertLeg(lg);
  85. if (lg.FinishDate == trp.FinishDate)
  86. {
  87. db.setStatus(trp);
  88. return Json(new { hasError = false, message = "Leg added, " + trp.TripName +" is now complete" }, JsonRequestBehavior.AllowGet);
  89. }
  90. return Json(new { hasError = false, message = "Leg added" }, JsonRequestBehavior.AllowGet);
  91. }
  92. catch (Exception ex)
  93. {
  94. return Json(new { hasError = true, message = "error: " + ex.Message }, JsonRequestBehavior.AllowGet);
  95. }
  96. }
  97. }
  98. [HttpPost]
  99. public ActionResult _AddLeg(int id)
  100. {
  101. Trip tr = db.findTrip(id);
  102. Leg lg = tr.LegsColl[tr.LegsColl.Count() - 1];
  103. if (tr.complete)
  104. {
  105. return PartialView("_TripComplete", lg ); // pass the last leg for completed trip
  106. }
  107. else
  108. return PartialView("_AddLeg", tr); //
  109. }
  110. [HttpGet]
  111. public ActionResult EditTrip(int id) // id is either a trip id (non ajax) or leg id with ajax call
  112. {
  113. if (!Request.IsAjaxRequest()) // id is a trip id
  114. {
  115. Trip trip = db.findTrip(id);
  116. double fullTrip = (trip.FinishDate - trip.StartDate).Days;
  117. Leg g = trip.LegsColl[trip.LegsColl.Count() - 1];
  118. double doneSoFar = (((trip.LegsColl[trip.LegsColl.Count() - 1]).FinishDate) - trip.StartDate).TotalDays;
  119. ViewBag.progress = Convert.ToInt32((doneSoFar / fullTrip) * 100);
  120. ViewBag.Legs = new SelectList(trip.LegsColl, "id", "StartLocation");
  121. if (trip.complete)
  122. {
  123. ViewBag.status = "Completed";
  124. }
  125. else
  126. ViewBag.status = "Not Completed";
  127. return View("EditTrip", trip);
  128. }
  129. else // this to update trip valid => after add guest(id is a leg id)
  130. {
  131. Leg lg = db.findLeg(id);
  132. Trip trip = db.findTrip(lg.Trip.TripId);
  133. db.updateIfValid(trip);
  134. double fullTrip = (trip.FinishDate - trip.StartDate).Days;
  135. Leg g = trip.LegsColl[trip.LegsColl.Count() - 1];
  136. double doneSoFar = (((trip.LegsColl[trip.LegsColl.Count() - 1]).FinishDate) - trip.StartDate).TotalDays;
  137. ViewBag.progress = Convert.ToInt32((doneSoFar / fullTrip) * 100);
  138. ViewBag.Legs = new SelectList(trip.LegsColl, "id", "StartLocation");
  139. if (trip.complete)
  140. {
  141. ViewBag.status = "Completed";
  142. }
  143. else
  144. ViewBag.status = "Not Completed";
  145. return View("EditTrip", trip);
  146. }
  147. }
  148. public async Task<ActionResult> _ShowLegs(int Id) //http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=xml&titles=sligo
  149. {
  150. client = new HttpClient();
  151. //client.BaseAddress = new Uri("http://it.wikipedia.org/w/api.php?");
  152. client.BaseAddress = new Uri("http://en.wikipedia.org/w/api.php?");
  153. client.DefaultRequestHeaders.Accept.Add(
  154. new MediaTypeWithQualityHeaderValue("application/xml"));
  155. Leg lg = db.getLegDets(Id);
  156. //string getUri = "action=query&prop=images&format=xml&titles=sligo";
  157. //var response = client.GetAsync(getUri).Result;
  158. var response = await client.PostAsync("http://en.wikipedia.org/w/api.php?action=query&prop=images&format=xml&titles=" + lg.StartLocation, null);
  159. //var response = await client.PostAsync(getUri, null);
  160. response.EnsureSuccessStatusCode();
  161. var xmlString = response.Content.ReadAsStringAsync().Result;
  162. XDocument doc = XDocument.Parse(xmlString);
  163. //var pic = doc.Root.Elements().Select(a => a.Element("Item")).FirstOrDefault().Value;
  164. //var pics = doc.Root.Elements().Select(x => x.Element("images"));
  165. var title = from e in doc.Descendants("page")
  166. select new {
  167. Title = (string)e.Attribute("title")
  168. };
  169. var pics = from e in doc.Descendants("images").Elements("im").Attributes("title")
  170. select e;
  171. string picFile = "";
  172. foreach (var item in pics)
  173. {
  174. if (item.Value.Contains(".jpg") && item.Value.Contains(lg.StartLocation))
  175. {
  176. //string s = item.Value.Replace(" ", "%");
  177. string s = item.Value.Replace("File", "");
  178. picFile = s;
  179. }
  180. }
  181. if (picFile == "")
  182. {
  183. picFile = "http://upload.wikimedia.org/wikipedia/commons/a/ab/Benbulbenmount.jpg";
  184. ViewBag.pic = picFile;
  185. ViewBag.guests = new SelectList(db.getGuestList(lg), "GuestId", "Name");
  186. return PartialView("_ShowLegs", lg);
  187. }
  188. var response2 = await client.PostAsync("http://en.wikipedia.org/w/api.php?action=query&titles=Image" + picFile + "&prop=imageinfo&iiprop=url&format=xml", null);
  189. //var response2 = await client.PostAsync("http://en.wikipedia.org/w/api.php?action=query&titles=Image:North%20Sligo%20Town.jpg&prop=imageinfo&iiprop=url&format=xml", null);
  190. response2.EnsureSuccessStatusCode();
  191. var xmlString2 = response2.Content.ReadAsStringAsync().Result;
  192. XDocument doc2 = XDocument.Parse(xmlString2);
  193. var picUrl = (from e in doc2.Descendants("imageinfo").Elements("ii").Attributes("url")
  194. select e).FirstOrDefault();
  195. ViewBag.pic = picUrl.Value;
  196. ViewBag.guests = new SelectList(db.getGuestList(lg), "GuestId", "Name");
  197. return PartialView("_ShowLegs", lg);
  198. }
  199. public ActionResult _AddGuests(int Id)
  200. {
  201. ViewBag.LegId = Id;
  202. ViewBag.allGuests = new SelectList(db.getAllGuests(), "GuestId", "Name", Id);
  203. return PartialView();
  204. }
  205. public JsonResult AddGuest(int gts, int id)
  206. {
  207. if (ModelState.IsValid) // if ok insert guest and tag on message with leg id to pass back to refresh _showlegs
  208. {
  209. Guest guest = db.getGuest(gts);
  210. if (db.insertGuest(gts, id) == true)
  211. {
  212. Leg leg = db.findLeg(id);
  213. Trip trp = db.findTrip(leg.TripId);
  214. if (trp.LegsColl.Count() >= trp.MinGuests)
  215. {
  216. return Json(new { hasError = false, message = "All went well - " + guest.Name + " added", Id = id.ToString(), isDup = "no", updateValide = "yes" },
  217. JsonRequestBehavior.AllowGet);
  218. }
  219. else
  220. return Json(new { hasError = false, message = "All went well - " + guest.Name + " added", Id = id.ToString(), isDup = "no", updateValide = "no" },
  221. JsonRequestBehavior.AllowGet);
  222. }
  223. else
  224. return Json(new { hasError = true, message = guest.Name + " has already been booked", isDup = "yes" },
  225. JsonRequestBehavior.AllowGet);
  226. }
  227. else
  228. return Json(new { hasError = true, message = "Failed to insert guest" },
  229. JsonRequestBehavior.AllowGet);
  230. }
  231. //public ActionResult AddGuest(int gts, int id)
  232. //{
  233. // int Id = id;
  234. // if (ModelState.IsValid)
  235. // {
  236. // db.insertGuest(gts, id);
  237. // return RedirectToAction("_ShowLegs/" + Id);
  238. // }
  239. //}
  240. }
  241. }