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); } }
internal static Dictionary <string, string> GetFileAsDict(Stream inputStream) { try { Dictionary <string, string> outDict = new Dictionary <string, string>(); using (StreamReader reader = new StreamReader(inputStream)) { string line; while ((line = reader.ReadLine()) != null) { string[] values = line.Split('='); if (!values[0].StartsWith("#", StringComparison.CurrentCulture)) { string val = null; if (values.Length == 2 && values[1] != null && values[1] != "") { val = values[1]; } outDict.Add(values[0], val); } } } return(outDict); } catch (ArgumentNullException e) { ZCRMLogger.LogError("Exception while initializing Zoho OAuth Client .. Essential configuration data not found"); throw new ZohoOAuthException(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); }
public APIResponse Update(ZCRMTag tag) { try { requestMethod = APIConstants.RequestMethod.PUT; urlPath = "settings/tags/" + tag.Id; requestQueryParams.Add("module", tag.ModuleApiName); JObject requestBodyObject = new JObject(); JArray dataArray = new JArray(); JObject TagJSON = new JObject(); TagJSON.Add("name", tag.Name); dataArray.Add(TagJSON); requestBodyObject.Add(APIConstants.TAGS, dataArray); requestBody = requestBodyObject; APIResponse response = APIRequest.GetInstance(this).GetAPIResponse(); JArray responseDataArray = (JArray)response.ResponseJSON[APIConstants.TAGS]; JObject responseData = (JObject)responseDataArray[0]; JObject tagDetails = (JObject)responseData[APIConstants.DETAILS]; ZCRMTag updatetag = tag; SetTagProperties(updatetag, tagDetails); response.Data = updatetag; return(response); } catch (Exception e) when(!(e is ZCRMException)) { ZCRMLogger.LogError(e); throw new ZCRMException(APIConstants.SDK_ERROR, e); } }
public APIResponse RemoveTags(ZCRMRecord record, List <string> tagNames) { if (tagNames.Count > 10) { throw new ZCRMException(APIConstants.API_MAX_RECORD_TAGS_MSG); } try { requestMethod = APIConstants.RequestMethod.POST; urlPath = "" + record.ModuleAPIName + "/" + record.EntityId + "/actions/remove_tags"; requestQueryParams.Add("tag_names", string.Join(",", JToken.FromObject(tagNames))); Console.WriteLine(JsonConvert.SerializeObject(requestQueryParams)); APIResponse response = APIRequest.GetInstance(this).GetAPIResponse(); JArray responseDataArray = (JArray)response.ResponseJSON[APIConstants.DATA]; JObject responseData = (JObject)responseDataArray[0]; JObject recordDetails = (JObject)responseData[APIConstants.DETAILS]; ZCRMRecord recordIns = record; EntityAPIHandler.GetInstance(recordIns).SetRecordProperties(recordDetails); response.Data = recordIns; return(response); } catch (Exception e) when(!(e is ZCRMException)) { ZCRMLogger.LogError(e); throw new ZCRMException(APIConstants.SDK_ERROR, e); } }
public APIResponse GetUser(long?userId) { try { requestMethod = APIConstants.RequestMethod.GET; if (userId != null) { urlPath = "users/" + userId; } else { urlPath = "users"; requestQueryParams.Add("type", "CurrentUser"); } APIResponse response = APIRequest.GetInstance(this).GetAPIResponse(); JArray usersArray = (JArray)response.ResponseJSON["users"]; response.Data = GetZCRMUser((JObject)usersArray[0]); return(response); } catch (Exception e) when(!(e is ZCRMException)) { ZCRMLogger.LogError(e); throw new ZCRMException(APIConstants.SDK_ERROR, e); } }
public BulkAPIResponse <ZCRMProfile> GetAllProfiles() { try { requestMethod = APIConstants.RequestMethod.GET; urlPath = "settings/profiles"; BulkAPIResponse <ZCRMProfile> response = APIRequest.GetInstance(this).GetBulkAPIResponse <ZCRMProfile>(); List <ZCRMProfile> allProfiles = new List <ZCRMProfile>(); JObject responseJSON = response.ResponseJSON; JArray profilesArray = (JArray)responseJSON["profiles"]; foreach (JObject profileDetails in profilesArray) { allProfiles.Add(GetZCRMProfile(profileDetails)); } response.BulkData = allProfiles; return(response); } catch (Exception e) when(!(e is ZCRMException)) { ZCRMLogger.LogError(e); throw new ZCRMException(APIConstants.SDK_ERROR, e); } }
public void DeleteOAuthTokens(string userMailId) { string connectionString = $"server={GetServerName()};username={GetMySqlUserName()};password={GetMySqlPassword()};database={GetDataBaseName()};port={GetPortNumber()};persistsecurityinfo=True;SslMode=none;"; MySqlConnection connection = null; try { connection = new MySqlConnection(connectionString); string commandStatement = "delete from oauthtokens where useridentifier = @userIdentifier"; connection.Open(); MySqlCommand command = new MySqlCommand(commandStatement, connection); command.Parameters.AddWithValue("@userIdentifier", userMailId); command.ExecuteNonQuery(); } catch (MySqlException e) { ZCRMLogger.LogError("Exception while deleting tokens from database" + e); throw new ZohoOAuthException(e); } finally { if (connection != null) { connection.Close(); } } }
public void SaveOAuthTokens(ZohoOAuthTokens zohoOAuthTokens) { string connectionString = $"server={GetServerName()};username={GetMySqlUserName()};password={GetMySqlPassword()};database={GetDataBaseName()};port={GetPortNumber()};persistsecurityinfo=True;SslMode=none;"; MySqlConnection connection = null; try { connection = new MySqlConnection(connectionString); string commandStatement = "insert into oauthtokens (useridentifier, accesstoken, refreshtoken, expirytime) values (@userIdentifier, @accessToken, @refreshToken, @expiryTime) on duplicate key update accesstoken = @accessToken, refreshtoken = @refreshToken, expirytime = @expiryTime"; connection.Open(); MySqlCommand command = new MySqlCommand(commandStatement, connection); command.Parameters.AddWithValue("@userIdentifier", zohoOAuthTokens.UserMaiilId); command.Parameters.AddWithValue("@accessToken", zohoOAuthTokens.AccessToken); command.Parameters.AddWithValue("@refreshToken", zohoOAuthTokens.RefreshToken); command.Parameters.AddWithValue("@expiryTime", zohoOAuthTokens.ExpiryTime); command.ExecuteNonQuery(); } catch (MySqlException e) { ZCRMLogger.LogError("Exception while inserting tokens to database." + e); throw new ZohoOAuthException(e); } finally { if (connection != null) { connection.Close(); } } }
public APIResponse RemoveTags(ZCRMRecord record, List <string> tagNames) { if (tagNames.Count > 10) { throw new ZCRMException(APIConstants.API_MAX_RECORD_TAGS_MSG); } try { string tagname = ""; requestMethod = APIConstants.RequestMethod.POST; foreach (string name in tagNames) { tagname += name + ","; } urlPath = "" + record.ModuleAPIName + "/" + record.EntityId + "/actions/remove_tags?tag_names=" + tagname + ""; APIResponse response = APIRequest.GetInstance(this).GetAPIResponse(); JArray responseDataArray = (JArray)response.ResponseJSON[APIConstants.DATA]; JObject responseData = (JObject)responseDataArray[0]; JObject recordDetails = (JObject)responseData[APIConstants.DETAILS]; ZCRMRecord tag = record; EntityAPIHandler.GetInstance(tag).SetRecordProperties(recordDetails); response.Data = tag; return(response); } catch (Exception e) when(!(e is ZCRMException)) { ZCRMLogger.LogError(e); throw new ZCRMException(APIConstants.SDK_ERROR, e); } }
//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); } }
public APIResponse CreateRecord() { try{ requestMethod = APIConstants.RequestMethod.POST; urlPath = record.ModuleAPIName; JObject requestBodyObject = new JObject(); JArray dataArray = new JArray(); dataArray.Add(GetZCRMRecordAsJSON()); requestBodyObject.Add(APIConstants.DATA, dataArray); requestBody = requestBodyObject; APIResponse response = APIRequest.GetInstance(this).GetAPIResponse(); JArray responseDataArray = (JArray)response.ResponseJSON[APIConstants.DATA]; JObject responseData = (JObject)responseDataArray[0]; JObject recordDetails = (JObject)responseData[APIConstants.DETAILS]; SetRecordProperties(recordDetails); response.Data = record; return(response); } catch (Exception e) when((e is ZCRMException)) { ZCRMLogger.LogError(e); throw new ZCRMException(APIConstants.SDK_ERROR, e); } }
public static Dictionary <string, string> GetFileAsDict(Stream inputStream) { try{ Dictionary <string, string> outDict = new Dictionary <string, string>(); using (StreamReader reader = new StreamReader(inputStream)) { string line; while ((line = reader.ReadLine()) != null) { string[] values = line.Split('='); if (!values[0].StartsWith("#", StringComparison.CurrentCulture)) { string val = null; if (values.Length == 2 && values[1] != null && values[1] != "") { val = values[1]; } else { continue; } outDict.Add(values[0], val); } } } return(outDict); } catch (Exception e) { ZCRMLogger.LogError(e); throw new ZCRMException(e); } }
public static Dictionary <string, string> GetConfigFileAsDict(string sectionName) { Dictionary <string, string> retDict = new Dictionary <string, string>(); try { Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); ConfigFileSection section = configuration.GetSection(sectionName) as ConfigFileSection; if (section != null) { foreach (ConfigFileElement element in section.Settings) { if (element.Value != null && element.Value != "") { retDict.Add(element.Key, element.Value); } } } } catch (Exception e) { ZCRMLogger.LogError(e); throw new ZCRMException(e); } return(retDict); }
private Stream GetFileRequestBodyStream(Stream fileContent, string fileName) { try { Stream fileDataStream = new MemoryStream(); //File Content-Disposition header excluding the boundary header; string fileHeader = string.Format("\r\nContent-Disposition: form-data; name=\"file\"; filename=\"" + fileName + "\"\r\nContent-Type: application/octet-stream\r\n\r\n"); byte[] fileHeaderBytes = Encoding.UTF8.GetBytes(fileHeader); fileDataStream.Write(fileHeaderBytes, 0, fileHeaderBytes.Length); //File content byte[] buffer = new byte[1024]; int bytesRead = 0; while ((bytesRead = fileContent.Read(buffer, 0, buffer.Length)) != 0) { fileDataStream.Write(buffer, 0, bytesRead); } //Footer byte[] fileFooterBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--"); fileDataStream.Write(fileFooterBytes, 0, fileFooterBytes.Length); fileDataStream.Position = 0; return(fileDataStream); } catch (IOException e) { ZCRMLogger.LogError(e); throw new ZCRMException(e); } }
public APIResponse UpdateNote(ZCRMNote note) { try { requestMethod = APIConstants.RequestMethod.PUT; urlPath = parentRecord.ModuleAPIName + "/" + parentRecord.EntityId + "/" + relatedList.ApiName + "/" + note.Id; JObject requestBodyObject = new JObject(); JArray dataArray = new JArray(); dataArray.Add(GetZCRMNoteAsJSON(note)); requestBodyObject.Add(APIConstants.DATA, dataArray); requestBody = requestBodyObject; APIResponse response = APIRequest.GetInstance(this).GetAPIResponse(); JArray responseDataArray = (JArray)response.ResponseJSON[APIConstants.DATA]; JObject responseData = (JObject)responseDataArray[0]; JObject responseDetails = (JObject)responseData[APIConstants.DETAILS]; note = GetZCRMNote(responseDetails, note); response.Data = note; return(response); } catch (Exception e) when(!(e is ZCRMException)) { ZCRMLogger.LogError(e); throw new ZCRMException(APIConstants.SDK_ERROR, e); } }
public APIResponse CreateBulkWriteJob() { try { if (this.writeRecord.JobId > 0) { throw new ZCRMException("JOB ID must be null for create operation."); } requestMethod = APIConstants.RequestMethod.POST; urlPath = APIConstants.WRITE; requestBody = this.GetZCRMBulkWriteAsJSON(); isBulk = true; APIResponse response = APIRequest.GetInstance(this).GetAPIResponse(); JObject responseData = response.ResponseJSON; JObject recordDetails = (JObject)responseData[APIConstants.DETAILS]; this.SetBulkWriteRecordProperties(recordDetails); response.Data = this.writeRecord; return(response); } catch (Exception e) when((e is ZCRMException)) { ZCRMLogger.LogError(e); throw new ZCRMException(APIConstants.SDK_ERROR, e); } }
public BulkAPIResponse <ZCRMAttachment> GetAttachments(int page, int perPage, string modifiedSince) { try { requestMethod = APIConstants.RequestMethod.GET; urlPath = parentRecord.ModuleAPIName + "/" + parentRecord.EntityId + "/" + relatedList.ApiName; requestQueryParams.Add(APIConstants.PAGE, page.ToString()); requestQueryParams.Add(APIConstants.PER_PAGE, perPage.ToString()); if (modifiedSince != null && modifiedSince != "") { requestHeaders.Add("If-Modified-Since", modifiedSince); } BulkAPIResponse <ZCRMAttachment> response = APIRequest.GetInstance(this).GetBulkAPIResponse <ZCRMAttachment>(); List <ZCRMAttachment> allAttachments = new List <ZCRMAttachment>(); JObject responseJSON = response.ResponseJSON; if (responseJSON.ContainsKey(APIConstants.DATA)) { JArray attachmentsArray = (JArray)responseJSON[APIConstants.DATA]; foreach (JObject attachmentDetails in attachmentsArray) { allAttachments.Add(GetZCRMAttachment(attachmentDetails)); } } response.BulkData = allAttachments; return(response); } catch (Exception e) when(!(e is ZCRMException)) { ZCRMLogger.LogError(e); throw new ZCRMException(APIConstants.SDK_ERROR, e); } }
private BulkAPIResponse <ZCRMUser> GetUsers(string type, string modifiedSince, int page, int perPage) { try { requestMethod = APIConstants.RequestMethod.GET; urlPath = "users"; requestQueryParams.Add("type", type); requestQueryParams.Add(APIConstants.PAGE, page.ToString()); requestQueryParams.Add(APIConstants.PER_PAGE, perPage.ToString()); if (modifiedSince != null && modifiedSince != "") { requestHeaders.Add("If-Modified-Since", modifiedSince); } BulkAPIResponse <ZCRMUser> response = APIRequest.GetInstance(this).GetBulkAPIResponse <ZCRMUser>(); List <ZCRMUser> allUsers = new List <ZCRMUser>(); JObject responseJSON = response.ResponseJSON; if (responseJSON.ContainsKey("users")) { JArray usersArray = (JArray)responseJSON["users"]; foreach (JObject userJSON in usersArray) { allUsers.Add(GetZCRMUser(userJSON)); } } response.BulkData = allUsers; return(response); } catch (Exception e) when(!(e is ZCRMException)) { ZCRMLogger.LogError(e); throw new ZCRMException(APIConstants.SDK_ERROR, e); } }
public APIResponse GetRecord() { try { requestMethod = APIConstants.RequestMethod.GET; urlPath = record.ModuleAPIName + "/" + record.EntityId; APIResponse response = APIRequest.GetInstance(this).GetAPIResponse(); JArray responseDataArray = (JArray)response.ResponseJSON[APIConstants.DATA]; JObject recordDetails = (JObject)responseDataArray[0]; SetRecordProperties(recordDetails); response.Data = record; return(response); } catch (Exception e) when(!(e is ZCRMException)) { ZCRMLogger.LogError(e); throw new ZCRMException(APIConstants.SDK_ERROR, e); } }
public APIResponse Merge(long?tagId, long?mergetagId) { try { requestMethod = APIConstants.RequestMethod.POST; urlPath = "settings/tags/" + mergetagId + "/actions/merge"; JObject requestBodyObject = new JObject(); JArray dataArray = new JArray(); JObject TagJSON = new JObject(); TagJSON.Add("conflict_id", tagId); dataArray.Add(TagJSON); requestBodyObject.Add(APIConstants.TAGS, dataArray); requestBody = requestBodyObject; APIResponse response = APIRequest.GetInstance(this).GetAPIResponse(); JArray responseDataArray = (JArray)response.ResponseJSON[APIConstants.TAGS]; JObject responseData = (JObject)responseDataArray[0]; JObject tagDetails = (JObject)responseData[APIConstants.DETAILS]; ZCRMTag mergetag = ZCRMTag.GetInstance(Convert.ToInt64(tagDetails["id"])); SetTagProperties(mergetag, tagDetails); response.Data = mergetag; return(response); } catch (Exception e) when(!(e is ZCRMException)) { ZCRMLogger.LogError(e); throw new ZCRMException(APIConstants.SDK_ERROR, e); } }
public APIResponse GetBulkReadJobDetails() { try { if (this.readRecord.JobId == null) { throw new ZCRMException("JOB ID must not be null for get operation."); } requestMethod = APIConstants.RequestMethod.GET; urlPath = APIConstants.READ + "/" + this.readRecord.JobId; isBulk = true; APIResponse response = APIRequest.GetInstance(this).GetAPIResponse(); JArray responseDataArray = (JArray)response.ResponseJSON[APIConstants.DATA]; JObject recordDetails = (JObject)responseDataArray[0]; this.SetBulkReadRecordProperties(recordDetails); response.Data = this.readRecord; return(response); } catch (Exception e) when(!(e is ZCRMException)) { ZCRMLogger.LogError(e); throw new ZCRMException(APIConstants.SDK_ERROR, e); } }
public BulkAPIResponse <ZCRMTag> GetTags() { try { requestMethod = APIConstants.RequestMethod.GET; urlPath = "settings/tags"; requestQueryParams.Add("module", module.ApiName); BulkAPIResponse <ZCRMTag> response = APIRequest.GetInstance(this).GetBulkAPIResponse <ZCRMTag>(); List <ZCRMTag> tags = new List <ZCRMTag>(); JObject responseJSON = response.ResponseJSON; if (responseJSON.ContainsKey(APIConstants.TAGS)) { JArray tagsArray = (JArray)responseJSON[APIConstants.TAGS]; foreach (JObject tagDetails in tagsArray) { ZCRMTag tag = ZCRMTag.GetInstance(Convert.ToInt64(tagDetails["id"])); SetTagProperties(tag, tagDetails); tags.Add(tag); } } response.BulkData = tags; return(response); } catch (Exception e) when((e is ZCRMException)) { ZCRMLogger.LogError(e); throw new ZCRMException(APIConstants.SDK_ERROR, e); } }
public APIResponse CreateBulkReadJob() { try { if (this.readRecord.JobId != null) { throw new ZCRMException("JOB ID must be null for create operation."); } requestMethod = APIConstants.RequestMethod.POST; urlPath = APIConstants.READ; requestBody = this.GetZCRMBulkQueryAsJSON(); isBulk = true; APIResponse response = APIRequest.GetInstance(this).GetAPIResponse(); JArray responseDataArray = (JArray)response.ResponseJSON[APIConstants.DATA]; JObject responseData = (JObject)responseDataArray[0]; JObject recordDetails = (JObject)responseData[APIConstants.DETAILS]; this.SetBulkReadRecordProperties(recordDetails); response.Data = this.readRecord; return(response); } catch (Exception e) when(!(e is ZCRMException)) { ZCRMLogger.LogError(e); throw new ZCRMException(APIConstants.SDK_ERROR, e); } }
public APIResponse UpdateRecord(List <string> trigger) { try { requestMethod = APIConstants.RequestMethod.PUT; urlPath = record.ModuleAPIName + "/" + record.EntityId; JObject requestBodyObject = new JObject(); JArray dataArray = new JArray(); dataArray.Add(GetZCRMRecordAsJSON()); requestBodyObject.Add(APIConstants.DATA, dataArray); if (trigger != null && trigger.Count > 0) { requestBodyObject.Add("trigger", JArray.FromObject(trigger)); } requestBody = requestBodyObject; APIResponse response = APIRequest.GetInstance(this).GetAPIResponse(); JArray responseDataArray = (JArray)response.ResponseJSON[APIConstants.DATA]; JObject responseData = (JObject)responseDataArray[0]; JObject responseDetails = (JObject)responseData[APIConstants.DETAILS]; SetRecordProperties(responseDetails); response.Data = record; return(response); } catch (Exception e) when(!(e is ZCRMException)) { ZCRMLogger.LogError(e); throw new ZCRMException(APIConstants.SDK_ERROR, e); } }
public ZohoOAuthTokens GetOAuthTokens(string userMailId) { ZohoOAuthTokens tokens; try { tokens = new ZohoOAuthTokens(); Dictionary <string, string> oauthTokens = ZohoOAuthUtil.GetFileAsDict(new FileStream(GetPersistenceHandlerFilePath(), FileMode.Open)); //Dictionary<string, string> oauthTokens = ZohoOAuthUtil.ConfigFileSectionToDict("tokens", "oauth_tokens.config"); if (!oauthTokens["useridentifier"].Equals(userMailId)) { throw new ZohoOAuthException("Given User not found in configuration"); } tokens.UserMaiilId = oauthTokens["useridentifier"]; tokens.AccessToken = oauthTokens["accesstoken"]; tokens.RefreshToken = oauthTokens["refreshtoken"]; tokens.ExpiryTime = Convert.ToInt64(oauthTokens["expirytime"]); return(tokens); } catch (FileNotFoundException e) { ZCRMLogger.LogError("Exception while fetching tokens from configuration." + e); throw new ZohoOAuthException(e); } }
//TODO: Create ZohoOAuthException class and change the throw exception class; private ZohoOAuthTokens RefreshAccessToken(string refreshToken, string userMailId) { if (refreshToken == null) { throw new ZohoOAuthException("Refresh token is not provided"); } try{ ZohoHTTPConnector conn = GetZohoConnector(ZohoOAuth.GetRefreshTokenURL()); conn.AddParam(ZohoOAuthConstants.GRANT_TYPE, ZohoOAuthConstants.REFRESH_TOKEN); conn.AddParam(ZohoOAuthConstants.REFRESH_TOKEN, refreshToken); string response = conn.Post(); JObject responseJSON = JObject.Parse(response); if (responseJSON.ContainsKey(ZohoOAuthConstants.ACCESS_TOKEN)) { ZohoOAuthTokens tokens = GetTokensFromJSON(responseJSON); tokens.RefreshToken = refreshToken; tokens.UserMaiilId = userMailId; ZohoOAuth.GetPersistenceHandlerInstance().SaveOAuthTokens(tokens); return(tokens); } throw new ZohoOAuthException("Exception while fetching access tokens from Refresh Token" + response); }catch (WebException e) { ZCRMLogger.LogError(e); throw new ZohoOAuthException(e); } }
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); } }
/// <summary> /// To get access token from grantToken. /// </summary> /// <returns>ZohoOAuthTokens class instance.</returns> /// <param name="grantToken">Grant token (String) of the oauth client</param> public ZohoOAuthTokens GenerateAccessToken(string grantToken) { if (grantToken == null || grantToken.Length == 0) { throw new ZohoOAuthException("Grant Type is not provided"); } try { var conn = GetZohoConnector(ZohoOAuth.GetTokenURL()); conn.AddParam(ZohoOAuthConstants.GRANT_TYPE, ZohoOAuthConstants.GRANT_TYPE_AUTH_CODE); conn.AddParam(ZohoOAuthConstants.CODE, grantToken); string response = conn.Post(); JObject responseJSON = JObject.Parse(response); if (responseJSON.ContainsKey(ZohoOAuthConstants.ACCESS_TOKEN)) { ZohoOAuthTokens tokens = GetTokensFromJSON(responseJSON); tokens.UserMaiilId = GetUserMailId(tokens.AccessToken); ZohoOAuth.GetPersistenceHandlerInstance().SaveOAuthTokens(tokens); return(tokens); } throw new ZohoOAuthException("Exception while fetching Access Token from grant token" + response); } catch (WebException e) { ZCRMLogger.LogError(e); throw new ZohoOAuthException(e); } }
public BulkAPIResponse <ZCRMModule> GetAllModules(string modifiedSince) { try { requestMethod = APIConstants.RequestMethod.GET; urlPath = "settings/modules"; if (!string.IsNullOrEmpty(modifiedSince)) { requestHeaders.Add("If-Modified-Since", modifiedSince); } BulkAPIResponse <ZCRMModule> response = APIRequest.GetInstance(this).GetBulkAPIResponse <ZCRMModule>(); JObject responseJSON = response.ResponseJSON; List <ZCRMModule> allModules = new List <ZCRMModule>(); if (responseJSON.ContainsKey("modules")) { JArray modulesArray = (JArray)responseJSON["modules"]; foreach (JObject moduleDetails in modulesArray) { allModules.Add(GetZCRMModule(moduleDetails)); } response.BulkData = allModules; } return(response); } catch (Exception e) when(!(e is ZCRMException)) { ZCRMLogger.LogError(e); throw new ZCRMException(APIConstants.SDK_ERROR, e); } }