PageRenderTime 45ms CodeModel.GetById 12ms RepoModel.GetById 1ms app.codeStats 0ms

/collegeCompanionApp/collegeCompanionApp/Controllers/HomeController.cs

https://bitbucket.org/nStark18/collegecompanion_nas
C# | 389 lines | 213 code | 70 blank | 106 comment | 22 complexity | ea435c4f65e2721ce2a3081b34699644 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. namespace collegeCompanionApp.Controllers
  16. {
  17. public class HomeController : Controller
  18. {
  19. //Global Parameters
  20. string schoolName = "";
  21. string state = "";
  22. string city = "";
  23. string accreditor = "";
  24. string ownership = "";
  25. string finLimit = "";
  26. string acceptRate = "";
  27. int storedLimit = 0;
  28. public ActionResult Index()
  29. {
  30. return View();
  31. }
  32. public ActionResult About()
  33. {
  34. return View();
  35. }
  36. public ActionResult Contact()
  37. {
  38. return View();
  39. }
  40. public ActionResult SchoolSearch()
  41. {
  42. return View();
  43. }
  44. public ActionResult StateSearch()
  45. {
  46. return View();
  47. }
  48. public ActionResult SearchForm()
  49. {
  50. FormdataDB db = new FormdataDB();
  51. Debug.Assert(db != null, "Database has the wrong connection.");
  52. return View(db);
  53. }
  54. public ActionResult SearchResults()
  55. {
  56. return View();
  57. }
  58. /// <summary>
  59. /// Searches for Colleges via an API call.
  60. /// </summary>
  61. /// <returns>
  62. /// A JSON result of colleges within the requested confines.
  63. /// </returns>
  64. public JsonResult Search()
  65. {
  66. Debug.WriteLine("SearchForm() Method!");
  67. //Get College Scorecard API
  68. //string key = System.Web.Configuration.WebConfigurationManager.AppSettings["CollegeScoreCardAPIKey"];
  69. schoolName = Request.QueryString["school.name"];
  70. state = Request.QueryString["school.state"];
  71. city = Request.QueryString["school.city"];
  72. accreditor = Request.QueryString["school.accreditor"];
  73. ownership = Request.QueryString["school.ownership"];
  74. finLimit = Request.QueryString["school.tuition_revenue_per_fte"];
  75. Debug.WriteLine("FinLimit: " + finLimit);
  76. acceptRate = Request.QueryString["2015.admissions.admission_rate.overall__range"];
  77. // build a WebRequest
  78. WebRequest request = WebRequest.Create(CreateURL(schoolName, state, city, accreditor, ownership, finLimit, acceptRate));
  79. WebResponse response = request.GetResponse();
  80. Stream dataStream = response.GetResponseStream();
  81. StreamReader reader = new StreamReader(response.GetResponseStream());
  82. // Read the content.
  83. string responseFromServer = reader.ReadToEnd();
  84. // Clean up the streams and the response.
  85. reader.Close();
  86. response.Close();
  87. // Create a JObject, using Newtonsoft NuGet package
  88. JObject json = JObject.Parse(responseFromServer);
  89. // Create a serializer to deserialize the string response (string in JSON format)
  90. JavaScriptSerializer serializer = new JavaScriptSerializer();
  91. // Store JSON results in results to be passed back to client (javascript)
  92. var data = serializer.DeserializeObject(responseFromServer);
  93. //saveData(schoolName, state, city, accreditor, ownership, finLimit);
  94. //return CollegeSearch(college);
  95. return Json(data, JsonRequestBehavior.AllowGet);
  96. }
  97. /// <summary>
  98. /// Saves selected data into the College Database
  99. /// </summary>
  100. /// <returns>
  101. /// True if data is successfully saved, False if it is not.
  102. /// </returns>
  103. /// <param name="schoolName">A string from the dataset of API results.</param>
  104. /// <param name="stateName">A string from the dataset of API results.</param>
  105. /// <param name="cityName">A string from the dataset of API results.</param>
  106. /// <param name="accreditor">A string from the dataset of API results.</param>
  107. /// <param name="ownership">An integer from the dataset of API results.</param>
  108. /// <param name="finLimit">An integer from the dataset of API results.</param>
  109. public Boolean SaveData(string schoolName, string stateName, string cityName, string accreditor, int ownership, int cost, int acceptRate)
  110. {
  111. Debug.WriteLine("saveData() Method!");
  112. if (ModelState.IsValid)
  113. {
  114. College db = new College
  115. {
  116. Name = schoolName,
  117. StateName = stateName,
  118. City = cityName,
  119. Accreditor = accreditor,
  120. Focus = Request.QueryString["degreeInput"],
  121. Ownership = ownership,
  122. Cost = cost,
  123. AdmissionRate = acceptRate
  124. };
  125. //db.SaveChanges();
  126. return true;
  127. }
  128. else
  129. {
  130. Debug.WriteLine("Error for SaveData() method.");
  131. return false;
  132. }
  133. }
  134. /// <summary>
  135. /// Creats a URL for the API search based on User Input.
  136. /// </summary>
  137. /// <returns>
  138. /// A URL string.
  139. /// </returns>
  140. /// <param name="schoolName">A string from the user input on the SearchForm.</param>
  141. /// <param name="stateName">A string from the user input on the SearchForm.</param>
  142. /// <param name="cityName">A string from the user input on the SearchForm.</param>
  143. /// <param name="accreditor">A string from the user input on the SearchForm.</param>
  144. /// <param name="ownership">An string from the user input on the SearchForm.</param>
  145. /// <param name="finLimit">An string from the user input on the SearchForm.</param>
  146. public string CreateURL(string schoolName, string stateName, string cityName, string accreditor, string ownership, string finLimit, string acceptRate)
  147. {
  148. Debug.WriteLine("createURL() Method!");
  149. var values = "school.state=" + state;
  150. if (schoolName != "")
  151. {
  152. values = values + "&school.name=" + schoolName;
  153. }
  154. if (city != "")
  155. {
  156. values = values + "&school.city=" + city;
  157. }
  158. if (accreditor != "")
  159. {
  160. values = values + "&school.accreditor=" + accreditor;
  161. }
  162. if (finLimit != null && finLimit != "")
  163. {
  164. if (finLimit.Length == 12)
  165. {
  166. //storedLimit = Convert.ToInt32(finLimit.Substring(0, 5));
  167. values = values + "&school.tuition_revenue_per_fte__range=" + finLimit;
  168. //Debug.WriteLine("Stored Limit: " + storedLimit);
  169. Debug.WriteLine("Fin Limit: " + finLimit);
  170. }
  171. else if (finLimit.Length == 10)
  172. {
  173. //storedLimit = Convert.ToInt32(finLimit.Substring(0, 3));
  174. values = values + "&school.tuition_revenue_per_fte__range=" + finLimit;
  175. //Debug.WriteLine("Stored Limit: " + storedLimit);
  176. Debug.WriteLine("Fin Limit: " + finLimit);
  177. }
  178. else
  179. {
  180. //storedLimit = Convert.ToInt32(finLimit); // get substring of val. and convert to integer. sp4 **************
  181. values = values + "&school.tuition_revenue_per_fte=" + finLimit;
  182. //Debug.WriteLine("Stored Limit: " + storedLimit);
  183. Debug.WriteLine("Fin Limit: " + finLimit);
  184. }
  185. }
  186. values = values + "&2015.admissions.admission_rate.overall__range=" + acceptRate;
  187. values = values + "&school.ownership=" + ownership;
  188. var source = "https://api.data.gov/ed/collegescorecard/v1/schools?"; //Source
  189. var APIKey = "&api_key=nKOePpukW43MVyeCch1t7xAFZxR2g0EFS3sHNkQ4"; //API Key
  190. var fields = "&_fields=school.name,school.state,school.city,school.accreditor,school.ownership,school.tuition_revenue_per_fte,2015.admissions.admission_rate.overall";
  191. //Fields
  192. //URL to College Scorecard
  193. string url = source + values + APIKey + fields;
  194. //Replace spaces with %20
  195. url = url.Trim();
  196. url = url.Replace(" ", "%20");
  197. Debug.WriteLine("URL: " + url);
  198. return url;
  199. }
  200. public String CheckFinLimit(String finLimit)
  201. {
  202. return finLimit;
  203. }
  204. public ActionResult Yelp()
  205. {
  206. return View();
  207. }
  208. public JsonResult YelpSearch()
  209. {
  210. Debug.WriteLine("YelpSearch() Method!");
  211. //Get Yelp API Key
  212. string YelpAPIKey = System.Web.Configuration.WebConfigurationManager.AppSettings["YelpAPIKey"];
  213. YelpAPIKey = IsAPIKey(YelpAPIKey);
  214. //Get Location
  215. string location = GetLocation(Request.QueryString["location"]);
  216. //Get Term
  217. string term = GetTerm(Request.QueryString["term"]);
  218. //Set Parameters
  219. string param = SetParam(location, term);
  220. //URL Endpoint
  221. var url = SetURL(param);
  222. //URL GET Request
  223. Debug.WriteLine("URL: " + url);
  224. // build a WebRequest
  225. WebRequest request = WebRequest.Create(url);
  226. request.Headers.Add("Authorization", "Bearer " + YelpAPIKey);
  227. WebResponse response = request.GetResponse();
  228. Stream dataStream = response.GetResponseStream();
  229. StreamReader reader = new StreamReader(response.GetResponseStream());
  230. // Read the content.
  231. string responseFromServer = reader.ReadToEnd();
  232. // Clean up the streams and the response.
  233. reader.Close();
  234. response.Close();
  235. // Create a JObject, using Newtonsoft NuGet package
  236. JObject json = JObject.Parse(responseFromServer);
  237. // Create a serializer to deserialize the string response (string in JSON format)
  238. JavaScriptSerializer serializer = new JavaScriptSerializer();
  239. // Store JSON results in results to be passed back to client (javascript)
  240. var data = serializer.DeserializeObject(responseFromServer);
  241. return Json(data, JsonRequestBehavior.AllowGet);
  242. }
  243. //working on getting the xml from zillow's api to work.
  244. //may end up not needing this code.
  245. //public XmlDocument CollegeRentsInArea()
  246. //{
  247. //I have put this at the end so I can just append to the div I want to.
  248. // a url for the zillow calls.
  249. //string theZillowApiUrl =
  250. //"http://www.zillow.com/webservice/GetRegionChildren.htm?zws-id={theAPIKeyHere}&state=" + state + "&city=" + city;
  251. //string collegeRentsUrl = "CollegeRentsInArea?school.state=" + state + "&school.city=" + city;
  252. //WebRequest request = WebRequest.Create(theZillowApiUrl);
  253. //Stream stream = request.GetResponse().GetResponseStream();
  254. //XmlDocument xmlDoc = new XmlDocument();
  255. //stream.Close();
  256. //return xmlDoc;
  257. //}
  258. //public ActionResult CollegeSearch()
  259. //{
  260. // var college = new College();
  261. // college.CollegeName = Request.QueryString["school.name"];
  262. // college.StateName = Request.QueryString["state.name"];
  263. // return View(college);
  264. //}
  265. //[Route("Home/Search")]
  266. //public JsonResult Search()
  267. //{
  268. // Console.WriteLine("In the Search method in Home Controller");
  269. // //Get College Scorecard API
  270. // string key = System.Web.Configuration.WebConfigurationManager.AppSettings["CollegeScoreCardAPIKey"];
  271. // //School Name
  272. // string schoolName = Request.QueryString["schoolName"];
  273. // HttpUtility.UrlPathEncode(schoolName);//Adds %20 to spaces
  274. // //URL to College Scorecard
  275. // string url = "https://api.data.gov/ed/collegescorecard/v1/schools?api_key=" +
  276. // key + "&school.name=" + schoolName + "&_fields=school.name,id";
  277. // //Sends request to College Scorecard to get JSon
  278. // WebRequest request = WebRequest.Create(url);
  279. // request.Credentials = CredentialCache.DefaultCredentials;
  280. // WebResponse response = request.GetResponse(); //The Response
  281. // Stream dataStream = response.GetResponseStream(); //Start Data Stream from Server.
  282. // string reader = new StreamReader(dataStream).ReadToEnd(); //Data Stream to a reader string
  283. // //JSon string to a JSon object
  284. // var serializer = new JavaScriptSerializer();
  285. // var data = serializer.DeserializeObject(reader); //Deserialize string into JSon Object
  286. public string IsAPIKey(string key)
  287. {
  288. if (key.Length <= 5)
  289. {
  290. key = "NoKey";
  291. }
  292. return key;
  293. }
  294. public string GetLocation(string location)
  295. {
  296. if (location == null)
  297. {
  298. Debug.WriteLine("No Location");
  299. }
  300. return location;
  301. }
  302. public string GetTerm(string term)
  303. {
  304. if (term == null)
  305. {
  306. term = "";
  307. }
  308. return term;
  309. }
  310. public string SetParam(string location, string term)
  311. {
  312. return "term=" + term + "&location=" + location + "&limit=10&sort_by=distance";
  313. }
  314. public string SetURL(string param)
  315. {
  316. return "https://api.yelp.com/v3/businesses/search?" + param;
  317. }
  318. }
  319. }