protected T DoRequest <T>(string restPath, IDictionary <string, string> parameters, int?page = null, int?pageSize = null, bool ignoreErrorOn404 = false) where T : Response { Stopwatch sw = Stopwatch.StartNew(); var req = CreateRequest(restPath, parameters, page, pageSize); T res = GetResponse <T>(req, ignoreErrorOn404); Traces.WebService_TraceEvent(TraceEventType.Information, 1, string.Format("RequestTime: {0} ms", sw.ElapsedMilliseconds)); return(res); }
protected HttpWebRequest CreateRequest(string restPath, IDictionary <string, string> parameters = null, int?page = null, int?pageSize = null) { //const string baseUrl = "https://forumsapi.contentservices.msdn.microsoft.com/"; //const string baseUrl = "https://qa.forumsapi.contentservices.msdn.microsoft.com/"; string url = BuildUrl(BaseUrl, restPath, parameters, page, pageSize); Traces.WebService_TraceEvent(TraceEventType.Information, 1, string.Format("CreateRequest: {0}", url)); var req = (HttpWebRequest)WebRequest.Create(url); req.Accept = "application/json;api-version=1.0-preview"; req.Headers.Add("x-ms-apikey", ApiKey); if (string.IsNullOrEmpty(this.AuthenticationTicket) == false) { req.Headers.Add("x-ms-useraccesstoken", AuthenticationTicket); } return(req); }
protected T GetResponse <T>(HttpWebRequest req, bool ignoreErrorOn404 = false) where T : Response { T result = null; try { var res = (HttpWebResponse)req.GetResponse(); using (var s = new StreamReader(res.GetResponseStream())) { var json = s.ReadToEnd(); Traces.WebService_TraceEvent(TraceEventType.Verbose, 1, string.Format("JSON-Response: {1}: {0}", req.RequestUri, json)); result = Deserialize <T>(json); } } catch (WebException webException) { if (webException.Response != null) { using (var s2 = new StreamReader(webException.Response.GetResponseStream())) { var json = s2.ReadToEnd(); Traces.WebService_TraceEvent(TraceEventType.Error, 1, string.Format("WebException: JSON: {0}", json)); result = Deserialize <T>(json); var res = (HttpWebResponse)webException.Response; result.StatusCode = res.StatusCode; // If status is "404 Not found" we ignore errors, if requested if (ignoreErrorOn404 && result.StatusCode == HttpStatusCode.NotFound) { return(result); } // A "message" is also an error... if (string.IsNullOrEmpty(result.Message) == false) { result.Errors.Add(result.Message); } // If we still do not have an error, we assume the whole json-string as error... if (result.Errors.Count <= 0) { result.Errors.Add(json); } } } else { Traces.WebService_TraceEvent(TraceEventType.Error, 1, string.Format("WebException: {0}", webException)); } } if (result != null) { if (result.Errors.Count > 0) { throw new ApplicationException(string.Join(" / ", result.Errors)); } } else { throw new ApplicationException("Could not get response!"); } Traces.WebService_TraceEvent(TraceEventType.Information, 1, string.Format("GetReponse: {0}: HasMore: {1}", req.RequestUri, result.HasMore)); return(result); }