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