private void AuthenticateRequest() { try { if (ZCRMConfigUtil.HandleAuthentication) { string accessToken = (string)(Type.GetType(ZCRMConfigUtil.GetAuthenticationClass()).GetMethod("GetAccessToken", BindingFlags.Static | BindingFlags.Public).Invoke(null, null)); if (accessToken == null) { ZCRMLogger.LogError("Access token is not set"); throw new ZCRMException(APIConstants.AUTHENTICATION_FAILURE, "Access token is not set"); } SetHeader("Authorization", APIConstants.authHeaderPrefix + accessToken); ZCRMLogger.LogInfo("Token fetched successfully.."); } } catch (TargetInvocationException e) { ZCRMLogger.LogError(e.GetBaseException()); if (e.GetBaseException() is ZCRMException) { throw (ZCRMException)(e.GetBaseException()); } throw new ZCRMException(e.GetBaseException()); } catch (Exception e) when(e is TargetException || e is MethodAccessException) { ZCRMLogger.LogError(e); throw new ZCRMException(e); } }
public string GetAccessToken(string userMailId) { IZohoPersistenceHandler persistenceHandler = ZohoOAuth.GetPersistenceHandlerInstance(); ZohoOAuthTokens tokens; try { ZCRMLogger.LogInfo("Retreiving access token.."); tokens = persistenceHandler.GetOAuthTokens(userMailId); } catch (Exception e) when(!(e is ZohoOAuthException)) { ZCRMLogger.LogError("Exception while fetching tokens from persistence" + e); throw new ZohoOAuthException(e); } try { return(tokens.AccessToken); } catch (ZohoOAuthException) { ZCRMLogger.LogInfo("Access Token expired, Refreshing Access token"); tokens = RefreshAccessToken(tokens.RefreshToken, userMailId); } return(tokens.AccessToken); }
//TODO: Throw Exceptions public string Get() { try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); request.UserAgent = "Mozilla/5.0"; if (RequestHeaders != null && RequestHeaders.Count != 0) { foreach (KeyValuePair <string, string> header in RequestHeaders) { request.Headers[header.Key] = header.Value; } } ZCRMLogger.LogInfo("GET - " + APIConstants.URL + " = " + url + ", " + APIConstants.HEADERS + " = " + CommonUtil.DictToString(RequestHeaders) + ", " + APIConstants.PARAMS + " = " + CommonUtil.DictToString(requestParams)); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); string responseString = ""; using (StreamReader reader = new StreamReader(response.GetResponseStream())) { responseString = reader.ReadToEnd(); } ZCRMLogger.LogInfo(APIConstants.STATUS_CODE + " = " + response.StatusCode + ", " + APIConstants.RESPONSE_JSON + " = " + responseString); return(responseString); }catch (WebException e) { ZCRMLogger.LogError(e); throw new ZohoOAuthException(e); } }
//TODO: Handle Exceptions <IMPORTANT = Handle UploadFile method in APIRequest>; public APIResponse UploadAttachment(string filePath) { //TODO: Validate File <IMPORTANT> try { requestMethod = APIConstants.RequestMethod.POST; urlPath = $"{parentRecord.ModuleAPIName}/{parentRecord.EntityId}/{relatedList.ApiName}"; ZCRMLogger.LogInfo("urlPath : " + urlPath); APIResponse response = APIRequest.GetInstance(this).UploadFile(filePath); JArray responseDataArray = (JArray)response.ResponseJSON.GetValue("data"); JObject responseData = (JObject)responseDataArray[0]; JObject responseDetails = (JObject)responseData.GetValue("details"); response.Data = GetZCRMAttachment(responseDetails); return(response); } catch (Exception e) { //TODO: Log the exception; Console.WriteLine("Exception in UploadAttachment"); Console.WriteLine(e); throw new ZCRMException("ZCRM_INTERNAL_ERROR"); } }
public static void Initialize(string domainSuffix, Dictionary <string, string> configData) { try { if (configData == null) { AddConfigurationData("oauth_configuration"); } else { AddConfigurationData(configData); } List <string> MandatoryKeys = new List <string>() { ZohoOAuthConstants.CLIENT_ID, ZohoOAuthConstants.CLIENT_SECRET, ZohoOAuthConstants.PERSISTENCE_HANDLER_CLASS, ZohoOAuthConstants.REDIRECT_URL }; foreach (string key in MandatoryKeys) { if (ConfigProperties.ContainsKey(key)) { if (string.IsNullOrEmpty(ConfigProperties[key]) || string.IsNullOrWhiteSpace(ConfigProperties[key])) { throw new ZCRMException(key + " value is not set"); } } else { throw new ZCRMException(key + " is Mandatory"); } } //set iamURL from ConfigProperties if (ConfigProperties.ContainsKey(ZohoOAuthConstants.IAM_URL)) { if (string.IsNullOrEmpty(ConfigProperties[ZohoOAuthConstants.IAM_URL]) || string.IsNullOrWhiteSpace(ConfigProperties[ZohoOAuthConstants.IAM_URL])) { SetIAMUrl(domainSuffix); } } else { SetIAMUrl(domainSuffix); } ZohoOAuthParams oAuthParams = new ZohoOAuthParams() { ClientId = GetConfigValue(ZohoOAuthConstants.CLIENT_ID), ClientSecret = GetConfigValue(ZohoOAuthConstants.CLIENT_SECRET), AccessType = GetConfigValue(ZohoOAuthConstants.ACCESS_TYPE) ?? "offline", RedirectURL = GetConfigValue(ZohoOAuthConstants.REDIRECT_URL) }; ZohoOAuthClient.GetInstance(oAuthParams); ZCRMLogger.LogInfo("Zoho OAuth Client Library configuration properties: " + CommonUtil.DictToString(ConfigProperties)); } catch (KeyNotFoundException e) { ZCRMLogger.LogError("Exception while initializing Zoho OAuth Client .. Essential configuration data not found"); throw new ZohoOAuthException(e); } }
public CommonAPIResponse(int statusCode, string responseString, WebHeaderCollection headers) { SetResponseHeaders(headers); Init(statusCode, responseString); ProcessResponse(); ZCRMLogger.LogInfo(ToString()); }
public CommonAPIResponse(HttpWebResponse response) { Response = response; Init(); ProcessResponse(); SetResponseHeaders(); ZCRMLogger.LogInfo(ToString()); }
//TODO: Change the access-modifier to internal; public string Post() { try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); string postData = null; if (requestParams.Count != 0) { foreach (KeyValuePair <string, string> param in requestParams) { if (postData == null) { postData = param.Key + "=" + param.Value; } else { postData += "&" + param.Key + "=" + param.Value; } } } request.UserAgent = "Mozilla/5.0"; var data = Encoding.UTF8.GetBytes(postData); if (RequestHeaders.Count != 0) { foreach (KeyValuePair <string, string> header in RequestHeaders) { if (header.Value != null && string.IsNullOrEmpty(header.Value)) { request.Headers[header.Key] = header.Value; } } } request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = data.Length; request.Method = "POST"; using (var dataStream = request.GetRequestStream()) { dataStream.Write(data, 0, data.Length); } ZCRMLogger.LogInfo("POST - " + APIConstants.URL + " = " + url + ", " + APIConstants.HEADERS + " = " + CommonUtil.DictToString(RequestHeaders) + ", " + APIConstants.PARAMS + " = " + CommonUtil.DictToString(requestParams)); var response = (HttpWebResponse)request.GetResponse(); string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); ZCRMLogger.LogInfo(APIConstants.STATUS_CODE + " = " + response.StatusCode + ", " + APIConstants.RESPONSE_JSON + " = " + responseString); return(responseString); }catch (WebException e) { ZCRMLogger.LogError(e); throw new ZohoOAuthException(e); } }
public string GetFileName() { ZCRMLogger.LogInfo("Content-Type = " + Response.Headers["Content-Type"]); string fileMetaData = Response.Headers["Content-Disposition"]; string fileName = fileMetaData.Split(new string[] { "=" }, StringSplitOptions.None)[1]; if (fileName.Contains("''")) { fileName = fileName.Split(new string[] { "''" }, StringSplitOptions.None)[1]; } return(fileName); }
public CommonAPIResponse(HttpWebResponse response) { try { Response = response; Init(); ProcessResponse(); SetResponseHeaders(); ZCRMLogger.LogInfo(ToString()); } catch (Exception) { ZCRMLogger.LogInfo(ToString()); } }
public static void Initialize(bool initOAuth, Stream configStream, Dictionary <string, string> configData) { Assembly assembly = Assembly.GetAssembly(typeof(ZCRMConfigUtil)); ConfigProperties = CommonUtil.GetFileAsDict(assembly.GetManifestResourceStream(assembly.GetName().Name + ".Resources.configuration.txt")); if (configStream == null && configData == null) { Dictionary <string, string> keyValuePairs = CommonUtil.GetConfigFileAsDict("zcrm_configuration"); foreach (KeyValuePair <string, string> keyValues in keyValuePairs) { ConfigProperties[keyValues.Key] = keyValues.Value; } } if (configStream != null) { configData = CommonUtil.GetFileAsDict(configStream); configStream = null; } if (configData != null) { AddConfigurationData(configData); } ZCRMLogger.Init(); if (initOAuth) { HandleAuthentication = true; try { ZohoOAuth.Initialize(ConfigProperties.ContainsKey(APIConstants.DOMAIN_SUFFIX) ? (string)ConfigProperties[APIConstants.DOMAIN_SUFFIX] : null, configData); if (ConfigProperties.ContainsKey(APIConstants.DOMAIN_SUFFIX)) { SetAPIBaseUrl(ConfigProperties[APIConstants.DOMAIN_SUFFIX]); } } catch (Exception e) { throw new ZCRMException(e); } } ZCRMLogger.LogInfo("C# Client Library Configuration Properties : " + CommonUtil.DictToString(ConfigProperties)); }
private HttpWebResponse GetResponseFromServer() { try { PopulateRequestHeaders(ZCRMRestClient.StaticHeaders); if (ZCRMRestClient.DYNAMIC_HEADERS.IsValueCreated) { PopulateRequestHeaders(ZCRMRestClient.GetDynamicHeaders()); } else { AuthenticateRequest(); } SetQueryParams(); HttpWebRequest request = GetHttpWebRequestClient(); SetHeaders(ref request); SetRequestMethod(request); ZCRMLogger.LogInfo(ToString()); HttpWebResponse response; try { response = (HttpWebResponse)request.GetResponse(); } catch (WebException e) { if (e.Response == null) { throw; } response = (HttpWebResponse)e.Response; } APIStats.UpdateStats(response); return(response); } catch (WebException e) { ZCRMLogger.LogError(e); throw new ZCRMException(e); } }
public static IZohoPersistenceHandler GetPersistenceHandlerInstance() { try { string classAssemblyName; try { classAssemblyName = GetConfigValue(ZohoOAuthConstants.PERSISTENCE_HANDLER_CLASS); } catch (KeyNotFoundException) { ZCRMLogger.LogInfo("Persistence Handler not specified. Hence using the default implementation."); classAssemblyName = ZohoOAuthConstants.DEFAULT_PERSISTENCE_HANDLER; } return((IZohoPersistenceHandler)Activator.CreateInstance(Type.GetType(classAssemblyName))); } catch (Exception e) when(e is ArgumentNullException) { ZCRMLogger.LogError(e); throw new ZohoOAuthException(e); } }
//TODO: Throw ZohoOAuthException ; public string GetAccessToken(string userMailId) { IZohoPersistenceHandler persistenceHandler = ZohoOAuth.GetPersistenceHandlerInstance(); ZohoOAuthTokens tokens; try{ Console.WriteLine("Getting tokens"); tokens = persistenceHandler.GetOAuthTokens(userMailId); }catch (Exception e) { Console.WriteLine("Exception while retrieving tokens from persistence " + e.Message); throw; } try { return(tokens.AccessToken); }catch (Exception e) { Console.WriteLine(e.Message); ZCRMLogger.LogInfo("Access Token expired, Refreshing Access token"); tokens = RefreshAccessToken(tokens.RefreshToken, userMailId); } return(tokens.AccessToken); }
public APIResponse UploadAttachment(string filePath) { CommonUtil.ValidateFile(filePath); try { requestMethod = APIConstants.RequestMethod.POST; urlPath = parentRecord.ModuleAPIName + "/" + parentRecord.EntityId + "/" + relatedList.ApiName; ZCRMLogger.LogInfo("urlPath : " + urlPath); APIResponse response = APIRequest.GetInstance(this).UploadFile(filePath); JArray responseDataArray = (JArray)response.ResponseJSON[APIConstants.DATA]; JObject responseData = (JObject)responseDataArray[0]; JObject responseDetails = (JObject)responseData[APIConstants.DETAILS]; response.Data = GetZCRMAttachment(responseDetails); return(response); } catch (Exception e) when(!(e is ZCRMException)) { ZCRMLogger.LogError(e); throw new ZCRMException(APIConstants.SDK_ERROR, e); } }
protected override void ProcessDataResponse() { JObject msgJSON = ResponseJSON; if (msgJSON.ContainsKey(APIConstants.DATA)) { JArray recordsArray = (JArray)ResponseJSON.GetValue(APIConstants.DATA); msgJSON = (JObject)recordsArray[0]; } if (msgJSON.ContainsKey(APIConstants.TAGS)) { JArray tagsArray = (JArray)ResponseJSON.GetValue(APIConstants.TAGS); msgJSON = (JObject)tagsArray[0]; } if (msgJSON.ContainsKey(APIConstants.USERS)) { JArray usersArray = (JArray)ResponseJSON.GetValue(APIConstants.USERS); msgJSON = (JObject)usersArray[0]; } if (msgJSON.ContainsKey(APIConstants.MESSAGE)) { Message = msgJSON.GetValue(APIConstants.MESSAGE).ToString(); } if (msgJSON.ContainsKey(APIConstants.STATUS)) { Status = msgJSON.GetValue(APIConstants.STATUS).ToString(); if (Status.Equals(APIConstants.CODE_ERROR)) { if (msgJSON.ContainsKey(APIConstants.DETAILS)) { //TODO: Inspect the working of this part; throw new ZCRMException(true, (int)HttpStatusCode.Value, msgJSON.GetValue(APIConstants.CODE).ToString(), Message, msgJSON.GetValue(APIConstants.DETAILS) as JObject); } throw new ZCRMException(true, (int)HttpStatusCode.Value, msgJSON.GetValue(APIConstants.CODE).ToString(), Message); } } //NOTE: For the user photo download method. else if (msgJSON.ContainsKey("status_code")) { Status = msgJSON["status_code"].ToString(); if (msgJSON.ContainsKey("errors")) { JArray errorDetails = (JArray)msgJSON["errors"]; throw new ZCRMException(true, (int)HttpStatusCode.Value, HttpStatusCode.Value.ToString(), "Status_code :" + (string)msgJSON["status_code"] + ", Error details: " + errorDetails[0]["code"] + ", Resource :" + errorDetails[0]["resource"]); } throw new ZCRMException(true, (int)HttpStatusCode.Value, HttpStatusCode.Value.ToString(), "Status_code :" + (string)msgJSON["status_code"] + msgJSON.ToString()); } //NOTE : while uploading the file if the org id is wrong the below else-if block will handle it. else if (msgJSON.ContainsKey("x-error")) { ZCRMLogger.LogInfo(ToString()); JToken infoMessageToken = msgJSON.GetValue("info"); string infoMessage = null; if (infoMessageToken != null && infoMessageToken.Type != JTokenType.Null) { infoMessage = infoMessageToken.ToString(); } throw new ZCRMException(true, (int)HttpStatusCode.Value, HttpStatusCode.Value.ToString(), infoMessage, msgJSON); } }