C # Call rest API

Source: Internet
Author: User

Due to resignation, I am busy looking for a job recently. During this period, I received a computer test question from a company. There are two questions in total, one of which is about the application of rest API. Although I have already said that I do not understand rest during the interview, the interview PM gave me this question. The PM for the interview was relatively friendly, and there was no time limit. As a result, I did not compete. I checked the information and did not do it after more than an hour, so I finally gave up, of course, the interview will fail. So I summarized the cause of the failure, mainly because I didn't know about rest. Taking rest as another form of web service will inevitably lead to failure.

What is rest? I will not elaborate here. Let me explain my understanding. Simply put, rest is a basic HTTP request service that enables resource operations. It supports multiple data formats, such as XML, JSON, and CSV. Web Service is a technology that uses basic XML and SOAP protocol for remote resource access. Therefore, the two are essentially different. Maybe my understanding is not completely correct. Please point out the mistake.

Let's take a look at this question as follows:

Userstory:
As a user I want to be able to see maximum, minimum and average predicted temperature for the following 3 days,
Based on the city that needs to be entered.
Acceptance Criteria:
Windows form application written in C #
One input field to define the city
A ComboBox to select Fahrenheit or Celcius degrees
Use free web service provided by http://www.worldweatheronline.com
The following key can be used to retrieve data: c6bbde7c9c021421323107
Show 'retrieving weather data... 'in status bar when request of data is submitted. Once data is retrieved
Update Status accordingly.
Use of LINQ statements to calculate the minimum, maximum and average temperature.
Main form needs to be responsive at all times
Use of delegates
Retrieval of data and UI logic needs to be seperated in code
Error handling when connection

 

 

The code I wrote is as follows:

Using system; using system. collections. generic; using system. componentmodel; using system. data; using system. drawing; using system. LINQ; using system. text; using system. windows. forms; using system. net; using system. io; using system. XML; using system. XML. LINQ; using system. threading; namespace windowsformsapplication1 {public partial class form1: FORM {public form1 () {initializecomponent (); Init ();} private Void Init () {// initialization unit data list <Object> List = new list <Object> (); list. add (New {key = "Celsius", value = "C"}); list. add (New {key = "Fahrenheit", value = "F"}); cbunit. datasource = List; cbunit. displaymember = "key"; cbunit. valuemember = "value"; cbunit. selectedindex = 0;} private void btcalculate_click (Object sender, eventargs e) {try {slstatus. TEXT = "retrieving weather data ..... "; string city = T Bcity. text; string unit = cbunit. selectedvalue. tostring (); dictionary <string, string> DIC = new dictionary <string, string> (); dic. add ("city", city); dic. add ("unit", Unit); thread = new thread (New parameterizedthreadstart (threadprocess); thread. isbackground = true; thread. start (DIC);} catch (exception ex) {slstatus. TEXT = "retrieving data failed .... ";}}/// <summary> /// background processing thread // </Summary> /// <para M name = "OBJ"> </param> private void threadprocess (Object OBJ) {dictionary <string, string> DIC = OBJ as Dictionary <string, string>; xdocument xmldoc = getdata (DIC ["city"]); setdata (xmldoc, DIC ["unit"]); slstatus. TEXT = "";} /// <summary> /// obtain data /// </Summary> /// <Param name = "city"> </param> /// <returns> </returns> private xdocument getdata (string City) {xdocument Doc; Uri uri = new uri (string. f Ormat (@ "http://free.worldweatheronline.com/feed/weather.ashx? Q = {0}, China & format = xml & num_of_days = 3 & Key = c6bbde7c9c021420.23107 ", city); httpwebrequest request = httpwebrequest. create (URI) as httpwebrequest; using (httpwebresponse response = request. getresponse () as httpwebresponse) {streamreader reader = new streamreader (response. getresponsestream (); string result = reader. readtoend (); stringreader STR = new stringreader (result); Doc = xdocument. load (STR);} RET Urn Doc ;} /// <summary> /// set data /// </Summary> /// <Param name = "Doc"> </param> /// <Param name = "unit"> </param> private void setdata (xdocument Doc, string unit) {var query = from P in Doc. root. elements ("Weather") Select New {date = P. element ("date") = NULL? Null: P. element ("date"). Value, maxc = P. element ("tempmaxc") = NULL? Null: P. element ("tempmaxc"). Value, minc = P. element ("tempminc") = NULL? Null: P. element ("tempminc"). Value, maxf = P. element ("tempmaxf") = NULL? Null: P. element ("tempmaxf"). Value, minf = P. element ("tempminf") = NULL? Null: P. element ("tempminf "). value}; If (unit = "C") {crossthreadaccess (tbmaximum, query. max (P => P. maxc); crossthreadaccess (tbminimum, query. min (P => P. minc);} else {crossthreadaccess (tbmaximum, query. max (P => P. maxf); crossthreadaccess (tbminimum, query. min (P => P. minf);} crossthreadaccess (tbaverage, convert. tostring (convert. toint32 (tbmaximum. text) + convert. toint32 (tbminimum. text ))/ 2 ));} /// <summary> /// access between UI threads /// </Summary> /// <Param name = "control"> </param> /// <Param name = "value"> </param> private void crossthreadaccess (Control, string Value) {If (control. invokerequired) {control. invoke (new action <control, string> (crossthreadaccess), control, value);} else {textbox TB = control as textbox; If (TB! = NULL) TB. Text = value ;}}}}

The effect is as follows:

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.