Beispiel #1
0
 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);
     }
 }
Beispiel #2
0
        //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);
                new ZohoOAuthException(e);
                return("Error: " + e.Message);
                //Messagebox.Show(e.Message)
            }
        }
Beispiel #3
0
        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);
        }
Beispiel #4
0
        //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);
                new ZohoOAuthException(e);
                MessageBox.Show(e.Message, "Get", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(null);
            }
        }
        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"));


            // Stream st = new Stream;

            ConfigProperties =
                CommonUtil.GetFileAsDict(File.Open(@"D:\Github\configuration.txt", FileMode.Open));



            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));
        }
 public CommonAPIResponse(HttpWebResponse response)
 {
     try
     {
         Response = response;
         Init();
         ProcessResponse();
         SetResponseHeaders();
         ZCRMLogger.LogInfo(ToString());
     }
     catch (Exception)
     {
         ZCRMLogger.LogInfo(ToString());
     }
 }
Beispiel #7
0
        private void 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());
                try
                {
                    response = (HttpWebResponse)request.GetResponse();
                }
                catch (WebException e)
                {
                    if (e.Response == null)
                    {
                        throw;
                    }
                    response = (HttpWebResponse)e.Response;
                }
                APIStats.UpdateStats(response);
            }
            catch (WebException e)
            {
                ZCRMLogger.LogError(e);
                throw new ZCRMException(e);
            }
        }
Beispiel #8
0
 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);
     }
 }
        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);
            }
        }
Beispiel #10
0
        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);
            }
        }