Connect a .NET Blazor App to Salesforce via ADO.NET

Salesforce is one of the most popular cloud-based customer relationship management (CRM) platforms that helps businesses manage customer relationships. It is often used as a data source in various web applications, particularly those built with Blazor.

Blazor is a front-end web framework based on HTML and C# that allows developers to build web applications quickly. The development process can be further improved by incorporating ADO.NET technologies for database-like interactions, especially with dotConnect for Salesforce by Devart.

In this article, we'll explore how to connect .NET Blazor applications to Salesforce using dotConnect for Salesforce.

Why dotConnect for Salesforce

dotConnect for Salesforce is an ADO.NET data provider that allows developers to access the Salesforce data directly when working on Salesforce-related apps. It is suitable for all Salesforce-related operations, offering easy connection, precise configuration, and perfect integration with Visual Studio along with support for ORM frameworks.

It is compatible with multiple .NET platforms, including Blazor, WPF, MAUI, Windows Forms, and more. Additionally, it is fully compliant with ADO.NET, allowing access to Salesforce without the need for specific client libraries.

Prerequisites

Before we begin, ensure that the following prerequisites are in place:

  • Visual Studio 2022: The IDE we'll use. If you do not have it installed, go to the official website to download and install it. We will be using the community version, so you can get it as well.
  • Blazor: An ASP.NET feature for building interactive web UIs with C# instead of JavaScript. It is .NET running in the browser on WebAssembly.
  • dotConnect for Salesforce: An ADO.NET provider with Entity Framework, NHibernate, and LinqConnect support.

Download and activate dotConnect for Salesforce

30-day free trial version

Download and install dotConnect for Salesforce directly on your machine, or install the Devart.Data.Salesforce NuGet package.

No license key is required, and you can start exploring the product immediately.

Full version

After purchasing the full version, go to your profile's Licenses page. Choose your product and click Details. Here, you'll find the license details and the Activation Key.

License details and the activation key

To activate a connection in your application, add the License Key to your connection string.

Get the security API token

To connect to Salesforce and access the data, you will need your valid credentials: the User ID, the password, and the security token.

To obtain that token, sign in to your Salesforce account, go to your profile, and select Settings.

Navigate to Reset My Security Token and request it. A new token will be sent to your email.

Reset the Salesforce Security API token

Install NuGet packages for a Blazor project

First of all, you need to create a Blazor project.

  • 1. Open your Visual Studio and click Create New Project.
  • 2. Select Blazor Web App and click Next.
  • 3. Give your project a name (we have created a demo project called SalesforceBlazor), check other details, and click Create.

Create a Blazor project for Salesforce and dotConnect

Now we need to install the NuGet package to use dotConnect for Salesforce in the process of creation applications with Visual Studio.

Сlick Tools, point to NuGet Package Manager, and click Manage NuGet Packages for Solution.

Select the NuGet Package Manager in Visual Studio

In the NuGet Package Manager page, click Browse, then search for Devart.Data.Salesforce, and select it once found. Click Install.

Install the NuGet package to use dotConnect for Salesforce in a Blazor project

Create a connection

To create the Salesforce connection instance using dotConnect within a .NET Blazor project, apply the below code.

Make sure to replace the placeholders with your valid Salesforce credentials: the host, the UserID, the password, and the security token.

public SalesforceService()
{
	_connectionString = "Authentication Type=UserNamePassword;" +
                    	"Host=https://develop.my.salesforce.com;" +
                    	"UserId=user@user.com;" +
                    	"Password=********;" +
                    	"Security Token=***********;" +
                    	"License Key=***********;";
}

public async Task TestConnectionAsync()
{
	try
	{
    	using (var connection = new SalesforceConnection(_connectionString))
    	{
        	await connection.OpenAsync();
        	return true;
    	}
	}
	catch
	{
    	return false;
	}
}
Note
If you're using a purchased dotConnect for a Salesforce license, include the license key in the code. If you're using the trial version, remove the License Key line.

To illustrate the work of our data provider dotConnect for Salesforce, we have created the class called SalesforceService.cs class. It will be used to set up the Salesforce connection, read Salesforce data, update, and delete it.

Create a class for your Blazor project

In this article, we provide examples of codes for you to use as references.

Read Salesforce data

To read and display data from Salesforce tables in a Blazor app, use the below code in the SalesforceService.cs class.

This code uses the following ADO.NET classes:

  • SalesforceConnection opens the connection to Salesforce.
  • SalesforceCommand executes the query to fetch the last 15 rows from the Lead table.
  • SalesforceDataReader reads the results row by row, and each row is processed into a LeadModel object.
public async Task> GetLeadDataAsync()
{
var leadData = new List();

try
{
   	using (var connection = new SalesforceConnection(_connectionString))
   	{
       	await connection.OpenAsync();

       	// Query to fetch the last 15 rows sorted by CreatedDate
       	string query = "SELECT Id, FirstName, LastName, Company, Title, Phone, Email, Status " +
             "FROM Lead " +
             "ORDER BY CreatedDate DESC " +
             "LIMIT 15";

       using (var command = new SalesforceCommand(query, connection))
        {
         using (var reader = await command.ExecuteReaderAsync())
          {
           while (await reader.ReadAsync())
            {
             leadData.Add(new LeadModel
               {
                Id = reader["Id"].ToString(),
                FullName = $"{reader["FirstName"]} {reader["LastName"]}",
                Company = reader["Company"].ToString(),
                Title = reader["Title"].ToString(),
                Phone = reader["Phone"].ToString(),
                Email = reader["Email"].ToString(),
                Status = reader["Status"].ToString()
              });
            }
           }
         }
        }
	}
	catch
	{
    	// Suppressed errors for cleaner output
	}

	return leadData;
}

The results will be displayed in a table with the below code:


<h4>Leads</h4>
<table>
                        <thead>
                        <tr>
                        <th>Full Name</th>
                        <th>Company</th>
                        <th>Title</th>
                        <th>Phone</th>
                        <th>Email</th>
                        <th>Status</th>
                        <th>Actions</th>
    	</tr>
	</thead>
                        <tbody>
    	@foreach (var lead in Leads)
    	{
                        <tr>
                        <td>@lead.FullName</td>
                        <td>@lead.Company</td>
                        <td>@lead.Title</td>
                        <td>@lead.Phone</td>
                        <td>@lead.Email</td>
                        <td>@lead.Status</td>
                        <td>
                        <a href="/salesforceleads?id=@lead.Id">Delete</a>
            	</td>
        	</tr>
    	}
	</tbody>
</table>

Click Run to view the data in your Blazor project.

View data from the Salesforce account in a Blazor app

Add data to Salesforce

To add data to Salesforce tables in a Blazor app, use the below code in the SalesforceService.cs class.

The ADO.NET classes used in this code are:

  • SalesforceConnection opens a connection to Salesforce.
  • SalesforceLoader handles the row insertion operation using methods like SetValue, NextRow, Open, and Close.
public async Task AddLeadAsync(string firstName, string lastName, string company, string title, string phone, string email)
{
	using (var connection = new SalesforceConnection(_connectionString))
	{
    	await connection.OpenAsync();

    	var loader = new SalesforceLoader
    	{
        	Connection = connection,
        	TableName = "Lead"
    	};

    	// Define the columns and open the loader
    	loader.CreateColumns();
    	loader.Open();

    	// Set values for the new lead
    	loader.SetValue("FirstName", firstName ?? string.Empty);
    	loader.SetValue("LastName", lastName ?? string.Empty);
    	loader.SetValue("Company", company ?? string.Empty);
    	loader.SetValue("Title", title ?? string.Empty);
    	loader.SetValue("Phone", phone ?? string.Empty);
    	loader.SetValue("Email", email ?? string.Empty);
    	loader.SetValue("Status", "Open - Not Contacted"); // Default status

    	// Commit the row
    	loader.NextRow();

    	// Close the loader
    	loader.Close();
	}
}

It produces the table:

<h3>Add New Lead</h3>

<form>
            <div>
            <label>First Name:</label>
            <input @bind="FirstName" placeholder="First Name" required=required />
	</div>
            <div>
            <label>Last Name:</label>
            <input @bind="LastName" placeholder="Last Name" required=required />
	</div>
            <div>
            <label>Company:</label>
            <input @bind="Company" placeholder="Company" required=required />
	</div>
            <div>
            <label>Title:</label>
            <input @bind="Title" placeholder="Title" />
	</div>
            <div>
            <label>Phone:</label>
            <input @bind="Phone" placeholder="Phone" />
	</div>
            <div>
            <label>Email:</label>
            <input @bind="Email" placeholder="Email" type="email" />
	</div>
            <button type="button" @onclick="SubmitLead">Add Lead</button>
</form>

@code {
	private string FirstName, LastName, Company, Title, Phone, Email;

	private async Task SubmitLead()
	{
    	await SalesforceService.AddLeadAsync(FirstName, LastName, Company, Title, Phone, Email);
    	NavigationManager.NavigateTo("/salesforceleads", true);
	}
}

Add data to Salesforce from the Blazor app

Delete Salesforce data

The below code uses the ADO.NET classes to delete records from Salesforce tables in your Blazor application.

  • SalesforceCommand prepares and executes the DELETE SQL command.
  • SalesforceParameter ensures secure parameterized queries.
public async Task DeleteLeadAsync(string id)
	{
    	try
    	{
        	using (var connection = new SalesforceConnection(_connectionString))
        	{
            	await connection.OpenAsync();

            	string query = "DELETE FROM Lead WHERE Id = @Id";
            	using (var command = new SalesforceCommand(query, connection))
            	{
                	command.Parameters.AddWithValue("Id", id);
                	await command.ExecuteNonQueryAsync();
            	}
        	}
        	return true;
    	}
    	catch
    	{
        	return false;
    	}
	}
}

To view the results, you will use the below code:

<a href="/salesforceleads?id=@lead.Id">Delete</a>

@code {
	protected override async Task OnInitializedAsync()
	{
    	// Extract query parameter
    	var uri = new Uri(NavigationManager.Uri);
    	var query = System.Web.HttpUtility.ParseQueryString(uri.Query);
    	var id = query.Get("id");

    	if (!string.IsNullOrEmpty(id))
    	{
        	await DeleteLead(id);
    	}

	}

	private async Task DeleteLead(string id)
	{
    	var success = await SalesforceService.DeleteLeadAsync(id);
    	if (success)
    	{
        	connectionStatus = $"Lead with ID {id} deleted successfully.";
        	Leads = await SalesforceService.GetLeadDataAsync();
    	}
    	else
    	{
        	connectionStatus = $"Failed to delete lead with ID {id}.";
    	}

    	// Remove query parameters after deletion
    	NavigationManager.NavigateTo("/salesforceleads", true);
	}
}

Delete data from the Salesforce account from within the Blazor app

Conclusion

The popularity of Salesforce has made it a data source for many commercial applications. To ensure a reliable connection to Salesforce and data management, developers need efficient and user-friendly solutions. dotConnect for Salesforce provides exactly that — a fast, hassle-free way to integrate Salesforce with applications.

When Blazor is your choice for application development, dotConnect for Salesforce provides a direct, secure, and efficient connection to Salesforce data from the Blazor application and easy data retrieval, updates, and deletions — without requiring additional client libraries or expertise in complex technologies.

You can experience the full capabilities of dotConnect for Salesforce with a 30-day free trial. Simply download and install it to start building applications powered by Salesforce, with a reliable and streamlined data connection.

dotConnect for Salesforce

Get an enhanced ORM-enabled data provider for Salesforce and develop .NET applications working with Salesforce data quickly and easily!