PageRenderTime 24ms CodeModel.GetById 2ms app.highlight 17ms RepoModel.GetById 1ms app.codeStats 0ms

/collegeCompanionApp/collegeCompanionApp/Controllers/HomeController.cs

https://bitbucket.org/daniel_tapia/collegecompanionfork
C# | 528 lines | 285 code | 99 blank | 144 comment | 23 complexity | 5b246c3a5f54d5f6f6d7230047a11b3c MD5 | raw file
  1using collegeCompanionApp.Models;
  2using System;
  3using System.Collections.Generic;
  4using System.IO;
  5using System.Linq;
  6using System.Net;
  7using System.Web;
  8using System.Web.Mvc;
  9using System.Web.Script.Serialization;
 10using collegeCompanionApp.Models.ViewModel;
 11using System.Diagnostics;
 12using Newtonsoft.Json.Linq;
 13using System.Xml;
 14using System.Data.Linq;
 15using System.Text;
 16
 17
 18
 19namespace collegeCompanionApp.Controllers
 20{
 21    public class HomeController : Controller
 22    {
 23        //Global Parameters
 24        string schoolName = "";
 25        string state = "";
 26        string city = "";
 27        string accreditor = "";
 28        string ownership = "";
 29        string finLimit = "";
 30        string acceptRate = "";
 31        int storedLimit = 0;
 32        //Adding in the context for the Colleges&CompanionUsers&College_User_Relations
 33        CompanionContext companiondb = new CompanionContext();
 34
 35        public ActionResult Index()
 36        {
 37            return View();
 38        }
 39
 40        public ActionResult Travel()
 41        {
 42            return View();
 43        }
 44
 45        public ActionResult SearchesMenu()
 46        {
 47            return View();
 48        }
 49
 50        public ActionResult About()
 51        {
 52            return View();
 53        }
 54
 55        public ActionResult Contact()
 56        {
 57            return View();
 58        }
 59
 60        public ActionResult Test()
 61        {
 62            return View();
 63        }
 64
 65        /// <summary>
 66        /// Searches for ratings of Walking, Transit & Bike for a given city using Walk Score API.
 67        /// </summary>
 68        /// <param name="location">A string from the user provided variable "locationInput" in TravelSearch.js</param>
 69        /// <returns>
 70        /// A "Content" result of JSON String with ratings within the requested city.
 71        /// </returns>
 72        public ActionResult WalkScoreSearch()
 73        {
 74            //Get user input data from Javascript file "TravelSearch.js"
 75            var street = Request.QueryString["addressInput"];
 76            var city = Request.QueryString["cityInput"];
 77            var state = Request.QueryString["stateInput"];
 78            var zipcode = Request.QueryString["zipInput"];
 79            var lat = Request.QueryString["latitude"];
 80            var lon = Request.QueryString["longitude"];
 81            var location = street + city + state + zipcode;
 82
 83            location = location.Replace(" ", "%20");
 84
 85            //User Stringbuilder to make a URL for the request.
 86            StringBuilder sb = new StringBuilder();
 87            sb.Append("http://api.walkscore.com/score?format=json&");
 88            sb.Append("&address=" + location);
 89            sb.Append("&lon=" + lon);
 90            sb.Append("&lat=" + lat);
 91            sb.Append("&transit=1&bike=1");
 92            sb.Append("&wsapikey=");
 93            sb.Append(System.Web.Configuration.WebConfigurationManager.AppSettings["WalkScoreAPIKey"]);
 94            Debug.WriteLine(sb.ToString());
 95
 96            // Make a web request to get the list of classes.
 97            WebRequest request = HttpWebRequest.Create(sb.ToString()); //Takes an arguement of the URL of the webserver being targeted.
 98            // Using a web response process the file returned from the API.
 99            WebResponse response = request.GetResponse();
100
101            string resultString;
102            using (var reader = new StreamReader(response.GetResponseStream()))
103            {
104                // Get the data from the stream reader to parse data into usable format
105                resultString = reader.ReadToEnd();
106            }
107            //Note: This is completed without a JSON parse action so don't treat it like the other methods! lol
108            return Content(resultString, "application/json");
109        }
110
111        public ActionResult SearchForm()
112        {
113            FormdataDB formdb = new FormdataDB();
114            Debug.Assert(formdb != null, "Database has the wrong connection.");
115            return View(formdb);
116        }
117
118        public ActionResult SearchResults()
119        {
120            return View();
121        }
122
123        /// <summary>
124        /// Searches for Colleges via an API call.
125        /// </summary>
126        /// <returns>
127        /// A JSON result of colleges within the requested confines.
128        /// </returns>
129        public JsonResult Search()
130        {
131            Debug.WriteLine("SearchForm() Method!");
132
133            //Get College Scorecard API
134            schoolName = Request.QueryString["school.name"];
135            state = Request.QueryString["school.state"];
136            city = Request.QueryString["school.city"];
137            accreditor = Request.QueryString["school.accreditor"];
138            ownership = Request.QueryString["school.ownership"];
139            finLimit = Request.QueryString["school.tuition_revenue_per_fte"];
140            Debug.WriteLine("FinLimit: " + finLimit);
141            acceptRate = Request.QueryString["2015.admissions.admission_rate.overall__range"];
142
143            // build a WebRequest
144            WebRequest request = WebRequest.Create(CreateURL(schoolName, state, city, accreditor, ownership, finLimit, acceptRate));
145            WebResponse response = request.GetResponse();
146            Stream dataStream = response.GetResponseStream();
147            StreamReader reader = new StreamReader(response.GetResponseStream());
148
149            // Read the content.  
150            string responseFromServer = reader.ReadToEnd();
151
152            // Clean up the streams and the response.  
153            reader.Close();
154            response.Close();
155
156            // Create a JObject, using Newtonsoft NuGet package
157            JObject json = JObject.Parse(responseFromServer);
158
159            // Create a serializer to deserialize the string response (string in JSON format)
160            JavaScriptSerializer serializer = new JavaScriptSerializer();
161
162            // Store JSON results in results to be passed back to client (javascript)
163            var data = serializer.DeserializeObject(responseFromServer);
164
165            //saveData(schoolName, state, city, accreditor, ownership, finLimit);
166
167            //return CollegeSearch(college);
168            return Json(data, JsonRequestBehavior.AllowGet);
169        }
170
171        /// <summary>
172        /// Saves selected data into the College Database
173        /// </summary>
174        /// <returns>
175        /// True if data is successfully saved, False if it is not.
176        /// </returns>
177        /// <param name="schoolName">A string from the dataset of API results.</param>
178        /// <param name="stateName">A string from the dataset of API results.</param>
179        /// <param name="cityName">A string from the dataset of API results.</param>
180        /// <param name="accreditor">A string from the dataset of API results.</param>
181        /// <param name="ownership">An integer from the dataset of API results.</param>
182        /// <param name="finLimit">An integer from the dataset of API results.</param>
183        public ActionResult SaveData([Bind(Include = "CollegeID,Name,StateName,City,Accreditor,Ownership,Cost")]College college)
184        {
185            if (User.Identity.IsAuthenticated)
186            {
187                Debug.WriteLine("saveData() Method!");
188
189                if (ModelState.IsValid)
190                {
191                    companiondb.Colleges.Add(college);
192
193                    companiondb.SaveChanges();
194                    return View();
195                }
196                else
197                {
198                    Debug.WriteLine("Error for SaveData() method.");
199                    return View();
200                }
201            }
202            else
203            {
204                return RedirectToAction("Register","Account");
205            }
206            //College db = new College
207            //{
208            // Name = schoolName,
209            //StateName = stateName,
210            //City = cityName,
211            //Accreditor = accreditor,
212            //Focus = Request.QueryString["degreeInput"],
213            //Ownership = ownership,
214            //Cost = cost,
215            //AdmissionRate = acceptRate
216            //};
217        }
218
219        /// <summary>
220        /// Creats a URL for the API search based on User Input.
221        /// </summary>
222        /// <returns>
223        /// A URL string.
224        /// </returns>
225        /// <param name="schoolName">A string from the user input on the SearchForm.</param>
226        /// <param name="stateName">A string from the user input on the SearchForm.</param>
227        /// <param name="cityName">A string from the user input on the SearchForm.</param>
228        /// <param name="accreditor">A string from the user input on the SearchForm.</param>
229        /// <param name="ownership">An string from the user input on the SearchForm.</param>
230        /// <param name="finLimit">An string from the user input on the SearchForm.</param>
231        public string CreateURL(string schoolName, string stateName, string cityName, string accreditor, string ownership, string finLimit, string acceptRate)
232        {
233            Debug.WriteLine("createURL() Method!");
234
235            var values = "school.state=" + state;
236
237            if (schoolName != "")
238            {
239                values = values + "&school.name=" + schoolName;
240            }
241            if (city != "")
242            {
243                values = values + "&school.city=" + city;
244            }
245            if (accreditor != "")
246            {
247                values = values + "&school.accreditor=" + accreditor;
248            }
249            if (finLimit != null && finLimit != "")
250            {
251                if (finLimit.Length == 12)
252                {
253                    //storedLimit = Convert.ToInt32(finLimit.Substring(0, 5));
254                    values = values + "&school.tuition_revenue_per_fte__range=" + finLimit;
255                    //Debug.WriteLine("Stored Limit: " + storedLimit);
256                    Debug.WriteLine("Fin Limit: " + finLimit);
257                }
258                else if (finLimit.Length == 10)
259                {
260                    //storedLimit = Convert.ToInt32(finLimit.Substring(0, 3));
261                    values = values + "&school.tuition_revenue_per_fte__range=" + finLimit;
262                    //Debug.WriteLine("Stored Limit: " + storedLimit);
263                    Debug.WriteLine("Fin Limit: " + finLimit);
264                }
265                else
266                {
267                    //storedLimit = Convert.ToInt32(finLimit);  // get substring of val. and convert to integer. sp4 **************
268                    values = values + "&school.tuition_revenue_per_fte=" + finLimit;
269                    //Debug.WriteLine("Stored Limit: " + storedLimit);
270                    Debug.WriteLine("Fin Limit: " + finLimit);
271                }
272            }
273            values = values + "&2015.admissions.admission_rate.overall__range=" + acceptRate;
274            values = values + "&school.ownership=" + ownership;
275
276            var source = "https://api.data.gov/ed/collegescorecard/v1/schools?"; //Source
277            var APIKey = System.Web.Configuration.WebConfigurationManager.AppSettings["CollegeScoreCardAPIKey"]; //API Key
278            var fields = "&_fields=school.name,school.state,school.city,school.accreditor,school.ownership,school.tuition_revenue_per_fte,2015.admissions.admission_rate.overall";
279            //Fields 
280            //URL to College Scorecard
281            string url = source + values + APIKey + fields;
282            //Replace spaces with %20 
283            url = url.Trim();
284            url = url.Replace(" ", "%20");
285            Debug.WriteLine("URL: " + url);
286
287            return url;
288        }
289
290        public String CheckFinLimit(String finLimit)
291
292        {
293
294            return finLimit;
295
296        }
297
298
299
300        public ActionResult Yelp()
301        {
302
303            return View();
304
305        }
306
307
308        public JsonResult YelpSearch()
309        {
310            Debug.WriteLine("YelpSearch() Method!");
311
312            //Get Yelp API Key
313            string YelpAPIKey = System.Web.Configuration.WebConfigurationManager.AppSettings["YelpAPIKey"];
314            YelpAPIKey = IsAPIKey(YelpAPIKey);
315            //Get Location
316            string location = GetLocation(Request.QueryString["location"]);
317            //Get Term
318            string term = GetTerm(Request.QueryString["term"]);
319            //Set Parameters
320            string param = SetParam(location, term);
321            //URL Endpoint
322            var url = SetURL(param);
323
324            //URL GET Request
325            Debug.WriteLine("URL: " + url);
326
327            // build a WebRequest
328            WebRequest request = WebRequest.Create(url);
329            request.Headers.Add("Authorization", "Bearer " + YelpAPIKey);
330            WebResponse response = request.GetResponse();
331            Stream dataStream = response.GetResponseStream();
332            StreamReader reader = new StreamReader(response.GetResponseStream());
333
334            // Read the content.  
335            string responseFromServer = reader.ReadToEnd();
336
337            // Clean up the streams and the response.  
338            reader.Close();
339            response.Close();
340
341            // Create a JObject, using Newtonsoft NuGet package
342            JObject json = JObject.Parse(responseFromServer);
343
344            // Create a serializer to deserialize the string response (string in JSON format)
345            JavaScriptSerializer serializer = new JavaScriptSerializer();
346
347            // Store JSON results in results to be passed back to client (javascript)
348            var data = serializer.DeserializeObject(responseFromServer);
349
350            return Json(data, JsonRequestBehavior.AllowGet);
351        }
352
353		
354        /// Yelp NUnit Testing
355        public string IsAPIKey(string key)
356        {
357            if (key.Length <= 5)
358            {
359                key = "NoKey";
360            }
361            return key;
362        }
363
364        public string GetLocation(string location)
365        {
366            if (location == null)
367            {
368                Debug.WriteLine("No Location");
369            }
370            return location;
371        }
372
373        public string GetTerm(string term)
374        {
375            if (term == null)
376            {
377                term = "";
378            }
379            return term;
380        }
381
382        public string SetParam(string location, string term)
383        {
384            return "term=" + term + "&location=" + location + "&limit=10&sort_by=distance";
385        }
386
387        public string SetURL(string param)
388        {
389            return "https://api.yelp.com/v3/businesses/search?" + param;
390        }
391
392
393        //working on getting the xml from zillow's api to work.
394        //may end up not needing this code.
395        //public XmlDocument CollegeRentsInArea()
396        //{
397
398
399        //I have put this at the end so I can just append to the div I want to.
400        // a url for the zillow calls.
401        //string theZillowApiUrl =
402        //"http://www.zillow.com/webservice/GetRegionChildren.htm?zws-id={theAPIKeyHere}&state=" + state + "&city=" + city;
403
404        //string collegeRentsUrl = "CollegeRentsInArea?school.state=" + state + "&school.city=" + city;
405
406        //WebRequest request = WebRequest.Create(theZillowApiUrl);
407        //Stream stream = request.GetResponse().GetResponseStream();
408
409        //XmlDocument xmlDoc = new XmlDocument();
410
411        //stream.Close();
412
413        //return xmlDoc;
414        //}
415
416        //public ActionResult CollegeSearch()
417        //{
418        //    var college = new College();
419        //    college.CollegeName = Request.QueryString["school.name"];
420        //    college.StateName = Request.QueryString["state.name"];
421
422        //    return View(college);
423        //}
424
425        //[Route("Home/Search")]
426        //public JsonResult Search()
427        //{
428        //    Console.WriteLine("In the Search method in Home Controller");
429
430        //    //Get College Scorecard API
431        //    string key = System.Web.Configuration.WebConfigurationManager.AppSettings["CollegeScoreCardAPIKey"];
432        //    //School Name
433        //    string schoolName = Request.QueryString["schoolName"];
434        //    HttpUtility.UrlPathEncode(schoolName);//Adds %20 to spaces
435
436
437        //    //URL to College Scorecard
438        //    string url = "https://api.data.gov/ed/collegescorecard/v1/schools?api_key=" + 
439        //        key + "&school.name=" + schoolName + "&_fields=school.name,id";
440
441
442        //    //Sends request to College Scorecard to get JSon
443        //    WebRequest request = WebRequest.Create(url);
444        //    request.Credentials = CredentialCache.DefaultCredentials;
445        //    WebResponse response = request.GetResponse(); //The Response            
446        //    Stream dataStream = response.GetResponseStream(); //Start Data Stream from Server.            
447        //    string reader = new StreamReader(dataStream).ReadToEnd(); //Data Stream to a reader string
448
449
450        //    //JSon string to a JSon object             
451        //    var serializer = new JavaScriptSerializer();
452        //    var data = serializer.DeserializeObject(reader); //Deserialize string into JSon Object
453
454
455
456        public ActionResult Demographic()
457        {
458            return View();
459        }
460
461        public JsonResult DemographicSearch()
462        {
463            Debug.WriteLine("DemographicSearch() Method!");
464
465            //Get Demographic API Key
466            string DemoAPIKey = System.Web.Configuration.WebConfigurationManager.AppSettings["DemographicAPIKey"];
467            //Gets the latitude & longitude
468            string coordinates = GetCoordinates(Request.QueryString["latitude"], Request.QueryString["longitude"]);
469            //Set parameters with coordinates & variables
470            string param = SetDemoParams(coordinates, Request.QueryString["variables"]);// + "/" + variables);
471            //Endpoint Description Link: https://market.mashape.com/mapfruition/demographicinquiry#inquire-by-point
472            //Set up url endpoint with parameters
473            var url = SetDemoURL(param);
474
475            //URL GET Request
476            Debug.WriteLine("JSon URL Call: " + url);
477
478            // build a WebRequest
479            WebRequest request = WebRequest.Create(url);
480            //Add Header with API Key
481            request.Headers.Add("X-Mashape-Key", DemoAPIKey);
482            WebResponse response = request.GetResponse();
483            Stream dataStream = response.GetResponseStream();
484            StreamReader reader = new StreamReader(response.GetResponseStream());
485
486            // Read the content.  
487            string responseFromServer = reader.ReadToEnd();
488
489            // Clean up the streams and the response.  
490            reader.Close();
491            response.Close();
492
493            // Create a JObject, using Newtonsoft NuGet package
494            JObject json = JObject.Parse(responseFromServer);
495
496            // Create a serializer to deserialize the string response (string in JSON format)
497            JavaScriptSerializer serializer = new JavaScriptSerializer();
498
499            // Store JSON results in results to be passed back to client (javascript)
500            var data = serializer.DeserializeObject(responseFromServer);
501
502            return Json(data, JsonRequestBehavior.AllowGet);
503        }
504
505
506        //Demographic NUnit Tests
507        public string SetDemoURL(string param)
508        {
509            string url = "https://mapfruition-demoinquiry.p.mashape.com/inquirebypoint/" + param;
510
511            return url;
512        }
513
514        public string SetDemoParams(string coordinates, string variables)
515        {
516            string param = coordinates + "/" + variables;
517
518            return param;
519        }
520
521        public string GetCoordinates(string lat, string lon)
522        {
523            string cord = lat + "," + lon;
524
525            return cord;
526        }
527    }
528}