1

I don't know how to organize my code. Right now I just dumped everything in MainPage for testing. But what is the proper way to handle getting data from REST web service in Windows Phone 8? I have multiple pages that need to utilize the data that is returned.

    /// <summary>
/// State information for our BeginGetResponse async call
/// </summary>
public class UpdateState
{
    public HttpWebRequest AsyncRequest { get; set; }
    public HttpWebResponse AsyncResponse { get; set; }
}


public partial class MainPage : PhoneApplicationPage
{
    // Constructor
    public MainPage()
    {
        InitializeComponent();

        // Sample code to localize the ApplicationBar
        //BuildLocalizedApplicationBar();
    }

    private async void test()
    {

        var handler = new HttpClientHandler();
        if (handler.SupportsAutomaticDecompression)
        {
            handler.AutomaticDecompression = DecompressionMethods.GZip |
                                             DecompressionMethods.Deflate;
        }

        // form the URI
        UriBuilder fullUri = new UriBuilder("http://test/GetData?");
        fullUri.Query = "format=xml&param=test&dateFrom=20071225&dateTo=20080101";

        var httpClient = new HttpClient(handler);
        var str = await httpClient.GetStringAsync(fullUri.Uri);
        string test = "";
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {


        test();



        // form the URI
        UriBuilder fullUri = new UriBuilder("http://test/GetData?");
        fullUri.Query = "format=xml&param=test&dateFrom=20140124&dateTo=201425 ";

        // initialize a new WebRequest
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(fullUri.Uri);

        // set up the state object for the async request
        UpdateState state = new UpdateState();
        state.AsyncRequest = request;

        // start the asynchronous request
        request.BeginGetResponse(new AsyncCallback(HandleResponse),
            state);
    }

    /// <summary>
    /// Handle the information returned from the async request
    /// </summary>
    /// <param name="asyncResult"></param>
    private void HandleResponse(IAsyncResult asyncResult)
    {
        // get the state information
        UpdateState forecastState = (UpdateState)asyncResult.AsyncState;
        HttpWebRequest forecastRequest = (HttpWebRequest)forecastState.AsyncRequest;

        // end the async request
        forecastState.AsyncResponse = (HttpWebResponse)forecastRequest.EndGetResponse(asyncResult);

        Stream streamResult;

        string newCredit = "";
        string newCityName = "";
        int newHeight = 0;

        string XMLresult = string.Empty;

        try
        {

            // get the stream containing the response from the async call
            string type = forecastState.AsyncResponse.ContentType; 
            streamResult = forecastState.AsyncResponse.GetResponseStream();

            XMLresult = getXMLData(streamResult);

            // load the XML
            XElement xmlData = XElement.Parse(XMLresult);

            string t = "";

        }
        catch (FormatException)
        {
            // there was some kind of error processing the response from the web
            // additional error handling would normally be added here
            return;
        }

    }
1

Take a look at the Single Responsibility Principle. The idea is you would create separate classes for each chunk of code that does only one thing. These should all be in their own CS file by the way.

In your example, I would split out the Http Request and XML parsing into their own classes. The Xml Parsing code should return a Model class which represents the data structure you are expecting back. Once you get to that point, go back and review all your code. Ask yourself do each one of these files only do a single thing? If not, refactor your more to split out more classes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.