I have the following bits of code, scattered throughout my application. I’d really like to boilerplate it, and place it in either a static class, or some utility set of classes so I don’t have all this duplication.
However, the small bits of the function are unique in such a way that I don’t know how to refactor it.
private void callResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response;
// End the get response operation
response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamReader = new StreamReader(streamResponse);
string responseData = streamReader.ReadToEnd();
streamResponse.Close();
streamReader.Close();
response.Close();
ExpectedResponseType regResponse = Newtonsoft.Json.JsonConvert.DeserializeObject<ExpectedResponseType>(responseData);
if (regResponse.ok == "0")
{
//error - handle the msg
//whether the user not loggin or not exist
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(CustomErrorMessage);
});
}
else
{
//check the variables unique to the ExpectedResponseType and do Stuff here;
}
}
catch (WebException e)
{
// Error treatment
// ...
Debug.WriteLine("error " + e);
}
I am most curious how to pass in “ExpectedResponseType”, such that it might be any Class, (i.e., is there a way to pass in T?) or possibly how to fire events that can then be executed by the UI thread and handled appropriately.
Thanks.
edit: “ExpectedResponseType” or “T” is a large collection of classes for each type of server call. For example I have LoginResponse, RegisterResponse, GetFilesResponse, UpdateResponse, DownloadResponse, etc..
EDIT: I have removed earlier example as it would not work with the delegate signature.
In order to handle the checking of the parameters specific to the type T you will need to add a little abstraction, the cleanest way is probably to wrap your code in a templated class that allows the registration of a delegate for handling the checking, I’m sure this is a specific pattern but cannot recall which one:
In response to you question about handling a large variety of T, perhaps the cleaned up code above clears it up, if not then this is what generics are for – provided you know what you are expecting in each case. So for each type you were expecting you would call it something along the lines of: