internal void Initialize(ApplicationUtil applicationUtility)
        {
            this._applicationUtils = applicationUtility;

            var returnDetails = applicationUtility.CredentialStore.GetConnectionDetails();

            _credentialInfo = ObjectUtils.JsonDeserialize <CredentialModel>(returnDetails.Value);
            if (_credentialInfo == null)
            {
                this._credentialInfo = new CredentialModel();
            }
        }
        /// <summary>
        /// Validates credential for configuraion data
        /// </summary>
        /// <param name="configurationData">Represents Credential model</param>
        /// <returns></returns>
        public ReturnMessage <bool> Validate(string configurationData)
        {
            var returnResult = new ReturnMessage <bool>();

            try
            {
                this._credentialInfo = ObjectUtils.JsonDeserialize <CredentialModel>(configurationData);
                if (!string.IsNullOrWhiteSpace(_credentialInfo.AccessToken) &&
                    !string.IsNullOrWhiteSpace(_credentialInfo.RefreshToken))
                {
                    returnResult.SetSuccess("Validation successful");
                }
                else
                {
                    returnResult.SetError("Validation failed. Access and Refresh token not found");
                }
            }
            catch (Exception e)
            {
                returnResult.SetError(e.ToString());
            }

            return(returnResult);
        }
        public string UpdateAccessToken(CredentialModel credentials, ApplicationUtil appUtil)
        {
            string accessToken = string.Empty;

            try
            {
                using (var authClient = new HttpClient())
                {
                    HttpContent content = new FormUrlEncodedContent(new Dictionary <string, string>
                    {
                        { "client_id", credentials.ClientID },
                        { "client_secret", credentials.ClientSecret },
                        { "refresh_token", credentials.RefreshToken },
                        { "grant_type", "refresh_token" }
                    }
                                                                    );
                    HttpResponseMessage message = authClient.PostAsync("https://accounts.zoho.com/oauth/v2/token", content).Result;
                    string  responseString      = message.Content.ReadAsStringAsync().Result;
                    JObject obj = JObject.Parse(responseString);
                    accessToken             = (string)obj["access_token"];
                    credentials.AccessToken = accessToken;
                    appUtil.CredentialStore.SaveConnectionDetails(credentials);
                }
            }
            catch (WebException wex)
            {
                var response = wex.ReadResponse();
                appUtil.Logger.ErrorLog("Unable to generate Access Token", response.Message);
            }
            catch (Exception ex)
            {
                accessToken = ex.Message;
                appUtil.Logger.ErrorLog("Failed to get access token", ex);
            }
            return(accessToken);
        }
        /// <summary>
        /// Generates intermediate resultset for partial data
        /// </summary>
        /// <param name="resource">A dictionay object for different level of data generation</param>
        /// <returns></returns>
        public ReturnMessage <IDictionary <string, string> > PartialValidate(IDictionary <string, string> resource)
        {
            var returnMessage = new ReturnMessage <IDictionary <string, string> >();

            //ToDo : Generate intermediate results for processing data / resultset etc.

            try
            {
                if (resource != null)
                {
                    var credentialInfo = resource["ConfigData"];
                    if (!string.IsNullOrEmpty(credentialInfo))
                    {
                        this._credentialInfo = ObjectUtils.JsonDeserialize <CredentialModel>(credentialInfo);
                        var step      = resource["Step"];
                        int stepValue = 0;
                        if (!string.IsNullOrWhiteSpace(step))
                        {
                            int.TryParse(step, out stepValue);
                        }
                        if (stepValue == 0)
                        {
                            string authorizationUrl = string.Format("https://accounts.zoho.com/oauth/v2/auth?scope={0}&client_id={1}&response_type=code&access_type=offline&redirect_uri={2}", this._credentialInfo.Scope, this._credentialInfo.ClientID, this._credentialInfo.CallBack);
                            resource["RequestUrl"]  = authorizationUrl;
                            resource["OpenBrowser"] = "true";
                            resource["Step"]        = (++stepValue).ToString();
                            resource["CallBack"]    = this._credentialInfo.CallBack;
                            resource["ConfigData"]  = ObjectUtils.JsonSerializer <CredentialModel>(this._credentialInfo);
                            returnMessage.SetSuccess("Success", resource);
                        }
                        else if (stepValue == 1)
                        {
                            var responseUrl = resource["ResponseUrl"];
                            if (!string.IsNullOrWhiteSpace(responseUrl))
                            {
                                string[] urlParts = responseUrl.Split('/');

                                foreach (string urlsPart in urlParts)
                                {
                                    if (urlsPart.Contains("code"))
                                    {
                                        this.tempToken = urlsPart.Split('=')[1];
                                    }
                                }
                                var validateResult = GetAccessToken(tempToken);
                                resource["OpenBrowser"] = "false";
                                resource["ConfigData"]  = ObjectUtils.JsonSerializer <CredentialModel>(this._credentialInfo);
                                if (!string.IsNullOrEmpty(validateResult))
                                {
                                    returnMessage.SetSuccess(validateResult, resource);
                                }
                                else
                                {
                                    returnMessage.SetError(validateResult, resource);
                                }
                            }
                        }
                    }
                    else
                    {
                        returnMessage.SetError("Empty config data");
                    }
                }
                else
                {
                    returnMessage.SetError("Resource data dictionary is empty");
                }
            }
            catch (Exception ex)
            {
                returnMessage.SetError("Error in Partial Validate " + ex.Message);
            }
            return(returnMessage);
        }
        public ReturnMessage <string> HttpGetRequest(string requestUrl, ExecutionSettings settings, CredentialModel credentials, ApplicationUtil appUtil, Logger logger)
        {
            var retMessage = new ReturnMessage <string>();

            //Validate Credential Access Token
            if (!string.IsNullOrEmpty(credentials.AccessToken))
            {
                string     responseData = string.Empty;
                HttpClient client       = new HttpClient();
                try
                {
                    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
                    request.Headers.Add("orgId", credentials.OrganizationId);
                    request.Headers.Add("Authorization", "Zoho-oauthtoken " + credentials.AccessToken);
                    HttpResponseMessage response = client.SendAsync(request).Result;
                    responseData = response.Content.ReadAsStringAsync().Result;
                    if (!string.IsNullOrEmpty(responseData) && ((int)response.StatusCode >= 200 && (int)response.StatusCode <= 204))
                    {
                        var jsonData = XElement.Parse(JsonConvert.DeserializeXmlNode(responseData, "data").OuterXml);
                        retMessage.Value   = jsonData.ToString();
                        retMessage.Status  = true;
                        retMessage.Message = ((int)response.StatusCode).ToString();
                    }
                    else if ((int)response.StatusCode == 401)
                    {
                        retMessage.Message = ((int)response.StatusCode).ToString();
                        retMessage.Value   = responseData;
                    }
                    else
                    {
                        logger.StatusLog($"No data found from zoho desk for GET method, Status {response.StatusCode}", requestUrl);
                        retMessage.Message = ((int)response.StatusCode).ToString();
                        retMessage.Value   = responseData;
                    }

                    return(retMessage);
                }
                catch (WebException ex)
                {
                    var error    = ex.ReadResponse();
                    var response = ex.Response as HttpWebResponse;
                    logger.ErrorLog($"GET operation failed for url {requestUrl}", $"WebException : Error Status : {ex.Status}, Response Status: {response.StatusCode} and Response is : {responseData}");
                    retMessage.SetError(((int)response.StatusCode).ToString());
                    retMessage.AddReturn(error.Message);
                    return(retMessage);
                }
                catch (Exception ex)
                {
                    retMessage.Value  = ex.Message;
                    retMessage.Status = false;
                    return(retMessage);
                }
                finally
                {
                    client.Dispose();
                }
            }
            else
            {
                retMessage.SetError("401");
            }
            return(retMessage);
        }
        public ReturnMessage <string> HttpPostRequest(XElement elements, ExecutionSettings settings, string actionParams, CredentialModel credentials, ApplicationUtil appUtil, Logger logger)
        {
            var returnMessage = new ReturnMessage <string>();

            //Validate Credential Access Token
            if (!string.IsNullOrEmpty(credentials.AccessToken))
            {
                //Stream reader = null;
                HttpWebRequest  request  = null;
                HttpWebResponse response = null;
                XmlDocument     xmlDoc   = new XmlDocument();

                var urlParam  = this.GetElementData(elements, "UploadURL", logger, string.Empty);
                var sourceKey = this.GetElementData(elements, "SourceKey", logger, string.Empty);
                var converter = new XmlToJsonConverter(elements.ToString());
                var url       = $"{credentials.BaseUrl}{urlParam}";
                var jsonData  = converter.Format().Message;


                request = (HttpWebRequest)WebRequest.Create(url);
                request.Headers.Add("orgId", credentials.OrganizationId);
                request.Headers.Add("Authorization", "Zoho-oauthtoken " + credentials.AccessToken);
                request.Method      = actionParams;
                request.ContentType = "application/json";
                string actualResponse = string.Empty;
                try
                {
                    using (var streamWriter = new StreamWriter(request.GetRequestStream()))
                    {
                        streamWriter.Write(jsonData);
                        streamWriter.Flush();
                        streamWriter.Close();
                    }
                    using (response = (HttpWebResponse)request.GetResponse())
                    {
                        using (Stream responseStream = response.GetResponseStream())
                        {
                            using (StreamReader responseReader = new StreamReader(responseStream))
                            {
                                actualResponse = responseReader.ReadToEnd();
                                xmlDoc         = JsonConvert.DeserializeXmlNode(actualResponse, "Results");
                            }
                        }
                    }
                    var xResponse = XElement.Parse(xmlDoc.InnerXml);
                    if (!string.IsNullOrEmpty(sourceKey))
                    {
                        xResponse.Add(new XElement("SourceKey", sourceKey));
                    }

                    returnMessage.Value  = xResponse.ToString();
                    returnMessage.Status = true;
                }
                catch (WebException wex)
                {
                    var error = wex.ReadResponse();
                    response = wex.Response as HttpWebResponse;
                    returnMessage.SetError(((int)response.StatusCode).ToString());
                    returnMessage.AddReturn(error.Message);
                    logger.ErrorLog($"Post operation failed for url {url}", $"WebException : Status : {response.StatusCode}, Data is : {jsonData} and Response is : {actualResponse}");
                }
                catch (Exception ex)
                {
                    logger.ErrorLog($"Post operation failed for url {url}", ex);
                    returnMessage.AddException(ex);
                }
            }
            else
            {
                returnMessage.SetError("401");
            }
            return(returnMessage);
        }