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