private static async Task<RESTResponse> ProcessResponse(HttpWebRequest request) { RESTResponse result = new RESTResponse(); try { using (HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse) { result.StatusCode = (int)response.StatusCode; using (Stream stream = response.GetResponseStream()) { result.Content = new StreamReader(stream, System.Text.Encoding.UTF8).ReadToEnd(); } } } catch (WebException ex) { if ((ex.Status == WebExceptionStatus.ProtocolError) && (ex.Response != null)) { HttpWebResponse response = ex.Response as HttpWebResponse; result.StatusCode = (int)response.StatusCode; using (Stream stream = response.GetResponseStream()) { result.Content = new StreamReader(stream, System.Text.Encoding.UTF8).ReadToEnd(); } } } return result; }
public static Object ConvertToSDKResponse(Object toReturn, RESTResponse response) { if (response != null && response.Result != null && (response.Status == 200 || response.Status == 0)) { return(Newtonsoft.Json.JsonConvert.DeserializeObject(response.Result.ToString(), toReturn.GetType())); } return(null); }
public static Object ConvertToSDKResponse(Object toReturn, RESTResponse response, ref PaginationInfo paginationInfo) { if (response != null && response.Result != null) { paginationInfo = response.Page; return(ConvertToSDKResponse(toReturn, response)); } return(null); }
public static T ConvertToSDKResponse <T>(RESTResponse response, ref PaginationInfo paginationInfo) { if (response != null && response.Result != null) { paginationInfo = response.Page; return(ConvertToSDKResponse <T>(response)); } //paginationInfo = new PaginationInfo { hasmore = false, limit = 0, offset = 0 }; return(default(T)); }
public Contact UpdateRecordContact(Contact contact, string recordId, string token, string fields = null) { try { // Validate RequestValidator.ValidateToken(token); if (String.IsNullOrWhiteSpace(recordId)) { throw new Exception("Null Record Id provided"); } if (contact == null) { throw new Exception("Null contact provided"); } if (string.IsNullOrEmpty(contact.id)) { throw new Exception("Null contact Id provided"); } // Update StringBuilder url = new StringBuilder(apiUrl + ConfigurationReader.GetValue("UpdateRecordContact").Replace("{recordId}", recordId).Replace("{id}", contact.id)); if (this.language != null || fields != null) { url.Append("?"); } if (this.language != null) { url.Append("lang=").Append(this.language); } if (this.language != null && fields != null) { url.Append("&"); } if (fields != null) { url.Append("fields=").Append(fields); } RESTResponse response = HttpHelper.SendPutRequest(url.ToString(), contact, token, this.appId); // create response return((Contact)HttpHelper.ConvertToSDKResponse(contact, response)); } catch (WebException webException) { throw new Exception(HttpHelper.HandleWebException(webException, "Error in Update Record Contact :")); } catch (Exception exception) { throw new Exception(HttpHelper.HandleException(exception, "Error in Update Record Contact :")); } }
public ResultDataPaged <Record> SearchRecords(string token, RecordFilter filter, string fields = null, int offset = -1, int limit = -1, string sortField = null, string sortOrder = null, string expand = null) { try { // validate RequestValidator.ValidateToken(token); // create url StringBuilder url = new StringBuilder(apiUrl); url = url.Append(ConfigurationReader.GetValue("SearchRecords")).Replace("{limit}", limit.ToString()).Replace("{offset}", offset.ToString()); if (fields != null) { url.Append("&fields=").Append(fields); } if (this.language != null) { url.Append("&lang=").Append(this.language); } if (sortField != null) { url.Append("&sort=").Append(sortField); } if (sortOrder != null) { url.Append("&direction=").Append(sortOrder); } if (expand != null) { url.Append("&expand=").Append(expand); } RESTResponse response = HttpHelper.SendPostRequest(url.ToString(), filter, token, this.appId); PaginationInfo paginationInfo = null; // create response List <Record> records = new List <Record>(); records = (List <Record>)HttpHelper.ConvertToSDKResponse(records, response, ref paginationInfo); ResultDataPaged <Record> results = new ResultDataPaged <Record> { Data = records, PageInfo = paginationInfo }; return(results); } catch (WebException webException) { throw new Exception(HttpHelper.HandleWebException(webException, "Error in Search Records :")); } catch (Exception exception) { throw new Exception(HttpHelper.HandleException(exception, "Error in Search Records :")); } }
public ResultDataPaged <Contact> GetRecordContacts(string recordId, string token, string fields = null, int offset = -1, int limit = -1) { try { // Validate if (String.IsNullOrWhiteSpace(recordId)) { throw new Exception("Null Record Id provided"); } RequestValidator.ValidateToken(token); // get contacts StringBuilder url = new StringBuilder(apiUrl + ConfigurationReader.GetValue("GetRecordContacts").Replace("{recordIds}", recordId).Replace("{limit}", limit.ToString()).Replace("{offset}", offset.ToString())); if (this.language != null || fields != null) { url.Append("?"); } if (this.language != null) { url.Append("lang=").Append(this.language); } if (this.language != null && fields != null) { url.Append("&"); } if (fields != null) { url.Append("fields=").Append(fields); } RESTResponse response = HttpHelper.SendGetRequest(url.ToString(), token, this.appId); PaginationInfo paginationInfo = null; // create response List <Contact> contacts = new List <Contact>(); contacts = (List <Contact>)HttpHelper.ConvertToSDKResponse(contacts, response); ResultDataPaged <Contact> results = new ResultDataPaged <Contact> { Data = contacts, PageInfo = paginationInfo }; return(results); } catch (WebException webException) { throw new Exception(HttpHelper.HandleWebException(webException, "Error in Get Record Contacts :")); } catch (Exception exception) { throw new Exception(HttpHelper.HandleException(exception, "Error in Get Record Contacts :")); } }
public ResultDataPaged <Record> GetRecords(string token, string filter, int offset = -1, int limit = -1) { try { // validate RequestValidator.ValidateToken(token); // create url StringBuilder url = new StringBuilder(apiUrl); if (this.appType == ApplicationType.Agency) { url = url.Append(ConfigurationReader.GetValue("GetRecords")).Replace("{limit}", limit.ToString()).Replace("{offset}", offset.ToString()); } else if (this.appType == ApplicationType.Citizen) { url = url.Append(ConfigurationReader.GetValue("GetMyRecords")).Replace("{limit}", limit.ToString()).Replace("{offset}", offset.ToString()); } if (!string.IsNullOrEmpty(filter)) { url.Append("&").Append(filter); } if (this.language != null) { url.Append("&lang=").Append(this.language); } // get records RESTResponse response = HttpHelper.SendGetRequest(url.ToString(), token, this.appId); PaginationInfo paginationInfo = new PaginationInfo { hasmore = false, offset = offset, limit = limit }; // create response //List<Record> records = new List<Record>(); //records = (List<Record>)HttpHelper.ConvertToSDKResponse(records, response, ref paginationInfo); var records = HttpHelper.ConvertToSDKResponse <List <Record> >(response, ref paginationInfo); ResultDataPaged <Record> results = new ResultDataPaged <Record> { Data = records, PageInfo = paginationInfo }; return(results); } catch (WebException webException) { throw new Exception(HttpHelper.HandleWebException(webException, "Error in Get Records :")); } catch (Exception exception) { throw new Exception(HttpHelper.HandleException(exception, "Error in Get Records :")); } }
public static async Task <RESTResponse> GetAsync(string url, string accept, string sessionToken) { RESTResponse result = null; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Accept = accept; if (!string.IsNullOrEmpty(sessionToken)) { request.Headers[HttpRequestHeader.Authorization] = string.Concat("Bearer ", sessionToken); } result = await ProcessResponse(request); return(result); }
public Document GetDocument(string documentId, string token, string fields = null) { try { // Validate if (String.IsNullOrWhiteSpace(documentId)) { throw new Exception("Null Document Id provided"); } RequestValidator.ValidateToken(token); // get document StringBuilder url = new StringBuilder(apiUrl + ConfigurationReader.GetValue("GetDocument").Replace("{documentIds}", documentId)); if (this.language != null || fields != null) { url.Append("?"); } if (this.language != null) { url.Append("lang=").Append(this.language); } if (this.language != null && fields != null) { url.Append("&"); } if (fields != null) { url.Append("fields=").Append(fields); } RESTResponse response = HttpHelper.SendGetRequest(url.ToString(), token, this.appId); // create response List <Document> doc = new List <Document>(); doc = (List <Document>)HttpHelper.ConvertToSDKResponse(doc, response); if (doc != null && doc.Count > 0) { return(doc[0]); } return(null); } catch (WebException webException) { throw new Exception(HttpHelper.HandleWebException(webException, "Error in Get Record Document :")); } catch (Exception exception) { throw new Exception(HttpHelper.HandleException(exception, "Error in Get Record Document :")); } }
public List <RecordFees> GetRecordFees(string recordId, string token, string fields = null, string status = null) { try { // Validate RequestValidator.ValidateToken(token); if (String.IsNullOrEmpty(recordId)) { throw new Exception("Null Record Id provided"); } // get related record StringBuilder url = new StringBuilder(apiUrl + ConfigurationReader.GetValue("GetRecordFees").Replace("{recordId}", recordId)); if (this.language != null || fields != null || status != null) { url.Append("?"); } if (this.language != null) { url.Append("lang=").Append(this.language).Append("&"); } if (fields != null) { url.Append("fields=").Append(fields).Append("&"); } if (status != null) { url.Append("status=").Append(status).Append("&"); } url = url.Replace("&", "", url.Length - 1, 1); RESTResponse response = HttpHelper.SendGetRequest(url.ToString(), token, this.appId); // create response List <RecordFees> recordFees = new List <RecordFees>(); recordFees = (List <RecordFees>)HttpHelper.ConvertToSDKResponse(recordFees, response); return(recordFees); } catch (WebException webException) { throw new Exception(HttpHelper.HandleWebException(webException, "Error in Get Record Fees :")); } catch (Exception exception) { throw new Exception(HttpHelper.HandleException(exception, "Error in Get Record Fees :")); } }
public List <Result> CreateRecordContact(List <Contact> contacts, string recordId, string token, string fields = null) { try { // Validate RequestValidator.ValidateToken(token); contacts = RequestValidator.ValidateContactsForCreate(contacts, recordId); if (String.IsNullOrWhiteSpace(recordId)) { throw new Exception("Null Record Id provided"); } // Create StringBuilder url = new StringBuilder(apiUrl + ConfigurationReader.GetValue("CreateRecordContact").Replace("{recordId}", recordId)); if (this.language != null || fields != null) { url.Append("?"); } if (this.language != null) { url.Append("lang=").Append(this.language); } if (this.language != null && fields != null) { url.Append("&"); } if (fields != null) { url.Append("fields=").Append(fields); } RESTResponse response = HttpHelper.SendPostRequest(url.ToString(), contacts, token, this.appId); // create response List <Result> result = new List <Result>(); return((List <Result>)HttpHelper.ConvertToSDKResponse(result, response)); } catch (WebException webException) { throw new Exception(HttpHelper.HandleWebException(webException, "Error in Create Record Contact :")); } catch (Exception exception) { throw new Exception(HttpHelper.HandleException(exception, "Error in Create Record Contact :")); } }
public string Profile_GetXNML(string api_key, string method, float call_id, string sig, string v, string session_key, int uid) { AssignRequiredParameters(api_key, session_key, method); if (uid != 0) { parameters.Add("uid", uid.ToString()); } client = new RESTRequest(API_SERVER, parameters); response = client.GetResponse(); var root = XElement.Parse(response.RawResponse); CheckErrorResponse(root); return(root.Value); }
public friends_areFriends_response Friends_AreFriends(string api_key, string method, string session_key, float call_id, string sig, string v, string uids1, string uids2) { if (string.IsNullOrEmpty(uids1)) { throw new ArgumentNullException("uids1", "必须指定第一组进行比较的用户id"); } if (string.IsNullOrEmpty(uids2)) { throw new ArgumentNullException("uids2", "必须指定第二组进行比较的用户id"); } var ids1 = uids1.Split(','); var ids2 = uids2.Split(','); if (ids1.Length != ids2.Length) { throw new ArgumentException("两组进行比较的用户id数量必须相同", "uids1 or uids2"); } AssignRequiredParameters(api_key, session_key, method); parameters.Add("uids1", uids1); parameters.Add("uids2", uids2); client = new RESTRequest(API_SERVER, parameters); response = client.GetResponse(); var root = XElement.Parse(response.RawResponse); CheckErrorResponse(root); var ns = root.Name.Namespace; var faf = new friends_areFriends_response() { //list = (bool)root.Attribute("list"), list = true, friend_info = (from fel in root.Elements(ns + "friend_info") select new friend_info() { uid1 = (int)fel.Element(ns + "uid1"), uid2 = (int)fel.Element(ns + "uid2"), are_friends = fel.Element(ns + "are_friends").Value == "1", }).ToArray(), }; return(faf); }
public void DeleteRecordDocument(string documentId, string recordId, string token, string password = null, string userId = null) { try { // Validate if (String.IsNullOrWhiteSpace(recordId)) { throw new Exception("Null Record Id provided"); } if (String.IsNullOrWhiteSpace(documentId)) { throw new Exception("Null Document Id provided"); } RequestValidator.ValidateToken(token); // delete document StringBuilder url = new StringBuilder(apiUrl + ConfigurationReader.GetValue("DeleteRecordDocument").Replace("{recordId}", recordId).Replace("{documentIds}", documentId)); if (this.language != null || password != null || userId != null) { url.Append("?"); } if (this.language != null) { url.Append("lang=").Append(this.language).Append("&"); } if (userId != null) { url.Append("userId=").Append(userId).Append("&"); } if (password != null) { url.Append("password="******"&"); } url = url.Replace("&", "", url.Length - 1, 1); RESTResponse response = HttpHelper.SendDeleteRequest(url.ToString(), token, this.appId); } catch (WebException webException) { throw new Exception(HttpHelper.HandleWebException(webException, "Error in Delete Record Documents :")); } catch (Exception exception) { throw new Exception(HttpHelper.HandleException(exception, "Error in Delete Record Documents :")); } }
public void DeleteRecordContact(string contactId, string recordId, string token, string fields = null) { try { // Validate RequestValidator.ValidateToken(token); if (String.IsNullOrWhiteSpace(recordId)) { throw new Exception("Null Record Id provided"); } if (String.IsNullOrWhiteSpace(contactId)) { throw new Exception("Null Contact Id provided"); } // Update StringBuilder url = new StringBuilder(apiUrl + ConfigurationReader.GetValue("DeleteRecordContact").Replace("{recordId}", recordId).Replace("{ids}", contactId)); if (this.language != null || fields != null) { url.Append("?"); } if (this.language != null) { url.Append("lang=").Append(this.language); } if (this.language != null && fields != null) { url.Append("&"); } if (fields != null) { url.Append("fields=").Append(fields); } RESTResponse response = HttpHelper.SendDeleteRequest(url.ToString(), token, appId); } catch (WebException webException) { throw new Exception(HttpHelper.HandleWebException(webException, "Error in Delete Record Contact :")); } catch (Exception exception) { throw new Exception(HttpHelper.HandleException(exception, "Error in Delete Record Contact :")); } }
public static MyAccount GetMyAccount() { List <RESTParameter> restParameters = new List <RESTParameter>(); restParameters.Add(new RESTParameter(RESTParameterType.HEADER, "X-Token", Context.Token)); restParameters.Add(new RESTParameter(RESTParameterType.HEADER, "X-Username", Context.Token)); RESTResponse restResponse = CallRESTService.CallService(Parameters.URLs.Auth.AboutMe, restParameters, CallModeServiceREST.GET); if (restResponse.Error != null) { throw new Exception(); } Tools.CheckBodyResponse(restResponse.Body); return(JsonConvert.DeserializeObject <MyAccount>(restResponse.Body)); }
public users_getLoggedInUser_response Users_GetLoggedInUser(string api_key, string method, string session_key, float call_id, string sig, string v) { AssignRequiredParameters(api_key, session_key, method); client = new RESTRequest(API_SERVER, parameters); response = client.GetResponse(); var root = XElement.Parse(response.RawResponse); CheckErrorResponse(root); var uservalue = new users_getLoggedInUser_response() { Value = Int32.Parse(root.Value) }; return(uservalue); }
public void Notifications_Send(string api_key, string method, string session_key, float call_id, string sig, string v, string to_ids, string notification) { if (string.IsNullOrEmpty(notification)) { throw new ArgumentNullException("notification", "必须指定通知内容"); } AssignRequiredParameters(api_key, session_key, method); parameters.Add("to_ids", to_ids); parameters.Add("notification", notification); client = new RESTRequest(API_SERVER, parameters); response = client.GetResponse(); var root = XElement.Parse(response.RawResponse); CheckErrorResponse(root); //everything is ok if no error occured. }
public List <FeeSchedule> GetFeeSchedule(string token, string feeScheduleId, string fields = null, string version = null) { try { // Validate RequestValidator.ValidateToken(token); if (string.IsNullOrEmpty(feeScheduleId)) { throw new Exception("Null Fee Schedule Id provided"); } // get fee schedule StringBuilder url = new StringBuilder(apiUrl + ConfigurationReader.GetValue("GetFeeScheule").Replace("{scheduleId}", feeScheduleId)); if (this.language != null) { url.Append("&lang=").Append(this.language); } if (fields != null) { url.Append("&fields=").Append(fields); } if (version != null) { url.Append("&version=").Append(version); } RESTResponse response = HttpHelper.SendGetRequest(url.ToString(), token, appId); // create response List <FeeSchedule> feeSchedules = new List <FeeSchedule>(); feeSchedules = (List <FeeSchedule>)HttpHelper.ConvertToSDKResponse(feeSchedules, response); return(feeSchedules); } catch (WebException webException) { throw new Exception(HttpHelper.HandleWebException(webException, "Error in getting fee schedule :")); } catch (Exception exception) { throw new Exception(HttpHelper.HandleException(exception, "Error in getting fee schedule :")); } }
public List <ContactType> GetContactTypes(string token, string module) { try { // Validate RequestValidator.ValidateToken(token); // get contacts List <ContactType> contactTypes = new List <ContactType>(); StringBuilder url = new StringBuilder(apiUrl + ConfigurationReader.GetValue("GetContactTypes")); if (this.language != null || !string.IsNullOrEmpty(module)) { url.Append("?"); } if (this.language != null) { url.Append("lang=").Append(this.language); } if (this.language != null && module != null) { url.Append("&"); } if (!string.IsNullOrEmpty(module)) { url.Append("modulename=").Append(module); } RESTResponse response = HttpHelper.SendGetRequest(url.ToString(), token, this.appId); // create response contactTypes = (List <ContactType>)HttpHelper.ConvertToSDKResponse(contactTypes, response); return(contactTypes); } catch (WebException webException) { throw new Exception(HttpHelper.HandleWebException(webException, "Error in Get Contact Types :")); } catch (Exception exception) { throw new Exception(HttpHelper.HandleException(exception, "Error in Get Contact Types :")); } }
public friends_get_response Friends_Get(string api_key, string method, string session_key, float call_id, string sig, string v) { AssignRequiredParameters(api_key, session_key, method); client = new RESTRequest(API_SERVER, parameters); response = client.GetResponse(); var root = XElement.Parse(response.RawResponse); CheckErrorResponse(root); var ns = root.Name.Namespace; var fidsget = new friends_get_response() { list = (bool)root.Attribute("list"), uid = (from idel in root.Elements(ns + "uid") select Int32.Parse(idel.Value)).ToArray() }; return(fidsget); }
private static RESTResponse ReceiveRESTResponse(HttpWebRequest httpRequest) { var httpResponse = (HttpWebResponse)httpRequest.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { var resp = streamReader.ReadToEnd(); RESTResponse response = new RESTResponse(); response = (RESTResponse)Newtonsoft.Json.JsonConvert.DeserializeObject(resp, response.GetType()); if (response != null) { if (response.Status == 0) { return(response); } if (response.Status != 200) { string message = string.Format("Request Failed with Code {0} and Error {1} ", response.Code, response.Message); message += httpResponse.Headers[errorResponseHeader] + " Trace Id : " + httpResponse.Headers[traceIdHeader]; throw new Exception(message); } else if (response.Status == 200 && response.Result != null) { string resultString = response.Result.ToString(); if (resultString.Contains("isSuccess")) { List <Result> result = new List <Result>(); result = (List <Result>)Newtonsoft.Json.JsonConvert.DeserializeObject(response.Result.ToString(), result.GetType()); int count = (from r in result where r.isSuccess == false select r).Count(); if (count > 0) { string message = resultString + " " + httpResponse.Headers[errorResponseHeader] + " Trace Id : " + httpResponse.Headers[traceIdHeader]; throw new Exception("Request Failed " + message); } } } } return(response); } }
public UserProfile GetUserProfile(string token, string fields = null) { try { // Validate RequestValidator.ValidateToken(token); // get user profile StringBuilder url = new StringBuilder(apiUrl + ConfigurationReader.GetValue("GetUserProfile")); if (this.language != null || fields != null) { url.Append("?"); } if (this.language != null) { url.Append("lang=").Append(this.language); } if (this.language != null && fields != null) { url.Append("&"); } if (fields != null) { url.Append("fields=").Append(fields); } RESTResponse response = HttpHelper.SendGetRequest(url.ToString(), token, this.appId); // create response UserProfile userProfile = new UserProfile(); return((UserProfile)HttpHelper.ConvertToSDKResponse(userProfile, response)); } catch (WebException webException) { throw new Exception(HttpHelper.HandleWebException(webException, "Error in Get User Profile :")); } catch (Exception exception) { throw new Exception(HttpHelper.HandleException(exception, "Error in Get User Profile :")); } }
public static AuthenticationAnswer Authenticate(string email, string password) { List <RESTParameter> restParameters = new List <RESTParameter>(); var body = new { email = email, password = password }; restParameters.Add(new RESTParameter(RESTParameterType.POST, JsonConvert.SerializeObject(body))); RESTResponse restResponse = CallRESTService.CallService(Parameters.URLs.Auth.Signin, restParameters, CallModeServiceREST.POST); AuthenticationAnswer authenticationAnswer = new AuthenticationAnswer(); if (restResponse.Error != null) { authenticationAnswer.Success = false; switch (restResponse.HTTPStatuCode) { case 401: authenticationAnswer.ErrorType = AuthenticationErrorType.Unauthorized; break; default: authenticationAnswer.ErrorType = AuthenticationErrorType.Unknow; break; } } else { Tools.CheckBodyResponse(restResponse.Body); authenticationAnswer.Token = ((JObject)JsonConvert.DeserializeObject(restResponse.Body)).SelectToken("token").ToObject <string>(); Context.Token = authenticationAnswer.Token; authenticationAnswer.Success = true; } return(authenticationAnswer); }
public Record GetRecord(string recordId, string token) { try { // Validate RequestValidator.ValidateToken(token); if (String.IsNullOrWhiteSpace(recordId)) { throw new Exception("Null Record Id provided"); } // get record summary string url = apiUrl + ConfigurationReader.GetValue("GetRecord").Replace("{recordIds}", recordId); if (this.language != null) { url += "?lang=" + this.language; } RESTResponse response = HttpHelper.SendGetRequest(url, token, this.appId); // create response List <Record> records = new List <Record>(); records = (List <Record>)HttpHelper.ConvertToSDKResponse(records, response); if (records != null && records.Count > 0) { return(records[0]); } return(null); } catch (WebException webException) { throw new Exception(HttpHelper.HandleWebException(webException, "Error in Get Record :")); } catch (Exception exception) { throw new Exception(HttpHelper.HandleException(exception, "Error in Get Record :")); } }
public List <Dictionary <string, string> > UpdateRecordCustomFields(string recordId, List <Dictionary <string, string> > customFieldList, string token) // Doesn't work bug raised { try { // Validate if (String.IsNullOrWhiteSpace(recordId)) { throw new Exception("Null Record Id provided"); } if (customFieldList == null || customFieldList.Count == 0) { throw new Exception("Null Custom Field List provided"); } RequestValidator.ValidateToken(token); // update Custom Fields string url = apiUrl + ConfigurationReader.GetValue("UpdateRecordCustomFields").Replace("{recordId}", recordId); if (this.language != null) { url += "?lang=" + this.language; } RESTResponse response = HttpHelper.SendPutRequest(url, customFieldList, token, this.appId); // create response customFieldList = (List <Dictionary <string, string> >)HttpHelper.ConvertToSDKResponse(customFieldList, response); return(customFieldList); } catch (WebException webException) { throw new Exception(HttpHelper.HandleWebException(webException, "Error in Update Record Custom Fields :")); } catch (Exception exception) { throw new Exception(HttpHelper.HandleException(exception, "Error in Update Record Custom Fields :")); } }
public async Task <T> SendRequest <T>(string resource, Method method = Method.GET, string body = "", bool authNeeded = true) { if (authNeeded && (AuthenticationData == null || AuthenticationData.Email == null || AuthenticationData.AuthenticationToken == null || AuthenticationData.Email.Length == 0 || AuthenticationData.AuthenticationToken.Length == 0)) { throw new NotAuthorizedException(); } var req = new RESTRequest() { Url = ApiUrl + "/" + resource, Method = method, }; req.Headers.Add("X-User-Language", "en-US"); if (authNeeded) { req.Headers.Add("X-User-Email", AuthenticationData.Email); req.Headers.Add("X-User-Token", AuthenticationData.AuthenticationToken); } if (body.Length > 0) { req.Body = new StringContent(body, Encoding.UTF8, "application/json"); } using (RESTResponse response = (RESTResponse)await restClient.PerformRequestAsync(req)) { //IF requested type is byte array do not check content and return binary data if (typeof(T) == typeof(byte[])) { if (response.GetStatusCode() != HttpStatusCode.OK) { throw ExceptionHelper.DetermineByHttpCode(response.GetStatusCode()); } return((T)(object)await response.ReadResponseAsByteArrayAsync()); } string responseBody = await response.ReadResponseAsStringAsync(); JToken responseContent; try { responseContent = JToken.Parse(responseBody); } catch (JsonException) { if (response.GetStatusCode() != HttpStatusCode.OK) { throw ExceptionHelper.DetermineByHttpCode(response.GetStatusCode()); } throw ExceptionHelper.DetermineByHttpCode(response.GetStatusCode(), "Server response doesn't have valid JSON"); } if (responseContent.Type == JTokenType.Object && responseContent["error"] != null) { throw ExceptionHelper.DetermineByHttpCode(response.GetStatusCode(), responseContent["error"].ToString()); } if (response.GetStatusCode() != HttpStatusCode.OK) { throw ExceptionHelper.DetermineByHttpCode(response.GetStatusCode()); } if (typeof(T) == typeof(string) || typeof(T) == typeof(String)) { return((T)(object)responseBody); } else { try { return(JsonConvert.DeserializeObject <T>(responseBody, jsonSettings)); } catch (JsonException e) { throw new ServerErrorException(response.GetStatusCode(), e.Message, e); } } } }
public users_getInfo_response Users_GetInfo(string api_key, string method, string session_key, float call_id, string sig, string v, string uids, string fields) { if (string.IsNullOrEmpty(uids)) { throw new ArgumentNullException("uids", "必须指定用户id"); } AssignRequiredParameters(api_key, session_key, method); parameters.Add("uids", uids); parameters.Add("fields", fields); //client = new RESTRequest(API_SERVER, parameters); client = new RESTRequest(API_SERVER, HttpMethod.POST, parameters); response = client.GetResponse(); var root = XElement.Parse(response.RawResponse); CheckErrorResponse(root); var ns = root.Name.Namespace; var userElements = from node in root.Elements(ns + "user") select node; var userEntities = new List <user>(); foreach (var usernode in userElements) { user u = new user(); u.uid = (int)usernode.Element(ns + "uid"); if (fields.Contains("name")) { u.name = (string)usernode.Element(ns + "name"); } if (fields.Contains("sex")) { u.sex = (int)usernode.Element(ns + "sex"); u.sexSpecified = true; } else { u.sex = -1; u.sexSpecified = false; } if (fields.Contains("birthday")) { u.birthday = (string)usernode.Element(ns + "birthday"); } if (fields.Contains("headurl")) { u.headurl = (string)usernode.Element(ns + "headurl"); } if (fields.Contains("mainurl")) { u.mainurl = (string)usernode.Element(ns + "mainurl"); } if (fields.Contains("tinyurl")) { u.tinyurl = (string)usernode.Element(ns + "tinyurl"); } if (fields.Contains("hometown_location") && usernode.Element(ns + "hometown_location") != null) { u.hometown_location = new hometown_location() { country = (string)usernode.Element(ns + "hometown_location").Element(ns + "country"), province = (string)usernode.Element(ns + "hometown_location").Element(ns + "province"), city = (string)usernode.Element(ns + "hometown_location").Element(ns + "city") }; } if (fields.Contains("work_history") && usernode.Element(ns + "work_history") != null) { u.work_history = new work_history() { list = (bool)usernode.Element(ns + "work_history").Attribute("list"), listSpecified = true, work_info = (from wel in usernode.Element(ns + "work_history").Elements(ns + "work_info") select new work_info() { company_name = (string)wel.Element(ns + "company_name"), description = (string)wel.Element(ns + "description"), start_date = (string)wel.Element(ns + "start_date"), end_date = (string)wel.Element(ns + "end_date"), }).ToArray(), }; } if (fields.Contains("university_history") && usernode.Element(ns + "university_history") != null) { u.university_history = new university_history() { list = (bool)usernode.Element(ns + "university_history").Attribute("list"), listSpecified = true, university_info = (from uel in usernode.Element(ns + "university_history").Elements(ns + "university_info") select new university_info() { name = (string)uel.Element(ns + "name"), year = (int)uel.Element(ns + "year"), department = (string)uel.Element(ns + "department"), yearSpecified = uel.Element(ns + "year") != null, }).ToArray(), }; } if (fields.Contains("hs_history") && usernode.Element(ns + "hs_history") != null) { u.hs_history = new hs_history() { list = (bool)usernode.Element(ns + "hs_history").Attribute("list"), listSpecified = true, hs_info = (from hel in usernode.Element(ns + "hs_history").Elements(ns + "hs_info") select new hs_info() { name = (string)hel.Element(ns + "name"), grad_year = (int)hel.Element(ns + "grad_year"), grad_yearSpecified = hel.Element(ns + "grad_year") != null, }).ToArray(), }; } userEntities.Add(u); } var usersinfo = new users_getInfo_response() { list = (bool)root.Attribute("list"), user = userEntities.ToArray() }; return(usersinfo); }