A Deep Dive into Telerik Library for Backend Efficiency
Tags: dotnet, csharp, telerik, backend
Published: 2024-04-07 18:50:21

In the realm of web development, achieving seamless frontend experiences often relies on robust backend support. The Telerik library, which is an essential component and plays a vital role as a powerful ally for developers, seamlessly integrates with frontend stacks that support Kendo UI and provides streamlining data to enhance server-side operations for a wide array of UI components, which include grids, charts, and many more. But the only limitation is that some of the services are  free, and for the important packages, we need to buy the commercial licence, even though we can avail of those packages with a one-month free trial.



## Table of Contents
- [Key Features](#keyFeatures)
- [Overview of Telerik Library](#overview)
- [Supporting Technologies](#supportingTechs)
- [Comparison of Telerik with Other Libraries](#comparisonTable)
- [Why choose Telerik](#whyChooseTelerik)
- [Best Practices with Telerik](#bestPractices)
- [Telerik Setup with .Net Core](#telerikSetup)
- [Implementation with Telerik](#telerikImplementation)



## **Key Features** <a name="keyFeatures"></a>

Now, let's delve into some of the key features that make Telerik Library, an indispensable tool for backend development:

1. **Server-Side Data Operations:** This library enables server-side data operations, significantly reducing the burden of processing data on the client side, which results in smoother performance and enhances the user experience seamlessly.

2. **Paging, Sorting, and Filtering:** The Telerik library provides native support for essential features such as pagination, sorting, filtration, grouping, and many more. This means developers can implement these functionalities effortlessly, without the need for extensive custom coding on the client side.

3. **Enhanced Efficiency:** By leveraging the Telerik library, developers can unlock a new level of efficiency in backend development, since this library's comprehensive feature set minimises the need for manual intervention, allowing developers to focus on crafting innovative solutions rather than wrestling with backend intricacies.

4. **Seamless Integration:** The Telerik library harmonises effortlessly with Kendo UI, facilitating automatic data mapping without custom coding. Even in non-Kendo supported frontend stacks, the library ensures smooth data operations, and we can have custom mapping for seamless integration across diverse tech stacks.



## **Overview of Telerik Library** <a name="overview"></a>

- **Data Operations:** It offers robust data management capabilities, including built-in data binding, pagination, sorting, filtration, and grouping functionalities for calculating aggregate values like sums, avg, min and max, etc., and many more.

- **Data Validations:** This framework typically offers great support for data validation and enforcing business rules for their entity models to meet specific criteria and constraints on the backend.

- **Caching Mechanism:** It's backend tools often incorporate caching mechanisms to optimise performance by storing frequently accessed data in memory, reducing the need for repeated database queries and improving overall application responsiveness.

- **Data Access:** It provides libraries and tools to streamline data access on the backend. This includes ORM (Object-Relational Mapping) frameworks like Telerik Data Access, which allows developers to work with databases using strongly-typed.NET objects.

- **Data Entity Mapping:** It provides tools for data modelling, mapping, and defining entity models that represent their data structure in code, and this simplifies CRUD (Create, Read, Update, Delete) operations by providing a clear abstraction layer.

- **Security Mechanisms:** It places a strong emphasis on security, and its backend tools typically include features for implementing authentication and authorization mechanisms.



## **Supporting Technologies** <a name="supportingTechs"></a>

- **Frontend Technologies using Kendo**

1. AngularJs
2. ReactJs
3. VueJs
4. .Net Razor
5. .Net Blazor
6. .Net MAUI

- **Backend Technologies using Telerik**

1. .Net Core MVC​
2. .Net Core WebApi
3. Java (JSP, Servlets)
4. PHP
5. NodeJs



## **Comparison of Telerik with Other Libraries** <a name="comparisonTable"></a>

| Feature | Telerik | DevExpress | Syncfusion |  
|---------|---------|------------|------------|
| Data Formatting | Strong data handling with extensive support for Kendo UI | Strong data handling capabilities | Strong data handling capabilities | 
| Ease of Use |  User-friendly API | Slightly more complex API | User-friendly API |
| Performance | High performance, optimized for Kendo UI | High performance | High performance |
| Integration | Seamless integration with Kendo UI | Seamless with DevExtreme | Seamless with Syncfusion UI |
| Documentation | Comprehensive and Kendo-focused | Comprehensive but overwhelming | Comprehensive and detailed |
| Community Support | Large and active |  Large and active | Growing but smaller than others |
| Pricing | Competitive, multiple licensing options | Generally higher pricing | Competitive, with a free community edition |
| Trial Version | Available | Available | Available |



## **Why choose Telerik** <a name="whyChooseTelerik"></a>

1. **Optimized for Kendo UI:** Telerik backend library is specifically optimized for formatting data for Kendo UI, ensuring seamless and efficient integration.

2. **Ease of Use:** The API is user-friendly, making it easier for developers to implement and manage data operations.

3. **Performance:** The controls are optimised for performance, ensuring that applications run smoothly and efficiently.

4. **Customization:** The high level of customization allows developers to tailor the controls to meet specific needs, enhancing the flexibility of the tool.

5. **Integration:** Designed to work perfectly with Kendo UI, making it an ideal choice for projects using this UI library.

6. **Comprehensive Documentation:** Detailed documentation and a large community provide significant support, making problem-solving easier.

7. **Competitive Pricing:** Telerik offers a variety of licensing options that can fit different budgets, providing good value for the money.



## **Best Practices with Telerik** <a name="bestPractices"></a>

1. **Version Compatibility:** Always ensure that the versions of Telerik libraries you're using are compatible with the version of the backend project you're working on. Telerik frequently releases updates and patches, so keeping your libraries up-to-date is crucial for stability, security, and the improvement of existing features.

2. **Proper Setup & Configuration:** Follow the official documentation and guidelines provided by Telerik for setting up and configuring their libraries within your backend project. This includes adding necessary dependencies, configuring routes, and integrating client-side components with server-side code, etc.

3. **Optimised Data Handling:** Utilise Telerik's data components effectively to handle data operations efficiently. This includes using data grids, charts, and other components to display and manipulate data on the client side while ensuring smooth communication with the backend through APIs.

4. **Community Engagement & Support:** Engage with the Telerik community, forums, and support channels to seek assistance, share knowledge, and stay updated on best practices and the latest developments related to Telerik libraries and your backend project.


## **Telerik Setup with .Net Core** <a name="telerikSetup"></a>

We have many backend technologies that have Telerik support, but I'm going to explain the Telerik setup with .Net Core.

Here I'm attaching the official documentation link for [Telerik Setup with .Net Core] (https://docs.telerik.com/aspnet-core/getting-started/first-steps).

**Step 1:** Create a .Net Core project `KendoWebApi` with either WebApi or MVC.

**Step 2:** We can see the only package source as `nuget.org` under NuGet Package Manager.
![npm with nuget.org] (https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zj089amxc4an3jkwx6uk.png)

**Step 3**: Download the UI for the [ASP.NET Core free trial] (https://www.telerik.com/aspnet-core-ui) installer, then you need to create an account to access the installer file.
![asp .net core installer] (https://dev-to-uploads.s3.amazonaws.com/uploads/articles/psyftu4740f862fsbu5e.png)

**Step 4:** Upon launching the installer, users are prompted to select the desired products for installation based on their requirements. Here, I'm opting for `Telerik UI for ASP.NET Core` for my project needs.
![products on Telerik installer] (https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m4k7vxz167fy6q5kj0y2.png)

**Step 5:** After installing the product, go back to the project's NuGet Package Manager, and you can see `TelerikNuGetV3` added in Package Source. And install the `Telerik.DataSource.Trail` to get native support to access pagination, sorting, filtration, grouping, and many more.
![npm with TelerikNuGetV3] (https://dev-to-uploads.s3.amazonaws.com/uploads/articles/buis3h895cazhmqau65g.png)



## **Implementation with Telerik** <a name="telerikImplementation"></a>

In this demonstration, we will explore the implementation of key built-in features of Telerik, including pagination, sorting, filtration, and grouping, utilising remote data sourced from a mock API.

![project structure of KendoWebApi] (https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5vymitfszgy4789jlrtt.png)

**Step 1:** Open the KendoWebApi project and create `Employee.cs` under Models with the necessary fields to get the data from a mock API and `DataEnvelope<T>` to return the generic data.

```
using Telerik.DataSource;

namespace KendoWebApi.Models
{
    public class Employee
    {
        public int Id { get; set; }
        public string FullName { get; set; }
        public string Email { get; set; }
        public string Gender { get; set; }
        public DateTime DateOfJoining { get; set; }
        public int Experience { get; set; }
        public string Country { get; set; }
    }

    public class DataEnvelope<T>
    {
        public List<AggregateFunctionsGroup> GroupedData { get; set; }
        public List<T> CurrentPageData { get; set; }
        public int TotalItemCount { get; set; }

        public static implicit operator DataEnvelope<T>(DataEnvelope<Employee> v)
        {
            throw new NotImplementedException();
        }
    }
}
```

**Step 2:** Create a `DataSourceService.cs` file to have our implementation needs for the controller. Here we will add the method `GetResponseFromHttpRequest` to fetch the data from the mock API using `IHttpClientFactory`.

```
using KendoWebApi.Models;
using Newtonsoft.Json;

namespace KendoWebApi.Services
{
    public class DataSourceService : IDataSourceService
    {
        private readonly IHttpClientFactory _httpClient;

        public DataSourceService(IHttpClientFactory httpClient)
        {
            _httpClient = httpClient;
        }

        public async Task<List<Employee>> GetResponseFromHttpRequest()
        {
            string apiUrl = "https://mocki.io/v1/eaee4f4e-2d0a-48d3-87d3-1d99190474bd";

            try
            {
                // Make a GET request
                var httpResponse = await _httpClient.CreateClient().GetAsync(apiUrl);

                // Check if the request was successful
                httpResponse.EnsureSuccessStatusCode();

                // Deserialise the response content into List of Employee
                var apiResponse = await httpResponse.Content.ReadAsStringAsync();
                var result = JsonConvert.DeserializeObject<List<Employee>>(apiResponse);

                return result;
            }
            catch (ApplicationException ex)
            {
                throw new ApplicationException($"Application Expection occurred - Message: {ex.Message}");
            }
            catch (Exception ex)
            {
                throw new Exception($"System Exception occurred - Message: {ex.Message}");
            }
        }
    }
}
```

**Step 3:** Then, we will add a method to the DataSourceService.cs named `GetResponseFromDataOperations`, leveraging the `ToDataSourceResultAsync`, this orchestrates the execution of various data operations, transforming the mock data into a queryable format using `AsQueryable`. If the requirement solely entails data manipulation for `pagination, sorting, and filtration`, the data is assigned to `CurrentPageData`. Alternatively, if `grouping functionality is necessary`, the data should be cast to `AggregateFunctionsGroup` and assigned to `GroupedData`.

```
public async Task<DataEnvelope<Employee>> GetResponseFromDataOperations(DataSourceRequest dataSourceRequest, List<Employee> employeeResponse)
        {
            try
            {
                DataEnvelope<Employee> dataToReturn;

                var processedData = await employeeResponse.AsQueryable().ToDataSourceResultAsync(dataSourceRequest);

                // If grouping is necessary, then cast to AggregateFunctionsGroup
                if (dataSourceRequest.Groups != null && dataSourceRequest.Groups.Any())
                {
                    dataToReturn = new DataEnvelope<Employee>
                    {
                        GroupedData = processedData.Data.Cast<AggregateFunctionsGroup>().ToList(),
                        TotalItemCount = processedData.Total
                    };
                }
                else
                {
                    dataToReturn = new DataEnvelope<Employee>
                    {
                        CurrentPageData = processedData.Data.Cast<Employee>().ToList(),
                        TotalItemCount = processedData.Total
                    };
                }

                return dataToReturn;
            }
            catch (ApplicationException ex)
            {
                throw new ApplicationException($"Application Expection occurred - Message: {ex.Message}");
            }
            catch (Exception ex)
            {
                throw new Exception($"System Exception occurred - Message: {ex.Message}");
            }
        }
```

**Step 4:** Create an `IDataSourceService.cs` file to have an interface for the methods that we have in `DataSourceService`.

```
using KendoWebApi.Models;
using Telerik.DataSource;

namespace KendoWebApi.Services
{
    public interface IDataSourceService
    {
        Task<List<Employee>> GetResponseFromHttpRequest();
        Task<DataEnvelope<Employee>> GetResponseFromDataOperations(DataSourceRequest dataSourceRequest, List<Employee> employeesResponse);
    }
}
```

**Step 5:** Then we need to add the lifetime scope for the DataSourceService and it's interface to the 'Program.cs'.

```
builder.Services.AddScoped<IDataSourceService, DataSourceService>();
```

**Step 6:** Finally, we will create a KendoWebApiController.cs file to have our API call `GetResponseFromHttpRequest` to fetch the data from the mock API, pass the data to 'GetResponseFromDataOperations', and return the data based on the data operations mentioned in the `DataSourceRequest`.

```
using KendoWebApi.Models;
using KendoWebApi.Services;
using Microsoft.AspNetCore.Mvc;
using Telerik.DataSource;

namespace KendoWebApi.Controllers
{
    [Route("api/[controller]")]
    [Produces("application/json")]
    [ApiController]
    public class KendoWebApiController : ControllerBase
    {
        private readonly IDataSourceService _dataSourceService;

        public KendoWebApiController(IDataSourceService dataSourceService)
        {
            _dataSourceService = dataSourceService;
        }

        [HttpPost("GetFilteredEmployees")]
        [Produces("application/json")]
        public async Task<ActionResult<DataEnvelope<Employee>>> GetFilteredEmployees([FromBody] DataSourceRequest dataSourceRequest)
        {
            try
            {
                var apiResponse = await _dataSourceService.GetResponseFromHttpRequest();

                if (apiResponse == null || !apiResponse.Any())
                {
                    return NotFound("No response found from this request");
                }

                var result = await _dataSourceService.GetResponseFromDataOperations(dataSourceRequest, apiResponse);
                return Ok(result);                
            }
            catch (ApplicationException exception)
            {
                throw new ApplicationException($"method execution failed with Business Exception - Message: {exception.Message}");
            }
            catch (AggregateException exception)
            {
                throw new AggregateException($"method execution failed with Aggregate Exception - Message: {exception.Message}");
            }
            catch (Exception exception)
            {
                throw new Exception($"method execution failed with System Exception - Message: {exception.Message}");
            }
        }
    }   
}
```

Finally, the Telerik Library serves as a catalyst for efficiency and productivity in backend development.

Thank you for reading my tech blog! If you have questions or need assistance, don't hesitate to reach out. I look forward to hearing from you!

For more reference, here I'm adding the links to refer to this demo project.

Github Source: [Codebase on GitHub for Telerik with .Net Core] (https://github.com/SriCharan9595/Telerik-With-DotNet-Core.git)
Postman Collection's JSON: [DataSourceRequest Collection] (https://api.postman.com/collections/20283352-90ce6120-bc78-427b-8987-0bf9a04652f0?access_key=PMAT-01HQ34M3CC7ZB65P703AMSMY1E)
Telerik Setup Demo: [Demo Video to Setup Telerik with .Net Core] (https://drive.google.com/file/d/1pqEGI9DNujrvRMGb4rRdv-eaUk53FoeM/view?usp=sharing)