public IAsyncResult BeginQuery(string query, AsyncCallback callback, object state) { string uri = ConstructQueryUri(query); HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest; req.Accept = "application/json"; ADResult fbResult = new ADResult(state); fbResult.InnerResult = req.BeginGetResponse( (result) => { if (callback != null) callback(fbResult); }, req); return fbResult; }
public IAsyncResult BeginQuery(string query, AsyncCallback callback, object state) { string uri = ConstructQueryUri(query); HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest; req.Accept = "application/json"; ADResult fbResult = new ADResult(state); fbResult.InnerResult = req.BeginGetResponse( (result) => { if (callback != null) { callback(fbResult); } }, req); return(fbResult); }
public IEnumerable <ADQueryResult> EndQuery(IAsyncResult result) { if (!result.IsCompleted) { result.AsyncWaitHandle.WaitOne(); } ADResult fbResult = result as ADResult; if (fbResult == null) { throw new ArgumentException(InvalidAsyncResult, "result"); } WebRequest req = fbResult.InnerResult.AsyncState as WebRequest; if (req == null) { throw new ArgumentException(InvalidAsyncResult, "result"); } JObject jObject = null; try { using (WebResponse resp = req.EndGetResponse(fbResult.InnerResult)) using (Stream stream = resp.GetResponseStream()) using (StreamReader reader = new StreamReader(stream)) { string json = reader.ReadToEnd(); jObject = JObject.Parse(json); } } catch (WebException ex) { // if this is a web exception (400 or 500 HTTP status codes), try // to retrieve any error messages in the json payload HttpWebResponse response = ex.Response as HttpWebResponse; if (response != null) { if (response.ContentType.ToLower().Contains("json")) { using (Stream stream = response.GetResponseStream()) using (StreamReader reader = new StreamReader(stream)) { string json = reader.ReadToEnd(); jObject = JObject.Parse(json); } } else { throw; } } else { throw; } } var errors = jObject["error"] as JObject; if (errors != null) { string message = errors.ToString(); int errorCode = 0; int.TryParse(errors.Value <string>("code"), out errorCode); switch (errorCode) { case 190: message = "Facebook authentication failed - need to renew token"; break; case 1190: message = "Directory authentication failed - need to renew token"; break; } throw new ApplicationException( String.Format( "AD Graph service errors were returned: message: {0}; code: {1}", message, errorCode), new ApplicationException(errorCode.ToString())); } var d = jObject["d"] as JObject; var data = d["results"] as JArray; if (data != null) { foreach (var queryResult in data) { var jobjResult = queryResult as JObject; yield return(new ADQueryResult(jobjResult)); } } }