public void SaveOAuthData(ZohoOAuthTokens zohoOAuthTokens) { string connectionString = $"server=localhost;database=zohooauth;port=3306;username={GetMySqlUserName()};password={GetMySqlPassword()}"; 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) { Console.WriteLine(e.ToString()); } finally { if (connection != null) { Console.WriteLine("Connection closed"); connection.Close(); } } }
//TODO: Generate ZohoOAuthTokens Class for GenerateAccessTokens Method(); //TODO: This method throws an exception; public ZohoOAuthTokens GenerateAccessToken(string grantToken) { if (grantToken == null || grantToken.Length == 0) { //TODO: Throw an ZohoOAuthException; Console.WriteLine("Null Grant Token"); } //TODO: Inspect the usage of Contract; Console.WriteLine("access token ok"); var conn = GetZohoConnector(ZohoOAuth.GetTokenURL()); conn.AddParam("grant_type", "authorization_code"); conn.AddParam("code", grantToken); string response = conn.Post(); Console.WriteLine("Request posted"); Dictionary <string, string> responseJSON = JsonConvert.DeserializeObject <Dictionary <string, string> >(response); if (responseJSON.ContainsKey("access_token")) { Console.WriteLine("Response contains Access Token"); ZohoOAuthTokens tokens = GetTokensFromJSON(responseJSON); tokens.UserMaiilId = GetUserMailId(tokens.AccessToken); ZohoOAuth.GetPersistenceHandlerInstance().SaveOAuthData(tokens); //Console.WriteLine(CRM.Library.Common.ZCRMConfigUtil.GetAuthenticationClass()); return(tokens); } //TODO: Throw exceptions and remove the return statement and console statement; Console.WriteLine("Exception fetching access tokens"); return(null); }
public IHttpActionResult CheckToken() { try { ZCRMRestClient.Initialize(config); ZohoOAuthClient client = ZohoOAuthClient.GetInstance(); if (!IsTokenGenerated("*****@*****.**")) { Trace.TraceError("Token Not Generated...Generating Access Token"); ZohoOAuthTokens tokens = client.GenerateAccessToken(grantToken); Trace.TraceError(tokens.AccessToken); } else { Trace.TraceError("Token Generated"); } return(Ok()); } catch (Exception ex) { Trace.TraceError(ex.Message); Trace.TraceError(ex.InnerException.Message); return(Ok()); } }
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(); } } }
//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); } }
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); } }
private ZohoOAuthTokens GetTokensFromJSON(JObject responseJSON) { try { ZohoOAuthTokens tokens = new ZohoOAuthTokens(); long expiresIn = 0; if (!responseJSON.ContainsKey("expires_in_sec")) { expiresIn = Convert.ToInt64(responseJSON[ZohoOAuthConstants.EXPIRES_IN]) * 1000; } else { expiresIn = Convert.ToInt64(responseJSON[ZohoOAuthConstants.EXPIRES_IN]); } tokens.ExpiryTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() + expiresIn - 600000; tokens.AccessToken = (string)responseJSON[ZohoOAuthConstants.ACCESS_TOKEN]; if (responseJSON.ContainsKey(ZohoOAuthConstants.REFRESH_TOKEN)) { tokens.RefreshToken = (string)responseJSON[ZohoOAuthConstants.REFRESH_TOKEN]; } //CRM.Library.Common.ZCRMConfigUtil.ConfigProperties["apiBaseUrl"] = (string)responseJSON["api_domain"]; return(tokens); } catch (Exception) { throw; } }
/// <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); } }
//TODO: Create ZohoOAuthException class and change the throw exception class; private ZohoOAuthTokens RefreshAccessToken(string refreshToken, string userMailId) { if (refreshToken == null) { throw new Exception("Refresh token is not provided"); } try{ ZohoHTTPConnector conn = GetZohoConnector(ZohoOAuth.GetRefreshTokenURL()); conn.AddParam("grant_type", "refresh_token"); conn.AddParam("refresh_token", refreshToken); string response = conn.Post(); Dictionary <string, string> responseJson = JsonConvert.DeserializeObject <Dictionary <string, string> >(response); if (responseJson.ContainsKey("access_token")) { ZohoOAuthTokens tokens = GetTokensFromJSON(responseJson); tokens.RefreshToken = refreshToken; tokens.UserMaiilId = userMailId; ZohoOAuth.GetPersistenceHandlerInstance().SaveOAuthData(tokens); return(tokens); } throw new Exception("Exception while fetching access tokens from site"); }catch (Exception e) { Console.WriteLine(e.Message); throw; } }
public void SaveOAuthTokens(ZohoOAuthTokens zohoOAuthTokens) { InMemoryStorage tokenStorage = InMemoryStorage.GetInstance(); tokenStorage.AccessToken = zohoOAuthTokens.AccessToken; tokenStorage.RefreshToken = zohoOAuthTokens.RefreshToken; tokenStorage.UserIdentifier = zohoOAuthTokens.UserMaiilId; tokenStorage.ExpiryTime = zohoOAuthTokens.ExpiryTime.ToString(); }
public void InitializeZoho(Dictionary <string, string> configuration) { ZCRMRestClient.Initialize(configuration); #region authorizing zoho ZohoOAuthClient client = ZohoOAuthClient.GetInstance(); string refreshToken = this._settings.refreshtoken; ZohoOAuthTokens tokens = client.GenerateAccessTokenFromRefreshToken(refreshToken, this._settings.currentUserEmail); #endregion }
public static void Main(string[] args) { ZCRMRestClient.Initialize(config); ZohoOAuthClient client = ZohoOAuthClient.GetInstance(); string refreshToken = "1000.e2facf5e81488b25451eef2958fef5e5.2cd91733e6db5147dbe4662cac73edc3"; string userMailId = "*****@*****.**"; ZohoOAuthTokens tokens = client.GenerateAccessTokenFromRefreshToken(refreshToken, userMailId); CreateWebHostBuilder(args).Build().Run(); }
public BulkAPIResponse <ZCRMRecord> InsertIssuer(IssuerModel issuer) { // hardcode ZCRMRestClient.Initialize(config); ZohoOAuthClient client = ZohoOAuthClient.GetInstance(); string refreshToken = "1000.354c162c19b5da4fc4053bc4e38dd27f.1e548f961cc913acbacd82fbad0a3387"; string userMailId = "*****@*****.**"; ZohoOAuthTokens tokens = client.GenerateAccessTokenFromRefreshToken(refreshToken, userMailId); List <ZCRMRecord> records = new List <ZCRMRecord>(); ZCRMRecord record1 = new ZCRMRecord("accounts"); //module api name record1.SetFieldValue("Account_Name", issuer.UserName); record1.SetFieldValue("Full_Name", issuer.FullName); record1.SetFieldValue("Username", issuer.UserName); record1.SetFieldValue("Industry", "1"); record1.SetFieldValue("Company_Name", issuer.BusinessName.ToString()); record1.SetFieldValue("Phone", issuer.MobileNumber); record1.SetFieldValue("Fax", issuer.MobileNumber); record1.SetFieldValue("Employees", 1); record1.SetFieldValue("Total_Amount_Disbursed", issuer.totaldisbursed); record1.SetFieldValue("Last_Repayment_Date", issuer.LastRepaymentDate.Value.ToString()); record1.SetFieldValue("Days_Overdue", issuer.daysoverdue); record1.SetFieldValue("Issuer_Account_Balance", issuer.ActualAmount); record1.SetFieldValue("Outstanding_Amount_with_Late_Fee", issuer.outamountwithlf); record1.SetFieldValue("Outstanding_Amount_no_Late_Fee", issuer.outamountwithoutlf); record1.SetFieldValue("Outstanding_Late_Fee", issuer.outstandinglf); record1.SetFieldValue("Total_Amount_Overdue", issuer.overdueamount); record1.SetFieldValue("Total_Principle_Paid", issuer.totalpaidprincipal); record1.SetFieldValue("Total_Interest_Paid", issuer.totalpaidinterest); record1.SetFieldValue("Total_Late_Fee_Paid", issuer.paidlatefees); record1.SetFieldValue("Total_Late_Interest_Paid", issuer.totalpaidlateinterest); record1.SetFieldValue("Total_Paid_Amount", issuer.TotalPaidAmount); record1.CreatedTime = DateTime.UtcNow.Ticks.ToString(); records.Add(record1); ZCRMModule moduleIns = ZCRMModule.GetInstance("accounts"); //module api name BulkAPIResponse <ZCRMRecord> response = moduleIns.CreateRecords(records); //records - list of ZCRMRecord instances filled with required data for upsert. List <ZCRMRecord> insertedRecords = response.BulkData; //upsertedRecords - list of ZCRMRecord instance foreach (var entityID in response.BulkData) { var newID = new tbl_CheckID { IDZoho = entityID.EntityId, EmailMS = issuer.UserName }; dbzoho.tbl_CheckID.Add(newID); dbzoho.SaveChanges(); } List <EntityResponse> entityResponses = response.BulkEntitiesResponse; //entityResponses - list of EntityResponses instance return(response); }
public List <ZCRMRecord> Post() { //test ZCRMRestClient.Initialize(config); ZohoOAuthClient client = ZohoOAuthClient.GetInstance(); string refreshToken = "1000.354c162c19b5da4fc4053bc4e38dd27f.1e548f961cc913acbacd82fbad0a3387"; string userMailId = "*****@*****.**"; ZohoOAuthTokens tokens = client.GenerateAccessTokenFromRefreshToken(refreshToken, userMailId); List <ZCRMRecord> records = new List <ZCRMRecord>(); var dbContext = new MS_DEVEntities(); var data = dbContext.Database.SqlQuery <InvestorModel>("select investorinfo.*,investamount.totalinvestedamount,investamount.paidP,paidI,paidLI,TotalAmountReceived,currentinFunding,numberofinvested,convert(decimal(18,2),Closeoff_PI)as Closeoff_PI,numofcloseoff,numberoffullypaidnotes,numofdelinquent,convert(decimal(18,2),outstanding_I)as outstanding_I,convert(decimal(18,2),outstanding_P)as outstanding_P,convert(decimal(18,2),outstandingPI)as outstandingPI from ( select oldinformation.*, newinformation.age, newinformation.FullName, newinformation.Gender, newinformation.Mobilenumber, newinformation.Nationality, newinformation.DateofBirth, newinformation.NRIC_Number, newinformation.PassportNumber from( select almost.*, lastlogin from( select users.*, ActualAmount from( select USER_ID, ActualAmount from tbl_Balances where User_ID is not null) as balance left join( select UserID, username, QualifiedDate, AdminVerification, DateCreated from tbl_users ) as users on balance.User_ID = users.UserID) as almost left join( select UserName, max(timestamp) as lastlogin from tbl_AuditLog group by UserName) as pre on almost.UserName = pre.UserName) as oldinformation left join( select User_ID, FullName, Gender, DateofBirth, datediff(year, DateofBirth, getdate()) as age, NRIC_Number, PassportNumber, Mobilenumber, Nationality from tbl_AccountDetails) as newinformation on oldinformation.UserID = newinformation.User_ID) as investorinfo left join( select totalinvested.*,paidI,paidP,paidLI,TotalAmountReceived,OfferedAmount as currentinFunding,numberofinvested,Closeoff_PI,numofcloseoff,numberoffullypaidnotes,outstanding_I,outstanding_P,outstandingPI,numofdelinquent From( select Investor_Id, sum(acceptedamount) as totalinvestedamount from( select OfferId, Investor_Id, case when LoanRequest_Id in (2036, 2001, 2037, 2019, 2004, 2059, 2020, 1994, 2053) then 0 else AcceptedAmount end as acceptedamount,LoanRequest_Id,case when LoanRequest_Id = 2001 then concat('2001','-',offerid) else ContractId end as newcontractid from tbl_Loanoffers where OfferStatus = 1) as a where acceptedamount<>0 group by Investor_Id) as totalinvested left join( select Investor_Id,convert(decimal(18, 2), sum(isnull(paidinterest, 0))) as paidI, convert(decimal(18, 2), sum(isnull(paidprincipal, 0))) as paidP,convert(decimal(18, 2), sum(isnull(paidlateinterest, 0))) as paidLI, convert(decimal(18, 2), sum(isnull(paidinterest, 0) + isnull(paidprincipal, 0) + isnull(paidlateinterest, 0))) as TotalAmountReceived from( select pre1.Investor_Id, pre1.AcceptedAmount, pre1.LoanRequest_Id, pre1.newcontractid, InvestorRepaymentPayment.* from( select OfferId, Investor_Id, AcceptedAmount, LoanRequest_Id,case when LoanRequest_Id = 2001 then concat('2001', '-', offerid) else ContractId end as newcontractid from tbl_Loanoffers where OfferStatus = 1 ) as pre1 join InvestorRepaymentPayment on pre1.OfferId = InvestorRepaymentPayment.OfferID ) as paidamount group by Investor_Id) as totalpaidamount on totalinvested.Investor_Id = totalpaidamount.Investor_Id left join( select Investor_Id,OfferedAmount from tbl_Loanoffers join( select* from tbl_LoanRequests where LoanStatus= 2) as a on tbl_Loanoffers.LoanRequest_Id = a.RequestId) as currentfunding on totalinvested.Investor_Id = currentfunding.Investor_Id left join( select Investor_Id,count(totalinvested) as numberofinvested from( select Investor_Id, sum(acceptedamount) as totalinvested, LoanRequest_Id from( select OfferId, Investor_Id, case when LoanRequest_Id in (2036, 2001, 2037, 2019, 2004, 2059, 2020, 1994, 2053) then 0 else AcceptedAmount end as acceptedamount,LoanRequest_Id,case when LoanRequest_Id = 2001 then concat('2001','-',offerid) else ContractId end as newcontractid from tbl_Loanoffers where OfferStatus = 1) as a where acceptedamount<>0 group by Investor_Id,LoanRequest_Id) as final group by Investor_Id) as numberofinvest on totalinvested.Investor_Id = numberofinvest.Investor_Id left join( select Investor_Id,sum(Principal - isnull(paidprincipal, 0) + interest - isnull(paidinterest, 0)) as Closeoff_PI from( select b.*, c.Investor_Id, c.AcceptedAmount, c.newcontractid from( select a.* From( select InvestorRepayment.*, LoanRequest_Id from InvestorRepayment left join tbl_Loanoffers on InvestorRepayment.OfferID = tbl_Loanoffers.OfferId) as a left join tbl_LoanRequests on a.LoanRequest_Id = tbl_LoanRequests.RequestId where LoanStatus = 9) as b left join( select OfferId, Investor_Id, AcceptedAmount, LoanRequest_Id,case when LoanRequest_Id = 2001 then concat('2001', '-', offerid) else ContractId end as newcontractid from tbl_Loanoffers where OfferStatus = 1) as c on b.OfferId = c.OfferId) as d where PayStatus<>1 group by Investor_Id) as closeoffamount on totalinvested.Investor_Id = closeoffamount.Investor_Id left join( select Investor_Id, count(totalclose) as numofcloseoff from( select a.Investor_Id, sum(AcceptedAmount) as totalclose, LoanRequest_Id from( select OfferId, Investor_Id, AcceptedAmount, LoanRequest_Id,case when LoanRequest_Id = 2001 then concat('2001', '-', offerid) else ContractId end as newcontractid from tbl_Loanoffers where OfferStatus = 1) as a left join tbl_LoanRequests on a.LoanRequest_Id = tbl_LoanRequests.RequestId where LoanStatus = 9 group by Investor_Id,LoanRequest_Id) as final group by Investor_Id) as numberofcloseoff on totalinvested.Investor_Id = numberofcloseoff.Investor_Id left join( select Investor_Id,count(amount) as numberoffullypaidnotes from( select Investor_Id, sum(acceptedamount) as amount, LoanRequest_Id from( select OfferId, Investor_Id, AcceptedAmount, LoanRequest_Id,case when LoanRequest_Id = 2001 then concat('2001', '-', offerid) else ContractId end as newcontractid from tbl_Loanoffers where OfferStatus = 1) as a left join tbl_LoanRequests on a.LoanRequest_Id = tbl_LoanRequests.RequestId where LoanStatus = 7 group by Investor_Id,LoanRequest_Id) as final group by Investor_Id) as fully on totalinvested.Investor_Id = fully.Investor_Id left join( select Investor_Id,sum(principal - isnull(paidprincipal, 0)) as outstanding_P, sum(Interest - isnull(paidinterest, 0)) as outstanding_I, sum(principal + interest - isnull(paidprincipal, 0) - isnull(paidinterest, 0)) as outstandingPI from( select b.*, Investor_Id from( select a.* From( select InvestorRepayment.*, LoanRequest_Id from InvestorRepayment left join tbl_Loanoffers on InvestorRepayment.OfferID = tbl_Loanoffers.OfferId) as a left join tbl_LoanRequests on a.LoanRequest_Id = tbl_LoanRequests.RequestId where LoanStatus in (3, 5, 7, 9)) as b left join( select OfferId, Investor_Id, AcceptedAmount, LoanRequest_Id,case when LoanRequest_Id = 2001 then concat('2001', '-', offerid) else ContractId end as newcontractid from tbl_Loanoffers where OfferStatus = 1) as c on b.OfferID = c.OfferId) as final where PayStatus<>1 group by Investor_Id) as deliquentamount on totalinvested.Investor_Id = deliquentamount.Investor_Id left join( select Investor_Id,count(LoanRequest_Id) as numofdelinquent from( select Investor_Id, sum(acceptedamount) as amount, LoanRequest_Id from( select a.*, RequestId from( select OfferId, Investor_Id, AcceptedAmount, LoanRequest_Id,case when LoanRequest_Id = 2001 then concat('2001', '-', offerid) else ContractId end as newcontractid from tbl_Loanoffers where OfferStatus = 1) as a left join(select* from tbl_LoanRequests where LoanStatus in (3,5,9) ) as b on a.LoanRequest_Id = b.RequestId where RequestId is not null) as pre group by Investor_Id,LoanRequest_Id) as final group by Investor_Id) as numberofdelinquent on totalinvested.Investor_Id = numberofdelinquent.Investor_Id) as investamount on investorinfo.UserID = investamount.Investor_Id").ToList(); //foreach (var rc in data) //{ ZCRMRecord record1 = new ZCRMRecord("accounts"); //module api name record1.SetFieldValue("UserID", "rc.CompanyName"); record1.SetFieldValue("FullName", "rc.FullName"); record1.SetFieldValue("UserName", "rc.UserName"); record1.SetFieldValue("Age", "rc.MobileNumber"); record1.SetFieldValue("Gender", "rc.IssuerAccountBalance"); record1.SetFieldValue("NRIC_Number", "rc.OverdueDate"); record1.SetFieldValue("PassportNumber", "rc.TotalAmountDisbursed"); record1.SetFieldValue("Nationality", "rc.TotalAmountOverdue"); record1.SetFieldValue("DateOfBirth", "rc.OutstandingLateFee"); record1.SetFieldValue("MobileNumber", "rc.OutstandingAmountNoLateFee"); record1.SetFieldValue("SignUpDate", "rc.OutstandingAmountWithLateFee"); record1.SetFieldValue("AdminVerification", "rc.LastRepaymentDate"); record1.SetFieldValue("QualifiedDate", "rc.TotalFeesPaid"); record1.SetFieldValue("LatestLogin", "rc.TotalPrincipalPaid"); record1.SetFieldValue("SumOfNumInvestNotes", "rc.TotalInterestPaid"); record1.SetFieldValue("InvestorAmount_TotalInvested", " rc.TotalLateInterestPaid"); record1.SetFieldValue("SumOfLedgerAmount", "rc.CompanyName"); record1.SetFieldValue("NumberOfDelinquentNote", "rc.FullName"); record1.SetFieldValue("TotalDelinquentAmount", "rc.UserName"); record1.SetFieldValue("NumberOfFullyPaidNote", "rc.MobileNumber"); record1.SetFieldValue("InvestorAmount_PrincipalReceived", "rc.IssuerAccountBalance"); record1.SetFieldValue("InvestorAmount_InvestReceived", "rc.OverdueDate"); record1.SetFieldValue("TotalAmountReceived", "rc.TotalAmountDisbursed"); record1.SetFieldValue("SumOftotPaidLateInterest", "rc.TotalAmountOverdue"); record1.SetFieldValue("NumberOfCloseOffNote", "rc.OutstandingLateFee"); record1.SetFieldValue("TotalCloseOffPandI", "rc.OutstandingAmountNoLateFee"); record1.SetFieldValue("CurrentInFundingAmount", "rc.OutstandingAmountWithLateFee"); record1.SetFieldValue("InvestorAmount_OutstandingP", "rc.LastRepaymentDate"); record1.SetFieldValue("InvestorAmount_OutstandingI", "rc.TotalFeesPaid"); records.Add(record1); //ZCRMModule moduleIns = ZCRMModule.GetInstance("Leads"); //module api name //BulkAPIResponse<ZCRMRecord> response = moduleIns.CreateRecords(records); // } ZCRMModule moduleIns = ZCRMModule.GetInstance("accounts"); //module api name BulkAPIResponse <ZCRMRecord> response = moduleIns.CreateRecords(records); //records - list of ZCRMRecord instances filled with required data for upsert. List <ZCRMRecord> upsertedRecords = response.BulkData; //upsertedRecords - list of ZCRMRecord instance List <EntityResponse> entityResponses = response.BulkEntitiesResponse; //entityResponses - list of EntityResponses instance return(records); }
private bool IsTokenGenerated(string currentUserEmail) { try { ZohoOAuthTokens tokens = ZohoOAuth.GetPersistenceHandlerInstance().GetOAuthTokens(currentUserEmail); return(tokens != null ? true : false); } catch (Exception ex) { Trace.TraceError("Is Token Generated Error: " + ex.Message); return(false); } }
private void InsertZohoLeads(List <ZohoLead> leads) { try { ZCRMRestClient.Initialize(config); ZohoOAuthClient client = ZohoOAuthClient.GetInstance(); if (!IsTokenGenerated("*****@*****.**")) { ZohoOAuthTokens tokens = client.GenerateAccessToken(grantToken); } List <ZCRMRecord> listRecord = new List <ZCRMRecord>(); foreach (var lead in leads) { ZCRMRecord record = ZCRMRecord.GetInstance("Leads", null); //To get ZCRMRecord instance if (lead.Offers != null) { record = InsertZohoLeadOffer(lead); listRecord.Add(record); } if (lead.HighBidAmount != null) { record = InsertZohoLeadBid(lead); listRecord.Add(record); } if (lead.MemberMessage != null) { record = InsertZohoLeadMessage(lead); listRecord.Add(record); } } ZCRMModule moduleIns = ZCRMModule.GetInstance("Leads"); BulkAPIResponse <ZCRMRecord> responseIns = moduleIns.CreateRecords(listRecord); //To call the create record method if (responseIns.HttpStatusCode != ZCRMSDK.CRM.Library.Api.APIConstants.ResponseCode.OK) { Console.WriteLine("Error"); } } catch (Exception ex) { Trace.TraceError(ex.Message); throw ex; } }
//TODO: Throws jsonexception; private ZohoOAuthTokens GetTokensFromJSON(Dictionary <string, string> responseDict) { ZohoOAuthTokens tokens = new ZohoOAuthTokens(); long expiresIn = Convert.ToInt64(responseDict["expires_in"]); tokens.ExpiryTime = (long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc))).TotalMilliseconds + expiresIn; tokens.AccessToken = responseDict["access_token"]; if (responseDict.ContainsKey("refresh_token")) { tokens.RefreshToken = responseDict["refresh_token"]; } Console.WriteLine("Token Fetched from JSON"); return(tokens); }
public ZohoOAuthTokens GetOAuthTokens(string userMailId) { InMemoryStorage tokenStorage = InMemoryStorage.GetInstance(); if (!userMailId.Equals(tokenStorage.UserIdentifier)) { throw new ZohoOAuthException("Given User not found in configuration"); } ZohoOAuthTokens tokens = new ZohoOAuthTokens(); tokens.UserMaiilId = tokenStorage.UserIdentifier; tokens.AccessToken = tokenStorage.AccessToken; tokens.RefreshToken = tokenStorage.RefreshToken; tokens.ExpiryTime = System.Convert.ToInt64(tokenStorage.ExpiryTime); return(tokens); }
public ZohoOAuthTokens GetOAuthTokens(string userMailId) { string connectionString = $"server=localhost;database=zohooauth;port=3306;username={GetMySqlUserName()};password={GetMySqlPassword()}"; MySqlConnection connection = null; ZohoOAuthTokens tokens = new ZohoOAuthTokens(); Boolean isUserAvailable = false; try { connection = new MySqlConnection(connectionString); string commandStatement = "select * from oauthtokens where useridentifier = @userIdentifier"; connection.Open(); MySqlCommand command = new MySqlCommand(commandStatement, connection); command.Parameters.AddWithValue("@userIdentifier", userMailId); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { isUserAvailable = true; tokens.UserMaiilId = userMailId; tokens.AccessToken = reader["accesstoken"].ToString(); tokens.RefreshToken = reader["refreshtoken"].ToString(); tokens.ExpiryTime = Convert.ToInt64(reader["expirytime"]); } } if (!isUserAvailable) { throw new ZohoOAuthException("User not available in persistence"); } } catch (MySqlException e) { tokens = null; //TODO: Log the info; Console.WriteLine(e.ToString()); throw new ZohoOAuthException(e); } finally { if (connection != null) { Console.WriteLine("Connection closed"); connection.Close(); } } return(tokens); }
public ZohoOAuthTokens GetOAuthTokens(string userMailId) { string connectionString = $"server={GetServerName()};username={GetMySqlUserName()};password={GetMySqlPassword()};database={GetDataBaseName()};port={GetPortNumber()};persistsecurityinfo=True;SslMode=none;"; MySqlConnection connection = null; ZohoOAuthTokens tokens = new ZohoOAuthTokens(); Boolean isUserAvailable = false; try { connection = new MySqlConnection(connectionString); string commandStatement = "select * from oauthtokens where useridentifier = @userIdentifier"; connection.Open(); MySqlCommand command = new MySqlCommand(commandStatement, connection); command.Parameters.AddWithValue("@userIdentifier", userMailId); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { isUserAvailable = true; tokens.UserMaiilId = userMailId; tokens.AccessToken = reader["accesstoken"].ToString(); tokens.RefreshToken = reader["refreshtoken"].ToString(); tokens.ExpiryTime = Convert.ToInt64(reader["expirytime"]); } } if (!isUserAvailable) { throw new ZohoOAuthException("User not available in persistence"); } return(tokens); } catch (MySqlException e) { tokens = null; ZCRMLogger.LogError("Exception while fetching tokens from database" + e); throw new ZohoOAuthException(e); } finally { if (connection != null) { connection.Close(); } } }
public void SaveOAuthTokens(ZohoOAuthTokens zohoOAuthTokens) { try { FileStream outFile = new FileStream(GetPersistenceHandlerFilePath(), FileMode.Create); using (StreamWriter writer = new StreamWriter(outFile)) { writer.WriteLine("useridentifier=" + zohoOAuthTokens.UserMaiilId); writer.WriteLine("accesstoken=" + zohoOAuthTokens.AccessToken); writer.WriteLine("refreshtoken=" + zohoOAuthTokens.RefreshToken); writer.WriteLine("expirytime=" + zohoOAuthTokens.ExpiryTime); } }catch (Exception e) when(e is UnauthorizedAccessException || e is DirectoryNotFoundException) { ZCRMLogger.LogError("Exception while inserting tokens to config file " + e); throw new ZohoOAuthException(e); } }
public ZohoOAuthTokens GetOAuthTokens(string userMailId) { ZohoOAuthTokens tokens = new ZohoOAuthTokens(); Dictionary <string, string> oauthTokens = ZohoOAuthUtil.ConfigFileSectionToDict("oauthtokens"); if (!oauthTokens["useridentifier"].Equals(userMailId)) { //TODO: Throw ZohoOAuthException and remove the console write statement; Console.WriteLine("Given user not found in persistence"); } tokens.UserMaiilId = oauthTokens["useridentifier"]; tokens.AccessToken = oauthTokens["accesstoken"]; tokens.RefreshToken = oauthTokens["refreshtoken"]; tokens.ExpiryTime = Convert.ToInt64(oauthTokens["expirytime"]); //TODO: Log the exceptions and implement try catching statements return(tokens); }
// POST api/issuer public List <ZCRMRecord> Post() { //tesst ZCRMRestClient.Initialize(config); ZohoOAuthClient client = ZohoOAuthClient.GetInstance(); string refreshToken = "1000.354c162c19b5da4fc4053bc4e38dd27f.1e548f961cc913acbacd82fbad0a3387"; string userMailId = "*****@*****.**"; ZohoOAuthTokens tokens = client.GenerateAccessTokenFromRefreshToken(refreshToken, userMailId); List <ZCRMRecord> records = new List <ZCRMRecord>(); var dbContext = new MS_DEVEntities(); var data = dbContext.Database.SqlQuery <IssuerModel>("select BusinessName,FullName,Mobilenumber,UserName,ActualAmount,max(daysoverdue) as daysoverdue, sum(totaldisbursed) as totaldisbursed, convert(decimal(18,2),sum(isnull(overdueamount,0)))as overdueamount, convert(decimal(18,2),sum(isnull(outstandinglf,0)))as outstandinglf,convert(decimal(18,2),sum(isnull(outamountwithoutlf,0)))as outamountwithoutlf,convert(decimal(18,2),sum(isnull(outamountwithlf,0)))as outamountwithlf, max(lastrepaymentdate)as lastrepaymentdate,convert(decimal(18,2), sum(isnull(totalpaidamount,0)))as totalpaidamount,convert(decimal(18,2),sum(isnull(totalpaidprincipal,0)))as totalpaidprincipal,convert(decimal(18,2),sum(isnull(totalpaidinterest,0)))as totalpaidinterest,convert(decimal(18,2), sum(isnull(totalpaidlateinterest,0)))as totalpaidlateinterest,convert(decimal(18,2),sum(isnull(paidlatefees,0)))as paidlatefees from( select company.BusinessName, company.FullName,case when company.Mobilenumber = '94389427' and company.UserName = '******' then '97521852' else company.Mobilenumber end as Mobilenumber,case when company.UserName = '******' then '*****@*****.**' else company.UserName end as UserName,company.ActualAmount,max(DAYS_OVERDUE) as daysoverdue, sum(finalamount) as totaldisbursed, sum(isnull(overdueamount, 0)) as overdueamount, sum(isnull(outstandinglf, 0)) as outstandinglf,sum(isnull(outamountwithoutlf, 0)) as outamountwithoutlf,sum(isnull(outamountwithlf, 0)) as outamountwithlf, max(lastrepaymentdate) as lastrepaymentdate, sum(isnull(totalpaidamount, 0)) as totalpaidamount,sum(isnull(totalpaidprincipal, 0)) as totalpaidprincipal,sum(isnull(totalpaidinterest, 0)) as totalpaidinterest, sum(isnull(totalpaidlateinterest, 0)) as totalpaidlateinterest,sum(isnull(paidlatefees, 0)) as paidlatefees from( select LoanRequestID, overduesincedate, lastrepaymentdate,case when LoanStatus = 8 then 0 else DAYS_OVERDUE end as days_overdue, case when loanstatus = 8 then 0 else overdueamount end as overdueamount,case when loanstatus = 8 then 0 else outamountwithoutlf end as outamountwithoutlf, case when LoanStatus = 8 then 0 else outamountwitlf end as outamountwithlf,case when LoanStatus = 8 then 0 else outstandinglf end as outstandinglf,case when LoanRequestID in (2036, 2001, 2037, 2019, 2004, 2059, 2020, 1994, 2053) then 0 else FinalAmount end as FinalAmount, paidlatefees,totalpaidamount,totalpaidprincipal,totalpaidinterest,totalpaidlateinterest from( select z.*,y.lastrepaymentdate,x.DAYS_OVERDUE,x.overdueamount,w.numofoutstandingrepayment,w.numofoverduerepayment,w.numofpaidrepayment,w.totalnumofrepayment,v.outamountwithoutlf,v.outamountwitlf,v.outstandinglf,u.FinalAmount,s.paidlatefees,r.totalpaidamount,q.accepteddate,p.totalpaidprincipal,o.totalpaidinterest,n.totalpaidlateinterest,m.LoanStatus from( select loanrequestid, min(iif(paystatus= 2, duedate,null)) as overduesincedate from issuerrepayment group by LoanRequestID) as z left join( select LoanRequestID, max(date) as lastrepaymentdate from issuerrepayment right join issuerrepaymentpayment on issuerrepayment.IssuerRepID = IssuerRepaymentPayment.IssuerRepID group by LoanRequestID) as y on z.LoanRequestID = y.LoanRequestID left join( select a1.*,b1.overdueamount from( select loanrequestid, isnull(DATEDIFF(day, MIN(IIF(PAYSTATUS<> 1,DUEDATE, NULL)),GETDATE()),0) AS DAYS_OVERDUE from issuerrepayment group by LoanRequestID ) as a1 left join( Select distinct LoanRequestID, Case when paystatus = 2 then SUM(Principal -isnull(PaidPrincipal, 0) - isnull(PaidInterest, 0) + Interest + isnull(lateinterest, 0)) over(partition by loanrequestID) else 0 end as overdueamount from IssuerRepayment where PayStatus = 2 ) as b1 on a1.LoanRequestID = b1.LoanRequestID) as x on z.LoanRequestID = x.LoanRequestID left join( select t.*,isnull(numpaid.numofpaidrepayment, 0) as numofpaidrepayment, isnull(numoverdue.numofoverduerepayment, 0) as numofoverduerepayment, isnull(numoutstanding.numofoutstandingrepayment, 0) as numofoutstandingrepayment from( select LoanRequestID, count(issuerrepid) as totalnumofrepayment from IssuerRepayment group by LoanRequestID) as t left join( select LoanRequestID, count(issuerrepid) as numofpaidrepayment from IssuerRepayment where PayStatus = 1 group by LoanRequestID) as numpaid on t.LoanRequestID = numpaid.LoanRequestID left join( select LoanRequestID, count(issuerrepid) as numofoverduerepayment from IssuerRepayment where PayStatus = 2 group by LoanRequestID ) as numoverdue on t.LoanRequestID = numoverdue.LoanRequestID left join( select LoanRequestID, count(issuerrepid) as numofoutstandingrepayment from IssuerRepayment where PayStatus <> 1 group by LoanRequestID) as numoutstanding on t.LoanRequestID = numoutstanding.LoanRequestID) as w on z.LoanRequestID = w.LoanRequestID left join( select LoanRequestID, sum((isnull(latefees,0)-isnull(paidlatefees, 0))*(1 - isfeewaiver))as outstandinglf,sum(principal - isnull(paidprincipal, 0) + Interest - isnull(paidinterest, 0) + isnull(lateinterest, 0)) as outamountwithoutlf,sum(principal - isnull(paidprincipal, 0) + Interest - isnull(paidinterest, 0) + isnull(lateinterest, 0) + (isnull(latefees, 0) - isnull(paidlatefees, 0)) * (1 - isfeewaiver)) as outamountwitlf from IssuerRepayment where PayStatus <> 1 group by LoanRequestID) as v on z.LoanRequestID = v.LoanRequestID left join( select RequestId, FinalAmount from tbl_LoanRequests ) as u on z.LoanRequestID = u.RequestId left join( select loanrequestid, sum(isnull(paidprincipal,0)+isnull(paidinterest, 0) + isnull(paidlateinterest, 0)) as totalamountpaid from issuerrepayment group by loanrequestid) t on z.LoanRequestID = t.LoanRequestID left join( select loanrequestid, sum(isnull(paidlatefees,0)) as paidlatefees from issuerrepayment where IsFeeWaiver = 0 group by loanrequestid) as s on z.LoanRequestID = s.LoanRequestID left join( select case when a.LoanRequestID is not null then a.LoanRequestID else b.LoanRequestID end as loanrequestid, isnull(totalpaid, 0) + isnull(totalpaida, 0) as totalpaidamount from( select LoanRequestID, sum(amount + isnull(PaidLateInterest, 0)) as totalpaid from IssuerRepayment where paystatus = 1 group by LoanRequestID) as a full join(select LoanRequestID, sum(isnull(paidprincipal,0)+isnull(paidinterest, 0) + isnull(paidlateinterest, 0)) as totalpaida from IssuerRepayment where PayStatus <> 1 group by LoanRequestID) as b on a.loanrequestid = b.loanrequestid ) as r on z.LoanRequestID = r.loanrequestid left join( select requestid, accepteddate from tbl_loanrequests) as q on z.loanrequestid = q.requestid left join( select case when a.LoanRequestID is not null then a.LoanRequestID else b.LoanRequestID end as loanrequestid, isnull(totalpaid, 0) + isnull(totalpaida, 0) as totalpaidprincipal from( select LoanRequestID, sum(Principal) as totalpaid from IssuerRepayment where paystatus = 1 group by LoanRequestID) as a full join(select LoanRequestID, sum(isnull(paidprincipal,0)) as totalpaida from IssuerRepayment where PayStatus <> 1 group by LoanRequestID) as b on a.loanrequestid = b.loanrequestid) as p on z.LoanRequestID = p.loanrequestid left join( select case when a.LoanRequestID is not null then a.LoanRequestID else b.LoanRequestID end as loanrequestid, isnull(totalpaid, 0) + isnull(totalpaida, 0) as totalpaidinterest from( select LoanRequestID, sum(interest) as totalpaid from IssuerRepayment where paystatus = 1 group by LoanRequestID) as a full join(select LoanRequestID, sum(isnull(PaidInterest,0)) as totalpaida from IssuerRepayment where PayStatus <> 1 group by LoanRequestID) as b on a.loanrequestid = b.loanrequestid) as o on z.LoanRequestID = o.loanrequestid left join( select case when a.LoanRequestID is not null then a.LoanRequestID else b.LoanRequestID end as loanrequestid, isnull(totalpaid, 0) + isnull(totalpaida, 0) as totalpaidlateinterest from( select LoanRequestID, sum(isnull(paidlateinterest, 0)) as totalpaid from IssuerRepayment where paystatus = 1 group by LoanRequestID) as a full join(select LoanRequestID, sum(isnull(PaidInterest,0)) as totalpaida from IssuerRepayment where PayStatus <> 1 group by LoanRequestID) as b on a.loanrequestid = b.loanrequestid) as n on z.LoanRequestID = n.loanrequestid left join( select RequestId, LoanStatus from tbl_loanRequests) as m on z.LoanRequestID = m.RequestId ) as notelevelmini ) as notelevel left join( select accountdetails.BusinessName, tbl_loanrequests.RequestId, accountdetails.FullName, accountdetails.Mobilenumber, users.UserName, balance.ActualAmount from tbl_loanrequests left join(select BusinessName, NRIC_Number, USER_ID, FullName, Mobilenumber from tbl_AccountDetails) as accountdetails on accountdetails.user_ID = tbl_loanrequests.user_ID left join( select userid, username from tbl_Users) as users on tbl_LoanRequests.User_ID = users.UserID left join( select User_ID, ActualAmount from tbl_Balances) as balance on tbl_LoanRequests.User_ID = balance.User_ID) as company on notelevel.LoanRequestID = company.RequestId group by BusinessName, fullname, UserName, Mobilenumber,ActualAmount) as abc group by BusinessName,FullName,UserName,Mobilenumber,ActualAmount ").ToList(); //foreach (var rc in data) //{ ZCRMRecord record1 = new ZCRMRecord("accounts"); //module api name record1.SetFieldValue("CompanyName", "rc.CompanyName"); record1.SetFieldValue("FullName", "rc.FullName"); record1.SetFieldValue("UserName", "rc.UserName"); record1.SetFieldValue("MobileNumber", "rc.MobileNumber"); record1.SetFieldValue("IssuerAccountBalance", "rc.IssuerAccountBalance"); record1.SetFieldValue("OverdueDate", "rc.OverdueDate"); record1.SetFieldValue("TotalAmountDisbursed", "rc.TotalAmountDisbursed"); record1.SetFieldValue("TotalAmountOverdue", "rc.TotalAmountOverdue"); record1.SetFieldValue("OutstandingLateFee", "rc.OutstandingLateFee"); record1.SetFieldValue("OutstandingAmountNoLateFee", "rc.OutstandingAmountNoLateFee"); record1.SetFieldValue("OutstandingAmountWithLateFee", "rc.OutstandingAmountWithLateFee"); record1.SetFieldValue("LastRepaymentDate", "rc.LastRepaymentDate"); record1.SetFieldValue("TotalFeesPaid", "rc.TotalFeesPaid"); record1.SetFieldValue("TotalPrincipalPaid", "rc.TotalPrincipalPaid"); record1.SetFieldValue("TotalInterestPaid", "rc.TotalInterestPaid"); record1.SetFieldValue("TotalLateInterestPaid", " rc.TotalLateInterestPaid"); records.Add(record1); //ZCRMModule moduleIns = ZCRMModule.GetInstance("Leads"); //module api name //BulkAPIResponse<ZCRMRecord> response = moduleIns.CreateRecords(records); // } ZCRMModule moduleIns = ZCRMModule.GetInstance("accounts"); //module api name BulkAPIResponse <ZCRMRecord> response = moduleIns.CreateRecords(records); //records - list of ZCRMRecord instances filled with required data for upsert. List <ZCRMRecord> upsertedRecords = response.BulkData; //upsertedRecords - list of ZCRMRecord instance List <EntityResponse> entityResponses = response.BulkEntitiesResponse; //entityResponses - list of EntityResponses instance return(records); }
public void SaveOAuthData(ZohoOAuthTokens zohoOAuthTokens) { ForceDeleteOAuthData(); Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); ConfigFileSection section = configuration.GetSection("oauthtokens") as ConfigFileSection; if (section == null) { section = new ConfigFileSection(); configuration.Sections.Add("oauthtokens", section); } section.Settings.Add(new ConfigFileElement("useridentifier", zohoOAuthTokens.UserMaiilId)); section.Settings.Add(new ConfigFileElement("accesstoken", zohoOAuthTokens.AccessToken)); section.Settings.Add(new ConfigFileElement("refreshtoken", zohoOAuthTokens.RefreshToken)); section.Settings.Add(new ConfigFileElement("expirytime", zohoOAuthTokens.ExpiryTime.ToString())); section.SectionInformation.ForceSave = true; configuration.Save(ConfigurationSaveMode.Modified); //TODO: Log the exceptions and implement exception handling; }
static void Main(string[] args) { Console.WriteLine("Enter Client Email:"); string clientMail = Console.ReadLine(); Console.WriteLine("Enter Client ID:"); string clientId = Console.ReadLine(); Console.WriteLine("Enter Client Secret:"); string clientSecret = Console.ReadLine(); Console.WriteLine("Enter Grant token:"); string grantToken = Console.ReadLine(); Dictionary <string, string> config = new Dictionary <string, string>() { { "client_id", clientId }, { "client_secret", clientSecret }, { "redirect_uri", "test" }, { "access_type", "offline" }, { "persistence_handler_class", "ZCRMSDK.OAuth.ClientApp.ZohoOAuthFilePersistence, ZCRMSDK" }, { "oauth_tokens_file_path", "./tokens.txt" }, { "apiBaseUrl", "{https://www.zohoapis.com}" }, { "fileUploadUrl", "{https://content.zohoapis.com}" }, { "apiVersion", "v2" }, { "currentUserEmail", clientMail } }; ZCRMRestClient.Initialize(config); ZohoOAuthClient authClient = ZohoOAuthClient.GetInstance(); ZohoOAuthTokens tokens = authClient.GenerateAccessToken(grantToken); Console.WriteLine(tokens.AccessToken); Console.WriteLine(tokens.RefreshToken); Console.ReadLine(); }
public void UpdateInvestor(InvestorModel investor) { var id = dbzoho.tbl_CheckID.FirstOrDefault(p => p.EmailMS == investor.UserName); ZCRMRestClient.Initialize(config); ZohoOAuthClient client = ZohoOAuthClient.GetInstance(); string refreshToken = "1000.354c162c19b5da4fc4053bc4e38dd27f.1e548f961cc913acbacd82fbad0a3387"; string userMailId = "*****@*****.**"; ZohoOAuthTokens tokens = client.GenerateAccessTokenFromRefreshToken(refreshToken, userMailId); List <ZCRMRecord> records = new List <ZCRMRecord>(); ZCRMRecord record1 = new ZCRMRecord("accounts"); //module api name record1.EntityId = id.IDZoho; record1.SetFieldValue("id", id.IDZoho); record1.SetFieldValue("Account_Name", investor.UserName); record1.SetFieldValue("Email", investor.UserName); record1.SetFieldValue("Username", investor.UserName); record1.SetFieldValue("Industry", "1"); record1.SetFieldValue("Status", "1"); record1.SetFieldValue("Phone", investor.MobileNumber); record1.SetFieldValue("Fax", investor.MobileNumber); record1.SetFieldValue("Employees", 1); record1.SetFieldValue("Age", investor.Age); record1.SetFieldValue("Gender", investor.Gender); record1.SetFieldValue("NRIC_Number", investor.NRIC_Number); record1.SetFieldValue("Passport_Number", investor.PassportNumber); record1.SetFieldValue("Date_Of_Birth", investor.DateOfBirth.Value); record1.SetFieldValue("Sign_Up_Date", investor.DateCreated.Value.Date.ToString()); record1.SetFieldValue("Total_Invested", investor.TotalInvestedAmount); record1.SetFieldValue("Admin_Verification", investor.AdminVerification); record1.SetFieldValue("Number_Of_Delinquent_Off_Note", investor.numofdelinquent); record1.SetFieldValue("Number_Of_Fully_Paid_Note", investor.NumberOfFullyPaidNotes); record1.SetFieldValue("Number_of_Close_Off_Note", investor.NumOfCloseOff); record1.SetFieldValue("Qualified_Date", investor.QualifiedDate.Value.Date.ToString()); if (investor.LastLogin == null) { investor.LastLogin = investor.DateCreated; } record1.SetFieldValue("Number_Of_Deliquent_Note", investor.numofdelinquent); record1.SetFieldValue("Last_Login", investor.LastLogin.Value.Date.ToString()); record1.SetFieldValue("Sum_of_Number_Invested_Note", investor.NumberOfInvested); record1.SetFieldValue("Current_in_Funding_Amount", investor.CurrentInFunding); record1.SetFieldValue("Sum_of_Ledge_Amount", investor.ActualAmount); record1.SetFieldValue("Total_Amount_Received", investor.TotalAmountReceived); record1.SetFieldValue("Total_Delinquent_Amount", investor.outstandingPI); record1.SetFieldValue("Outstanding_L", investor.outstanding_I); record1.SetFieldValue("Outstanding_P", investor.outstanding_P); record1.SetFieldValue("Principal_Received", investor.PaidP); record1.SetFieldValue("Interest_Received", investor.PaidI); records.Add(record1); ZCRMModule moduleIns = ZCRMModule.GetInstance("accounts"); //module api name BulkAPIResponse <ZCRMRecord> responseIns = moduleIns.UpdateRecords(records); //To call the Update record method Console.WriteLine("HTTP Status Code:" + responseIns.HttpStatusCode); //To get Update record http response code foreach (EntityResponse response in responseIns.BulkEntitiesResponse) { Console.WriteLine("Status:" + response.Status); //To get Update record response status Console.WriteLine("Message:" + response.Message); //To get Update record response message Console.WriteLine("Details:" + response.ResponseJSON); //To get Update record response details ZCRMRecord record11 = (ZCRMRecord)response.Data; Console.WriteLine(record11.EntityId); //To get inserted record id Console.WriteLine(record11.CreatedTime); Console.WriteLine(record11.ModifiedTime); ZCRMUser CreatedBy = record11.CreatedBy; if (CreatedBy != null) { Console.WriteLine(CreatedBy.Id); Console.WriteLine(CreatedBy.FullName); } ZCRMUser ModifiedBy = record1.ModifiedBy; if (ModifiedBy != null) { Console.WriteLine(ModifiedBy.Id); Console.WriteLine(ModifiedBy.FullName); } } }
//public BulkAPIResponse<ZCRMRecord> InsertInvestor(InvestorModel investor) //{ // ZCRMRestClient.Initialize(config); // ZohoOAuthClient client = ZohoOAuthClient.GetInstance(); // string refreshToken = "1000.354c162c19b5da4fc4053bc4e38dd27f.1e548f961cc913acbacd82fbad0a3387"; // string userMailId = "*****@*****.**"; // ZohoOAuthTokens tokens = client.GenerateAccessTokenFromRefreshToken(refreshToken, userMailId); // List<ZCRMRecord> records = new List<ZCRMRecord>(); // ZCRMRecord record1 = new ZCRMRecord("accounts"); //module api name // record1.SetFieldValue("Account_Name", investor.UserName); // record1.SetFieldValue("Email", investor.UserName); // record1.SetFieldValue("Username", investor.UserName); // record1.SetFieldValue("Industry", "1"); // record1.SetFieldValue("Status", "1"); // record1.SetFieldValue("Phone", investor.MobileNumber); // record1.SetFieldValue("Fax", investor.MobileNumber); // record1.SetFieldValue("Employees", 1); // record1.SetFieldValue("Age", investor.Age); // record1.SetFieldValue("Gender", investor.Gender); // record1.SetFieldValue("NRIC_Number", investor.NRIC_Number); // record1.SetFieldValue("Passport_Number", investor.PassportNumber); // record1.SetFieldValue("Date_Of_Birth", investor.DateOfBirth.Value); // record1.SetFieldValue("Sign_Up_Date", investor.DateCreated.Value.Date.ToString()); // record1.SetFieldValue("Total_Invested", investor.TotalInvestedAmount); // record1.SetFieldValue("Admin_Verification", investor.AdminVerification); // record1.SetFieldValue("Number_Of_Delinquent_Off_Note", investor.numofdelinquent); // record1.SetFieldValue("Number_Of_Fully_Paid_Note", investor.NumberOfFullyPaidNotes); // record1.SetFieldValue("Number_of_Close_Off_Note", investor.NumOfCloseOff); // record1.SetFieldValue("Qualified_Date", investor.QualifiedDate.Value.Date.ToString()); // if (investor.LastLogin == null) // { // investor.LastLogin = investor.DateCreated; // } // record1.SetFieldValue("Last_Login", investor.LastLogin.Value.Date.ToString()); // record1.SetFieldValue("Number_Of_Deliquent_Note", investor.numofdelinquent); // record1.SetFieldValue("Sum_of_Number_Invested_Note", investor.NumberOfInvested); // record1.SetFieldValue("Current_in_Funding_Amount", investor.CurrentInFunding); // record1.SetFieldValue("Sum_of_Ledge_Amount", investor.ActualAmount); // record1.SetFieldValue("Total_Amount_Received", investor.TotalAmountReceived); // record1.SetFieldValue("Total_Delinquent_Amount", investor.outstandingPI); // record1.SetFieldValue("Outstanding_L", investor.outstanding_I); // record1.SetFieldValue("Outstanding_P", investor.outstanding_P); // record1.SetFieldValue("Principal_Received", investor.PaidP); // record1.SetFieldValue("Interest_Received", investor.PaidI); // record1.CreatedTime = DateTime.UtcNow.Ticks.ToString(); // records.Add(record1); // ZCRMModule moduleIns = ZCRMModule.GetInstance("accounts"); //module api name // BulkAPIResponse<ZCRMRecord> response = moduleIns.CreateRecords(records); //records - list of ZCRMRecord instances filled with required data for upsert. // List<ZCRMRecord> insertedRecords = response.BulkData; //upsertedRecords - list of ZCRMRecord instance // foreach (var entityID in response.BulkData) // { // var newID = new tbl_CheckID // { // IDZoho = entityID.EntityId, // EmailMS = investor.UserName // }; // dbzoho.tbl_CheckID.Add(newID); // dbzoho.SaveChanges(); // } // List<EntityResponse> entityResponses = response.BulkEntitiesResponse; //entityResponses - list of EntityResponses instance // return response; //} public void UpdateIssuer(IssuerModel issuer) { var id = dbzoho.tbl_CheckID.FirstOrDefault(p => p.EmailMS == issuer.UserName); ZCRMRestClient.Initialize(config); ZohoOAuthClient client = ZohoOAuthClient.GetInstance(); string refreshToken = "1000.354c162c19b5da4fc4053bc4e38dd27f.1e548f961cc913acbacd82fbad0a3387"; string userMailId = "*****@*****.**"; ZohoOAuthTokens tokens = client.GenerateAccessTokenFromRefreshToken(refreshToken, userMailId); List <ZCRMRecord> records = new List <ZCRMRecord>(); ZCRMRecord record1 = new ZCRMRecord("accounts"); //module api name record1.EntityId = id.IDZoho; record1.SetFieldValue("id", id.IDZoho); record1.SetFieldValue("Account_Name", issuer.UserName); record1.SetFieldValue("Full_Name", issuer.FullName); record1.SetFieldValue("Username", issuer.UserName); record1.SetFieldValue("Industry", "1"); record1.SetFieldValue("Company_Name", issuer.BusinessName.ToString()); record1.SetFieldValue("Phone", issuer.MobileNumber); record1.SetFieldValue("Fax", issuer.MobileNumber); record1.SetFieldValue("Employees", 1); record1.SetFieldValue("Total_Amount_Disbursed", issuer.totaldisbursed); record1.SetFieldValue("Last_Repayment_Date", issuer.LastRepaymentDate.Value.ToString()); record1.SetFieldValue("Days_Overdue", issuer.daysoverdue); record1.SetFieldValue("Issuer_Account_Balance", issuer.ActualAmount); record1.SetFieldValue("Outstanding_Amount_with_Late_Fee", issuer.outamountwithlf); record1.SetFieldValue("Outstanding_Amount_no_Late_Fee", issuer.outamountwithoutlf); record1.SetFieldValue("Outstanding_Late_Fee", issuer.outstandinglf); record1.SetFieldValue("Total_Amount_Overdue", issuer.overdueamount); record1.SetFieldValue("Total_Principle_Paid", issuer.totalpaidprincipal); record1.SetFieldValue("Total_Interest_Paid", issuer.totalpaidinterest); record1.SetFieldValue("Total_Late_Fee_Paid", issuer.paidlatefees); record1.SetFieldValue("Total_Late_Interest_Paid", issuer.totalpaidlateinterest); record1.SetFieldValue("Total_Paid_Amount", issuer.TotalPaidAmount); records.Add(record1); ZCRMModule moduleIns = ZCRMModule.GetInstance("accounts"); //module api name BulkAPIResponse <ZCRMRecord> responseIns = moduleIns.UpdateRecords(records); //To call the Update record method Console.WriteLine("HTTP Status Code:" + responseIns.HttpStatusCode); //To get Update record http response code foreach (EntityResponse response in responseIns.BulkEntitiesResponse) { Console.WriteLine("Status:" + response.Status); //To get Update record response status Console.WriteLine("Message:" + response.Message); //To get Update record response message Console.WriteLine("Details:" + response.ResponseJSON); //To get Update record response details ZCRMRecord record11 = (ZCRMRecord)response.Data; Console.WriteLine(record11.EntityId); //To get inserted record id Console.WriteLine(record11.CreatedTime); Console.WriteLine(record11.ModifiedTime); ZCRMUser CreatedBy = record11.CreatedBy; if (CreatedBy != null) { Console.WriteLine(CreatedBy.Id); Console.WriteLine(CreatedBy.FullName); } ZCRMUser ModifiedBy = record1.ModifiedBy; if (ModifiedBy != null) { Console.WriteLine(ModifiedBy.Id); Console.WriteLine(ModifiedBy.FullName); } } }