Kaizen #19- C# SDK

Kaizen #19- C# SDK

Hello everyone!
Welcome back to another week of Kaizen!
This week, we will discuss the C# SDK.

What is the C# SDK for Zoho CRM?

C# SDK allows you to create client C# applications that you can integrate with Zoho CRM, effortlessly. It serves as a wrapper for the REST APIs, thus making it easier to use the services of Zoho CRM.

Here is a sample of how the SDK acts as a middleware between Zoho CRM and a client C# Application.


What can you do with the C# Software Development Kit?

  • You can use C# SDK to exchange data between Zoho CRM and the client Java application. 
  • The authentication process becomes hassle-free with C# SDK. Since it is handled in the SDK code by default, you need not worry about generating the grant token, access/refresh tokens every time you sync data between Zoho CRM and your client. 
Environment Setup
  • Client app must use .net framework 4.6.1 or above. You can download .net framework through: https://dotnet.microsoft.com/download/dotnet-framework/. The .net core is present by default in Mac and Linux OS.
  • The C# SDK is available as a NuGet package. You can install it in three ways:
    • Packet Manager (Windows OS)
      Goto visual studio > View > Other windows > Package manager console.
      Using the following commands, you can install the C# SDK.
      Install-Package ZCRMSDK
      Install-Package Newtonsoft.Json
      Install-Package MySql.Data
      Install-Package System.IO.Compression.ZipFile -Version 4.3.0
      Install-Package System.IO.Compression -Version 4.3.0
    • .NET CLI
      Install the .NET core CLI by clicking here. Further, in command prompt, navigate to your project and using the following commands, install the C# SDK.
      dotnet add package ZCRMSDK
      dotnet add package Newtonsoft.Json
      dotnet add package MySql.Data [Only if DB persistence is used]
      dotnet add package System.IO.Compression.ZipFile --version 4.3.0
      dotnet add package System.IO.Compression --version 4.3.0
    • Visual Studio
      For Mac OS
      Goto Visual Studio > Project > Dependencies > NuGet > Manage Nuget  Packages > Search for ZCRMSDK and install it.
      For Windows OS
      Goto Visual Studio > Project > References > Manage NuGet packages > In  the browse tab search for ZCRMSDK and install it.
How to Start using the C# SDK?
In this section, we will discuss how to start using the C# SDK for your application (authenticated via self-client) which uses Zoho CRM: 
Step 1: Register your application 
      1.a. For self-client
      1.b. For web-based client
Step 2: Configure your application
      2.a. For .Net Core applications
      2.b. For other applications 
Step 3: Add persistent classes
      3.a. File Persistence
      3.b. DB Persistence
      3.c. InMemory Persistence
Step 4: Initialization
      4.a. Generating grant token
      4.b. Generating access and refresh token using the grant token
      4.c. Generating access token using the refresh token
Let us now discuss these steps in detail.

Step 1: Register your application

All the Zoho CRM APIs are authenticated by the OAuth2.0 standards. It is mandatory to authenticate your application with Zoho.
You can register your application either as a Self Client (single user app) or a web-based app (multiple users app).

1.a. Self Client
  1. Go to https://api-console.zoho.com.
  2. Click ADD CLIENT
  3. Choose the Client Type as Self Client, and click CREATE.
  4. You will receive a client ID and a client secret upon successful registration.


1.b. Web-based Client
  1. Go to https://api-console.zoho.com.
  2. Click ADD CLIENT
  3. Choose the client as Web-based and click CREATE NOW.
  4. Specify the client name, homepage URL of your application's UI, and a redirect URI to which you want to redirect the users after they grant consent to your application.
  5. Click CREATE.

Your Client ID and Client Secret will be displayed.


Step 2: Configure your client application

2.a. For .Net Core applications

Specify the application configuration details in the app.config file. Add a section named oauth_configuration and ensure that the section has the attribute type as 'ZCRMSDK.CRM.Library.Common.ConfigFileHandler.ConfigFileSection, ZCRMSDK', which is a namespace in C# that consists of the code to read the app.config file. 

<configuration>
    <configSections>
        <section name="oauth_configuration" type="ZCRMSDK.CRM.Library.Common.ConfigFileHandler.ConfigFileSection, ZCRMSDK"></section>
        <section name="zcrm_configuration" type="ZCRMSDK.CRM.Library.Common.ConfigFileHandler.ConfigFileSection, ZCRMSDK"></section>
    </configSections>
    <oauth_configuration>
        <settings>
            <add key="client_id" value="1000. xxxxxxx" />
            <add key="client_secret" value="xxxxxxxx" />
            <add key="redirect_uri" value="null" />
            <add key="iamUrl" value="https://accounts.zoho.com" />
            <add key="persistence_handler_class" value="com.zoho.oauth.clientapp.ZohoOAuthDBPersistence" />
            <!--for database. "com.zoho.oauth.clientapp.ZohoOAuthFilePersistence" for file, user can also implement own persistence and provide the path here-->
            <add key="mysql_username" value="username" />
            <add key="mysql_password" value="password" />
            <add key="mysql_database" value="zohooauth" />
            <add key="mysql_server" value="localhost" />
            <add key="mysql_port" value="3306" />
            <add key="oauth_tokens_file_path" value="/path/to/file.log" />
            <!--Ex:/User/Document/testapplication/src/file.txt). The file can be .txt or .config-->
        </settings>
    </oauth_configuration>
    <zcrm_configuration>
        <settings>
            <add key="apiBaseUrl" value="https://www.zohoapis.com" />
            <add key="photoUrl" value="https://profile.zoho.com/api/v1/user/self/photo" />
            <add key="apiVersion" value="v2" />
            <add key="logFilePath" value="/path/to/file.log" />
            <!--path must be absolute(Ex:/User/Document/testapplication/src/file.log)-->
            <add key="timeout" value="3000" />
            <add key="minLogLevel" value="WARNING" />
            <add key="currentUserEmail" value="patricia@zylker.com" />
            <add key="domainSuffix" value=".com" />
        </settings>
    </zcrm_configuration>
</configuration>

Key Value Description
a. <oauth_configuration>
Key 
Description
client_id and client_secret
mandatory
Client details you received after registering your application. 
redirect_uri
mandatory for web-based clients
The callback URL that you specified during client registration. You need not specify this key for self client from ZCRMSDK version 2.1.5. For lesser versions, this key is mandatory for all types of clients. In the case of self-client in lesser versions, specify the value as "null".
iamURL
optional
The domain-specific accounts URL from which you generate the tokens.
peristence_handler_class
mandatory
Name of the class of the custom implementation for persistence. This key is mandatory if you want to use custom persistence.
mysql_password, mysql_username, mysql_port, mysql_database, mysql_server
mandatory when you use DB persistence
The MySQL details. Default values are:
mysql_username="root",
mysql_password="youe_password",
mysql_database="zohoauth",
mysql_sever="localhost",
and mysql_port="3306".
oauth_tokens_file_path
mandatory when you use file persistence
The path to store the OAuth tokens in the file. This key is mandatory if you want to use file persistence. If you include this key, this method takes precedence over other persistent methods.

b.<zcrm_configuration>

Key
Description
apiBaseUrl
optional
The domain-specific API URL from which you make API calls. For users from domains other than US, this key is mandatory.
photoUrl
optional
The URL of the image representing the record. It differs based on apiBaseUrl.
apiVersion
optional
Represents the version of the CRM APIs. The value is v2.
logFilePath
optional
The absolute path to log the exceptions during the usage of the SDK.
timeout
optional
The request timeout in milliseconds.
minLogLevel
optional
Represents the minimum log level for logging of SDK. The supported values are:
a. ALL: Verbose messages, informational messages, warning messages, and error messages.
b. INFO (default): Informational messages. warning messages, and error messages
c. WARNING: Warning messages and error messages
d. ERROR: Only error messages.
e. OFF: None
currentUserEmail
mandatory
The email ID of the current user. When you do not specify this value, the SDK throws an exception. This key is mandatory in the configuration dictionary for self-client apps.
domainSuffix
optional
The domain from which the API calls are made. It can be com(for US), eu(for Europe), cn(for China), au(for Australia). If you specify this value, you need not specify apiBaseUrl and iamURL.

2.b. For other applications like ASP.NET, ASP Web App, ASP Website, and so on

Specify the application configuration details in the configuration dictionary. In this case, you can specify the properties of <oauth_configuration> and <zcrm_configuration> in a single section.

Sample:

public static Dictionary<string, string> config = new Dictionary<string, string>()
 {
 {"client_id","1000.XXXX"},
 {"client_secret","b477XXXX"},
 {"redirect_uri","null"},
{"persistence_handler_class","ZCRMSDK.OAuth.ClientApp.ZohoOAuthDBPersistence, ZCRMSDK"},
  
{"oauth_tokens_file_path","/path/to/file.txt"}, //file can be .txt or .config file
  {"mysql_username","root"},
  {"mysql_password","your_password"},
  {"mysql_database","zohooauth"},
  {"mysql_server","localhost"},
  {"mysql_port","3306"},
  {"apiBaseUrl","{https://www.zohoapis.com}"},
  {"fileUploadUrl","{https://content.zohoapis.com}"},
"},
  {"apiVersion","v2"},
  {"logFilePath","/path/to/file.log" }, //absolute path
  {"timeout","3000"},
  {"minLogLevel","WARNING"},
  {"domainSuffix","com"},
  {"currentUserEmail","patricia@zylker.com"}
 };
ZCRMRestClient.Initialize(config);

Step 3: Add persistence classes

Your application should retain tokens (grant, access, and refresh tokens) to automate the process of data sync between your C# application and Zoho CRM.

You can choose to persist (store) the tokens in three ways.
      3.a. File Persistence
      3.b. DB Persistence
      3.c. In Memory Persistence

3.a. File Persistence

If you want to store the tokens in a file, provide the absolute path of the directory containing this file in the oauth_tokens_file_path key in <oauth_configuration> section in the app.config file (or) config dictionary. The file persists the tokens of a single user. So, it is best used for the 'self-client' type of authentication since it involves only one user.  

Ex: 
<add key = "oauth_tokens_file_path" value = "/User/Document/testapplication/src/file.txt" /> 

The file can be a .txt or .config file.

3.b. DB Persistence

Pre-requisites:

  1. MySQL must be running in the same machine serving at the default port 3306.
  2. The database name should be zohooauth.
  3. There must be a table oauthtokens with the columns useridentifier (varchar(100)), accesstoken (varchar(100)), refreshtoken (varchar(100)) and expirytime (bigint).
To use custom DB persistence, you must
Implement IZohoPersistenceHandler interface, and write a custom implementation of the following functions:
  • GetOAuthTokens: invoked to fetch the saved tokens. This method should return the ZohoOAuthTokens object for the library to process it.
  • SaveOAuthTokens: invoked to store the tokens.
  • DeleteOAuthTokens: invoked to delete the tokens.
Include "persistence_handler_class" in the app.config file (2.a) or configuration dictionary (2.b), along with other mandatory keys. 
Ex: 
a. app.config file: 
<add key = "persistence_handler_class" value = "ZCRMSDK.OAuth.ClientApp.ZohoOAuthDBPersistence"/> 

b. Configuration dictionary: 
{"persistence_handler_class","ZCRMSDK.OAuth.ClientApp.ZohoOAuthDBPersistence, ZCRMSDK"}

If the persistence handler class is not specified, the InMemory Persistence handler handles the persistence implementation by default. Pre-defined persistence handler classes belong to the assembly ZCRMSDK.

3.c. InMemory Persistence

This type of persistence uses a singleton class to store and retrieve tokens. The InMemory persists the tokens of a single user. So, it is best used for the 'self-client' type of authentication since it involves only one user. 

The below table contains the list of keys you must include in the configuration dictionary based on the type of persistence.

Mandatory Keys
File Persistence
DB Persistence
InMemory Persistence
client_id
client_id
client_id
client_secret
client_secret
client_secret
redirect_uri (for web-based client)
redirect_uri (for web-based client)
redirect_uri (for web-based client)
persistence_handler_class
persistence_handler_class
persistence_handler_class
oauth_tokens_file_path
-
-

Optional Keys
File Persistence
DB persistence
InMemory Persistence
logFilePath
logFilePath
logFilePath
apiBaseUrl
apiBaseUrl
apiBaseUrl
apiVersion
apiVersion
apiVersion
currentUserEmail
currentUserEmail
currentUserEmail

Step 4: Initialization

Intializing your application involves the following steps:

      4.a. Generating grant token
      4.b. Generating access and refresh token using the grant token
      4.c. Generating access token using the refresh token

4.a. Generating grant token

For Self Client Applications
  1. Log in to Zoho and go to Zoho Developer Console.
  2. Select your Self Client.
  3. Provide the necessary scopes separated by commas, along with the scope aaaserver.profile.READ
  4. Select the Time Duration from the drop-down. This is the time the grant token is valid for.
  5. Add a description. Click GENERATE.
  6. Copy the grant token.
For Web-based Applications

It is the responsibility of your client app to generate the grant token for the users trying to login.
Your Application's UI must have the Login with Zoho option to open the grant token URL of Zoho, which would prompt for the user's OAuth2.0 authorization.
Upon the successful login of the user, the grant token will be sent as a parameter to your registered redirect URL.

4.b. Generating an access and refresh tokens from the grant token

Use the below code snippet in your main class to generate the access and refresh tokens for the first time. As discussed earlier, the C# SDK will automatically generate the grant token, access/refresh tokens every time you sync data between Zoho CRM and your client.

ZCRMRestClient.Initialize(config);
ZohoOAuthClient client = ZohoOAuthClient.GetInstance();
string grantToken = <paste_grant_token_here>;
ZohoOAuthTokens tokens = client.GenerateAccessToken(grantToken);
string accessToken = tokens.AccessToken;
string refreshToken = tokens.RefreshToken;

Note:
  • The code snippet to generate the access token from the grant token is valid only once per grant token. If the grant token expires before you generate the access token, you must generate a new grant token only.
  • Generating access and refresh tokens is a one-time process. After the tokens are generated for the first time, the SDK persists them based on the keys defined in the configuration dictionary and refreshes the access token as and when required.
4.c. Generating an access token from the refresh token

Use the below code snippet when you already have a refresh token in place, and you want to use it to generate access token:

ZCRMRestClient.Initialize(config);
ZohoOAuthClient client = ZohoOAuthClient.GetInstance();
string refreshToken = <paste_refresh_token_here>;
string userMailId = <provide_user_email_here>;
ZohoOAuthTokens tokens = client. GenerateAccessTokenFromRefreshToken(refreshToken,userMailId);

Starting the application
The SDK requires the following line of code to be invoked every time your app gets started. This method should be called from the main class of your c# application to start the application. It needs to be invoked without any exception.
ZCRMRestClient.Initialize(config);
The parameter passed is the configuration dictionary name (config), if you are using an app.config file, mention null.

Sample code

Here is a sample to insert records. You can find the code in the attachment.


The isTokenGenerated Method

You need to add this method to check if the access token has already been generated or not. It returns a Boolean value.

true - The access token has already been generated. 
false - The access token has not been generated previously, thus, it shifts the control to the code snippet that leads to access token generation.

For more sample codes, refer to REST API samples.

Cheers!

Previous 'Kaizen' - Ruby SDK
Next 'Kaizen' - Node JS SDK

    Access your files securely from anywhere

        Zoho Developer Community







                                  Zoho Desk Resources

                                  • Desk Community Learning Series


                                  • Digest


                                  • Functions


                                  • Meetups


                                  • Kbase


                                  • Resources


                                  • Glossary


                                  • Desk Marketplace


                                  • MVP Corner


                                  • Word of the Day



                                      Zoho Marketing Automation


                                              Manage your brands on social media



                                                    Zoho TeamInbox Resources

                                                      Zoho DataPrep Resources



                                                        Zoho CRM Plus Resources

                                                          Zoho Books Resources


                                                            Zoho Subscriptions Resources

                                                              Zoho Projects Resources


                                                                Zoho Sprints Resources


                                                                  Qntrl Resources


                                                                    Zoho Creator Resources



                                                                        Zoho Campaigns Resources


                                                                          Zoho CRM Resources

                                                                          • CRM Community Learning Series

                                                                            CRM Community Learning Series


                                                                          • Kaizen

                                                                            Kaizen

                                                                          • Functions

                                                                            Functions

                                                                          • Meetups

                                                                            Meetups

                                                                          • Kbase

                                                                            Kbase

                                                                          • Resources

                                                                            Resources

                                                                          • Digest

                                                                            Digest

                                                                          • CRM Marketplace

                                                                            CRM Marketplace

                                                                          • MVP Corner

                                                                            MVP Corner





                                                                              Design. Discuss. Deliver.

                                                                              Create visually engaging stories with Zoho Show.

                                                                              Get Started Now