コード例 #1
0
        public void Authenticate(APIHTTPConnector urlConnection)
        {
            lock (this)
            {
                try
                {
                    Initializer initializer = Initializer.GetInitializer();

                    TokenStore store = initializer.Store;

                    UserSignature user = initializer.User;

                    OAuthToken oauthToken = (OAuthToken)store.GetToken(initializer.User, this);

                    string token = null;

                    if (oauthToken == null)//first time
                    {
                        token = this.refreshToken != null?this.RefreshAccessToken(user, store).AccessToken : this.GenerateAccessToken(user, store).AccessToken;
                    }
                    else if (GetExpiryLapseInMillis(oauthToken.ExpiresIn) < 5L)//access token will expire in next 5 seconds or less
                    {
                        SDKLogger.LogInfo(Constants.REFRESH_TOKEN_MESSAGE);

                        token = oauthToken.RefreshAccessToken(user, store).AccessToken;
                    }
                    else
                    {
                        token = oauthToken.AccessToken;
                    }

                    urlConnection.AddHeader(Constants.AUTHORIZATION, Constants.OAUTH_HEADER_PREFIX + token);
                }
                catch (System.Exception ex) when(!(ex is SDKException))
                {
                    throw new SDKException(ex);
                }
            }
        }
コード例 #2
0
        /// <summary>
        /// The method to switch the different user in SDK environment.
        /// </summary>
        /// <param name="user">A User class instance represents the CRM user.</param>
        /// <param name="environment">A Environment class instance containing the CRM API base URL and Accounts URL.</param>
        /// <param name="token">A Token class instance containing the OAuth client application information.</param>
        /// <param name="sdkConfig">A SDKConfig class instance containing the configuration.</param>
        /// <param name="proxy">An RequestProxy class instance containing the proxy properties of the user.
        private static void SwitchUser(UserSignature user, Dc.DataCenter.Environment environment, Token token, SDKConfig sdkConfig, RequestProxy proxy)
        {
            Initializer initializer = new Initializer();

            initializer.user = user;

            initializer.environment = environment;

            initializer.token = token;

            initializer.store = Initializer.initializer.store;

            initializer.sdkConfig = sdkConfig;

            initializer.requestProxy = proxy;

            initializer.resourcePath = Initializer.initializer.resourcePath;

            LOCAL.Value = initializer;

            SDKLogger.LogInfo(Constants.INITIALIZATION_SWITCHED + initializer.ToString());
        }
コード例 #3
0
        ///<summary>
        /// The method to delete fields JSON File of the current user.
        ///</summary>
        public static void DeleteFieldsFile()
        {
            lock (LOCK)
            {
                try
                {
                    string recordFieldDetailsPath = GetDirectory() + Path.DirectorySeparatorChar + GetEncodedFileName();

                    if (System.IO.File.Exists(recordFieldDetailsPath))
                    {
                        System.IO.File.Delete(recordFieldDetailsPath);
                    }
                }
                catch (Exception e)
                {
                    SDKException exception = new SDKException(e);

                    SDKLogger.LogError(Constants.DELETE_FIELD_FILE_ERROR + JsonConvert.SerializeObject(exception));

                    throw exception;
                }
            }
        }
コード例 #4
0
        /**
         * The method to force-refresh fields of all the available modules.
         * @throws SDKException
         */
        public static void RefreshAllModules()
        {
            lock (LOCK)
            {
                try
                {
                    Utility.RefreshModules();
                }
                catch (SDKException e)
                {
                    SDKLogger.LogError(Constants.REFRESH_ALL_MODULE_FIELDS_ERROR + JsonConvert.SerializeObject(e));

                    throw e;
                }
                catch (Exception e)
                {
                    SDKException exception = new SDKException(e);

                    SDKLogger.LogError(Constants.REFRESH_ALL_MODULE_FIELDS_ERROR + JsonConvert.SerializeObject(exception));

                    throw exception;
                }
            }
        }
コード例 #5
0
        ///<summary>
        ///This method to get module field data from Zoho CRM.
        ///</summary>
        ///<param name="moduleAPIName">A String containing the CRM module API name.</param>
        ///<returns>A Object representing the Zoho CRM module field details.</returns>
        public static object GetFieldsDetails(string moduleAPIName)
        {
            JObject fieldsDetails = new JObject();

            FieldsOperations fieldOperation = new FieldsOperations(moduleAPIName);

            ParameterMap parameterinstance = new ParameterMap();

            APIResponse <Com.Zoho.Crm.API.Fields.ResponseHandler> response = fieldOperation.GetFields(parameterinstance);

            if (response != null)
            {
                if (response.StatusCode == Constants.NO_CONTENT_STATUS_CODE)
                {
                    return(fieldsDetails);
                }

                //Check if expected response is received
                if (response.IsExpected)
                {
                    Com.Zoho.Crm.API.Fields.ResponseHandler responseHandler = response.Object;

                    if (responseHandler is Com.Zoho.Crm.API.Fields.ResponseWrapper)
                    {
                        Com.Zoho.Crm.API.Fields.ResponseWrapper responseWrapper = (Com.Zoho.Crm.API.Fields.ResponseWrapper)responseHandler;

                        List <Field> fields = (List <Field>)responseWrapper.Fields;

                        foreach (Field field in fields)
                        {
                            string keyName = field.APIName;

                            if (Constants.KEYS_TO_SKIP.Contains(keyName))
                            {
                                continue;
                            }

                            JObject fieldDetail = new JObject();

                            SetDataType(fieldDetail, field, moduleAPIName);

                            fieldsDetails[field.APIName] = fieldDetail;
                        }

                        if (Constants.INVENTORY_MODULES.Contains(moduleAPIName.ToLower()))
                        {
                            JObject fieldDetail = new JObject();

                            fieldDetail.Add(Constants.NAME, Constants.LINE_TAX);

                            fieldDetail.Add(Constants.TYPE, Constants.LIST_NAMESPACE);

                            fieldDetail.Add(Constants.STRUCTURE_NAME, Constants.LINE_TAX_NAMESPACE);

                            fieldDetail.Add(Constants.LOOKUP, true);

                            fieldsDetails.Add(Constants.LINE_TAX, fieldDetail);
                        }

                        if (Constants.NOTES.Equals(moduleAPIName, StringComparison.OrdinalIgnoreCase))
                        {
                            JObject fieldDetail = new JObject();

                            fieldDetail.Add(Constants.NAME, Constants.ATTACHMENTS);

                            fieldDetail.Add(Constants.TYPE, Constants.LIST_NAMESPACE);

                            fieldDetail.Add(Constants.STRUCTURE_NAME, Constants.ATTACHMENTS_NAMESPACE);

                            fieldsDetails.Add(Constants.ATTACHMENTS, fieldDetail);
                        }
                    }
                    else if (responseHandler is Fields.APIException)
                    {
                        Fields.APIException exception = (Fields.APIException)responseHandler;

                        JObject errorResponse = new JObject();

                        errorResponse.Add(Constants.CODE, exception.Code.Value);

                        errorResponse.Add(Constants.STATUS, exception.Status.Value);

                        errorResponse.Add(Constants.MESSAGE, exception.Message.Value);

                        SDKException exception1 = new SDKException(Constants.API_EXCEPTION, errorResponse);

                        if (Utility.moduleAPIName.ToLower().Equals(moduleAPIName.ToLower()))
                        {
                            throw exception1;
                        }

                        SDKLogger.LogError(JsonConvert.SerializeObject(exception1));
                    }
                }
                else
                {
                    JObject errorResponse = new JObject();

                    errorResponse.Add(Constants.CODE, response.StatusCode);

                    throw new SDKException(Constants.API_EXCEPTION, errorResponse);
                }
            }

            return(fieldsDetails);
        }
コード例 #6
0
        /// <summary>
        /// This method to initialize the SDK.
        /// </summary>
        /// <param name="user">A User class instance represents the CRM user.</param>
        /// <param name="environment">A Environment class instance containing the CRM API base URL and Accounts URL.</param>
        /// <param name="token">A Token class instance containing the OAuth client application information.</param>
        /// <param name="store">A TokenStore class instance containing the token store information.</param>
        /// <param name="sdkConfig">A SDKConfig class instance containing the configuration.</param>
        /// <param name="sdkConfig">A SDKConfig class instance containing the configuration.</param>
        /// <param name="logger">A Logger class instance containing the log file path and Logger type.</param>
        /// <param name="proxy">An RequestProxy class instance containing the proxy properties of the user.</param>
        public static void Initialize(UserSignature user, Dc.DataCenter.Environment environment, Token token, TokenStore store, SDKConfig sdkConfig, string resourcePath, Logger.Logger logger, RequestProxy proxy)
        {
            try
            {
                if (user == null)
                {
                    throw new SDKException(Constants.INITIALIZATION_ERROR, Constants.USERSIGNATURE_ERROR_MESSAGE);
                }

                if (environment == null)
                {
                    throw new SDKException(Constants.INITIALIZATION_ERROR, Constants.ENVIRONMENT_ERROR_MESSAGE);
                }

                if (token == null)
                {
                    throw new SDKException(Constants.INITIALIZATION_ERROR, Constants.TOKEN_ERROR_MESSAGE);
                }

                if (store == null)
                {
                    throw new SDKException(Constants.INITIALIZATION_ERROR, Constants.STORE_ERROR_MESSAGE);
                }

                if (sdkConfig == null)
                {
                    throw new SDKException(Constants.INITIALIZATION_ERROR, Constants.SDK_CONFIG_ERROR_MESSAGE);
                }

                if (string.IsNullOrEmpty(resourcePath) || string.IsNullOrWhiteSpace(resourcePath))
                {
                    throw new SDKException(Constants.INITIALIZATION_ERROR, Constants.RESOURCE_PATH_ERROR_MESSAGE);
                }

                if (!Directory.Exists(resourcePath))
                {
                    throw new SDKException(Constants.INITIALIZATION_ERROR, Constants.RESOURCE_PATH_INVALID_ERROR_MESSAGE);
                }

                if (logger == null)
                {
                    logger = Logger.Logger.GetInstance(Logger.Logger.Levels.INFO, Path.GetDirectoryName(Assembly.GetCallingAssembly().Location) + Path.DirectorySeparatorChar + Constants.LOG_FILE_NAME);
                }

                SDKLogger.Initialize(logger);

                try
                {
                    string result = "";

                    using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(Constants.JSON_DETAILS_FILE_PATH))
                    {
                        using (StreamReader reader = new StreamReader(stream))
                        {
                            result = reader.ReadToEnd();
                        }
                    }

                    jsonDetails = JObject.Parse(result);
                }
                catch (System.Exception e)
                {
                    throw new SDKException(Constants.JSON_DETAILS_ERROR, e);
                }

                initializer = new Initializer();

                initializer.user = user;

                initializer.environment = environment;

                initializer.token = token;

                initializer.store = store;

                initializer.sdkConfig = sdkConfig;

                initializer.resourcePath = resourcePath;

                initializer.requestProxy = proxy;

                SDKLogger.LogInfo(Constants.INITIALIZATION_SUCCESSFUL + initializer.ToString());
            }
            catch (SDKException e)
            {
                throw e;
            }
            catch (Exception e)
            {
                throw new SDKException(Constants.INITIALIZATION_EXCEPTION, e);
            }
        }
コード例 #7
0
        /// <summary>
        /// This method makes a Zoho CRM Rest API request.
        /// </summary>
        /// <param name="converterInstance">A Converter class instance to call appendToRequest method.</param>
        /// <returns>HttpWebResponse class instance or null</returns>
        public HttpWebResponse FireRequest(Converter converterInstance)
        {
            SetQueryParams();

            HttpWebRequest requestObj = (HttpWebRequest)WebRequest.Create(url);

            RequestProxy requestProxy = Initializer.GetInitializer().RequestProxy;

            if (requestProxy != null)
            {
                //Validate proxy address
                var proxyURI = new Uri(string.Format("{0}:{1}", requestProxy.Host, requestProxy.Port));

                ICredentials credentials = null;

                if (requestProxy.User != null)
                {
                    //Set credentials
                    credentials = new NetworkCredential(requestProxy.User, requestProxy.Password, requestProxy.UserDomain);
                }

                //Set proxy
                requestObj.Proxy = new WebProxy(proxyURI, true, null, credentials);

                SDKLogger.LogInfo(this.ProxyLog(requestProxy));
            }

            requestObj.Timeout = Initializer.GetInitializer().SDKConfig.Timeout;

            SetRequestMethod(requestObj);

            if (contentType != null)
            {
                this.SetContentTypeHeader(ref requestObj);
            }

            SetQueryHeaders(ref requestObj);

            if (requestBody != null)
            {
                converterInstance.AppendToRequest(requestObj, requestBody);
            }

            SDKLogger.LogInfo(ToString());

            HttpWebResponse response;

            try
            {
                response = (HttpWebResponse)requestObj.GetResponse();
            }
            catch (WebException e)
            {
                if (e.Response == null)
                {
                    throw;
                }

                response = (HttpWebResponse)e.Response;
            }

            return(response);
        }
コード例 #8
0
        /// <summary>
        /// This method is used in constructing API request and response details. To make the Zoho CRM API calls.
        /// </summary>
        /// <typeparam name="T">A T containing the specified type method.</typeparam>
        /// <param name="className">A Type containing the method return type.</param>
        /// <param name="encodeType">A string containing the expected API response content type.</param>
        /// <returns>A APIResponse&lt;T&gt; representing the Zoho CRM API response instance or null. </returns>
        public APIResponse <T> APICall <T>(Type className, string encodeType)
        {
            if (Initializer.GetInitializer() == null)
            {
                throw new SDKException(Constants.SDK_UNINITIALIZATION_ERROR, Constants.SDK_UNINITIALIZATION_MESSAGE);
            }

            APIHTTPConnector connector = new APIHTTPConnector
            {
                RequestMethod = httpMethod
            };

            try
            {
                SetAPIURL(connector);
            }
            catch (SDKException e)
            {
                SDKLogger.LogError(Constants.SET_API_URL_EXCEPTION + JsonConvert.SerializeObject(e));

                throw e;
            }
            catch (Exception e)
            {
                SDKException exception = new SDKException(e);

                SDKLogger.LogError(Constants.SET_API_URL_EXCEPTION + JsonConvert.SerializeObject(exception));

                throw exception;
            }

            connector.ContentType = contentType;

            if (header != null && header.HeaderMaps.Count > 0)
            {
                connector.Headers = header.HeaderMaps;
            }

            if (param != null && param.ParameterMaps.Count > 0)
            {
                connector.Params = param.ParameterMaps;
            }

            try
            {
                Initializer.GetInitializer().Token.Authenticate(connector);
            }
            catch (SDKException e)
            {
                SDKLogger.LogError(Constants.AUTHENTICATION_EXCEPTION + JsonConvert.SerializeObject(e));

                throw e;
            }
            catch (Exception e)
            {
                SDKException exception = new SDKException(e);

                SDKLogger.LogError(Constants.AUTHENTICATION_EXCEPTION + JsonConvert.SerializeObject(exception));

                throw exception;
            }

            string pack = className.FullName;

            Converter convertInstance = null;

            if (contentType != null && Constants.GENERATE_REQUEST_BODY.Contains(httpMethod.ToUpper()))
            {
                object request;

                try
                {
                    convertInstance = GetConverterClassInstance(contentType.ToLower());

                    request = convertInstance.FormRequest(this.request, this.request.GetType().FullName, null, null);
                }
                catch (SDKException e)
                {
                    SDKLogger.LogError(Constants.FORM_REQUEST_EXCEPTION + JsonConvert.SerializeObject(e));

                    throw e;
                }
                catch (Exception e)
                {
                    SDKException exception = new SDKException(e);

                    SDKLogger.LogError(Constants.FORM_REQUEST_EXCEPTION + JsonConvert.SerializeObject(exception));

                    throw exception;
                }

                connector.RequestBody = request;
            }

            try
            {
                connector.AddHeader(Constants.ZOHO_SDK, Environment.OSVersion.Platform.ToString() + "/" +
                                    Environment.OSVersion.Version.ToString() + "/csharp-2.1/" +
                                    Environment.Version.Major.ToString() + "." +
                                    Environment.Version.Minor.ToString() + ":" + Constants.SDK_VERSION);

                HttpWebResponse response = connector.FireRequest(convertInstance);

                int statusCode = (int)response.StatusCode;

                string statusDescription = response.StatusDescription;

                Dictionary <string, string> headerMap = GetHeaders(response.Headers);

                bool isModel = false;

                string mimeType = response.ContentType;

                Model returnObject = null;

                if (!string.IsNullOrEmpty(mimeType) && !string.IsNullOrWhiteSpace(mimeType))
                {
                    if (mimeType.Contains(";"))
                    {
                        mimeType = mimeType.Split(';')[0];
                    }

                    convertInstance = GetConverterClassInstance(mimeType.ToLower());

                    returnObject = (Model)convertInstance.GetWrappedResponse(response, pack);

                    if (returnObject != null && (pack.Equals(returnObject.GetType().FullName) || IsExpectedType(returnObject, pack)))
                    {
                        isModel = true;
                    }
                }
                else
                {
                    if (response != null)
                    {
                        HttpWebResponse responseEntity = ((HttpWebResponse)response);

                        string responseString = new StreamReader(responseEntity.GetResponseStream()).ReadToEnd();

                        SDKLogger.LogError(Constants.API_ERROR_RESPONSE + responseString);

                        responseEntity.Close();
                    }
                }

                return(new APIResponse <T>(headerMap, statusCode, returnObject, isModel, statusDescription));
            }
            catch (SDKException e)
            {
                SDKLogger.LogError(Constants.API_CALL_EXCEPTION + JsonConvert.SerializeObject(e));

                throw e;
            }
            catch (Exception e)
            {
                SDKException exception = new SDKException(e);

                SDKLogger.LogError(Constants.API_CALL_EXCEPTION + JsonConvert.SerializeObject(exception));

                throw exception;
            }
        }