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