Connect .NET MAUI App to Salesforce via ADO.NET

.NET MAUI (Multi-platform App UI) is a framework developed by Microsoft for building native mobile and desktop applications using C# and .NET. It allows developers to create apps that run on Android, iOS, Windows, and macOS. One of its biggest advantages is the ability to use a single codebase letting the developers share code, tests, and program logic across multiple platforms.

A key aspect of app development is ensuring a reliable connection to data sources and direct data management within the application. Data connectivity solutions, such as Devart's dotConnect products, help us resolve these challenges efficiently.

In this article, we'll explore how to connect a .NET MAUI application to a Salesforce data source using ADO.NET and perform read, insert, and delete operations.

Why dotConnect for Salesforce

dotConnect for Salesforce is a powerful data provider built with the ADO.NET technology. With its help, developers can access the Salesforce data directly and manage it efficiently when creating Salesforce-related applications.

With dotConnect for Salesforce, developers obtain a secure and reliable connection to the data source, flexible configuration options, full compliance with ADO.NET, and smooth integration with Visual Studio. These aspects are ideal for building MAUI-based applications.

Prerequisites

Before we begin, let's ensure all necessary 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 Edition, so you can get it as well.
  • .NET MAUI: The framework is installable with the .NET CLI tool and is available within the Visual Studio 2022 installer.
  • dotConnect for Salesforce: An ADO.NET provider with Entity Framework, NHibernate, and LinqConnect support.

Download and activate dotConnect for Salesforce

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 need the security token. Sign in to your Salesforce account, go to your profile > Settings. Navigate to Reset My Security Token and request it. A new token will be sent to your email. We'll use it for API access when we establish connection to Salesforce.

Reset the Salesforce Security API token

Install NuGet packages for the MAUI project

Open Visual Studio and choose to create a new project. Search for .NET MAUI App.

Create a new .NET MAUI project

Click Next, check all details, and click Create. For the demonstration purposes, we have created a project called SalesforceMaui.

Now we need to install the Devart.Data.Salesforce NuGet package.

  • 1. Open Visual Studio, click Tools > NuGet Package Manager > Manage NuGet Packages for Solution.
  • 2. In the NuGet Package Manager window, click Browse and search for Devart.Data.Salesforce. When you find it, click Install.
  • 3. Once the packages are installed, you can see them listed on the Installed tab.

Install the NuGet Package in Visual Studio

This way, we integrate the required components into the .NET MAUI project to work with Salesforce data.

Create a connection

This article includes a sample of the code that you can use to connect to Salesforce using dotConnect within a .NET MAUI project.

Replace the placeholders with your valid Salesforce credentials: Host, UserID, Password, and Security Token.

Note
For a paid dotConnect for Salesforce license, include the license key in the code. For the trial version, remove the License Key line.
private readonly string _connectionString;

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))
    	{
        	connection.Open();
        	return true;
    	}
	}
	catch
	{
    	return false;
	}
}

We are going to use our demo SalesforceMaui project to illustrate the READ, INSERT, and DELETE operations.

Read Salesforce data

To read and display data from your Salesforce account in an MAUI app, use the below code in the SalesforceService.cs class. In this code, the following ADO.NET classes are used:

  • SalesforceConnection manages the connection lifecycle.
  • SalesforceCommand represents the SQL query.
  • SalesforceDataReader reads query results row by row.
public async Task<List<LeadModel>> GetLeadDataAsync()
{
var leadData = new List<LeadModel>();

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

    string query = "SELECT Id, FirstName, LastName, Company, Title, Phone, Email, Status FROM Lead LIMIT 15";
     using (var command = new SalesforceCommand(query, connection))
     {
        using (var reader = command.ExecuteReader())
         {
            while (reader.Read())
            {
                leadData.Add(new LeadModel
                {
                    Id = reader["Id"].ToString(),
                    FullName = $"{reader["FirstName"]} {reader["LastName"]}",
                    DetailInfo = $"Company: {reader["Company"]}, Title: {reader["Title"]}, Phone: {reader["Phone"]}, Email: {reader["Email"]}, Status: {reader["Status"]}"
                    });
             }
         }
     }
    }
}
catch (Exception ex)
{
    Console.WriteLine($"Error retrieving data: {ex.Message}");
}

return leadData;
}

The results are displayed in the table:

<Label Text="Leads Table" FontAttributes="Bold" Margin="0,10,0,5" />
<CollectionView x:Name="DataCollectionView" ItemsSource="{Binding LeadData}" VerticalOptions="FillAndExpand">
<CollectionView.ItemTemplate>
    <DataTemplate>
     <Grid Padding="5" ColumnDefinitions="*,*,Auto">
         <!-- Full Name -->
         <Label Grid.Column="0" Text="{Binding FullName}" FontSize="16" />

         <!-- Detail Info -->
         <Label Grid.Column="1" Text="{Binding DetailInfo}" FontSize="12" TextColor="Gray" />

         <!-- Delete Button -->
         <Button Grid.Column="2" Text="Delete" TextColor="White" BackgroundColor="Red"
            Command="{Binding Path=BindingContext.DeleteCommand, Source={x:Reference DataCollectionView}}"
            CommandParameter="{Binding Id}" />
        </Grid>
    </DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>

Read Salesforce data in a .NET MAUI project

Add data to Salesforce

To add data to Salesforce tables from within the MAUI app, use the below code with the ADO.NET classes:

  • SalesforceConnection manages connection lifecycle.
  • SalesforceCommand prepares and executes the INSERT query.
  • SalesforceParameter ensures secure and parameterized queries.
public async Task<bool> AddLeadAsync(string firstName, string lastName, string company, string title, string phone, string email, string status)
{
	try
	{
    	using (var connection = new SalesforceConnection(_connectionString))
    	{
        	connection.Open();

        	string query = "INSERT INTO Lead (FirstName, LastName, Company, Title, Phone, Email, Status) VALUES (@FirstName, @LastName, @Company, @Title, @Phone, @Email, @Status)";
        	using (var command = new SalesforceCommand(query, connection))
        	{
            	command.Parameters.AddWithValue("FirstName", firstName ?? string.Empty);
            	command.Parameters.AddWithValue("LastName", lastName ?? string.Empty);
            	command.Parameters.AddWithValue("Company", company ?? string.Empty);
            	command.Parameters.AddWithValue("Title", title ?? string.Empty);
            	command.Parameters.AddWithValue("Phone", phone ?? string.Empty);
            	command.Parameters.AddWithValue("Email", email ?? string.Empty);
            	command.Parameters.AddWithValue("Status", status ?? string.Empty);

            	command.ExecuteNonQuery();
        	}
    	}
    	return true;
	}
	catch (Exception ex)
	{
    	Console.WriteLine($"Error adding lead: {ex.Message}");
    	return false;
	}
}

The table to display the results is:

<VerticalStackLayout Padding="10" Spacing="10">
	<Label Text="Add New Lead" FontAttributes="Bold" FontSize="20" HorizontalOptions="Center" />

	<Grid ColumnDefinitions="*,3*" RowDefinitions="Auto,Auto,Auto,Auto,Auto,Auto,Auto" RowSpacing="15" Padding="0,10,0,10">
    	<!-- First Name -->
    	<Label Text="First Name:" VerticalTextAlignment="Center" />
    	<Entry x:Name="FirstNameEntry" Placeholder="First Name" Grid.Column="1" />

    	<!-- Last Name -->
    	<Label Text="Last Name:" VerticalTextAlignment="Center" Grid.Row="1" />
    	<Entry x:Name="LastNameEntry" Placeholder="Last Name" Grid.Row="1" Grid.Column="1" />

    	<!-- Company -->
    	<Label Text="Company:" VerticalTextAlignment="Center" Grid.Row="2" />
    	<Entry x:Name="CompanyEntry" Placeholder="Company" Grid.Row="2" Grid.Column="1" />

    	<!-- Title -->
    	<Label Text="Title:" VerticalTextAlignment="Center" Grid.Row="3" />
    	<Entry x:Name="TitleEntry" Placeholder="Title" Grid.Row="3" Grid.Column="1" />

    	<!-- Phone -->
    	<Label Text="Phone:" VerticalTextAlignment="Center" Grid.Row="4" />
    	<Entry x:Name="PhoneEntry" Placeholder="Phone" Grid.Row="4" Grid.Column="1" />

    	<!-- Email -->
    	<Label Text="Email:" VerticalTextAlignment="Center" Grid.Row="5" />
    	<Entry x:Name="EmailEntry" Placeholder="Email" Grid.Row="5" Grid.Column="1" />

    	<!-- Status -->
    	<Label Text="Status:" VerticalTextAlignment="Center" Grid.Row="6" />
    	<Entry x:Name="StatusEntry" Placeholder="Status" Grid.Row="6" Grid.Column="1" />
	</Grid>
</VerticalStackLayout>

<Button Text="Add Lead" Clicked="OnAddLeadClicked" />

Add new records to Salesforce from the .NET MAUI project

Delete Salesforce records

To delete records from the Salesforce tables, use the below code with the following ADO.NET classes:

  • SalesforceConnection manages the database connection lifecycle.
  • SalesforceCommand represents the SQL query and executes it.
  • SalesforceParameter binds parameters securely to the SQL query.
public async Task<bool> DeleteLeadAsync(string id)
{
    try
    {
        using (var connection = new SalesforceConnection(_connectionString))
        {
            connection.Open();

            string query = "DELETE FROM Lead WHERE Id = @Id";
            using (var command = new SalesforceCommand(query, connection))
            {
            command.Parameters.AddWithValue("Id", id);

            command.ExecuteNonQuery();
            }
        }
        return true;
    }
    catch (Exception ex)
    {
    Console.WriteLine($"Error deleting lead: {ex.Message}");
    return false;
    }
}
}

The Delete button in the Leads table that we presented earlier in this article is created with the below code:

<Button Grid.Column="2" Text="Delete" TextColor="White" BackgroundColor="Red" Command="{Binding Path=BindingContext.DeleteCommand, Source={x:Reference DataCollectionView}}" CommandParameter="{Binding Id}" />

Conclusion

.NET MAUI is a popular framework for cross-platform application development. In this process it is crucial to ensure efficient connectivity to data sources. dotConnect products provide that required secure, direct connection and allow direct data manipulation from within the application.

If your MAUI app relies on Salesforce, dotConnect for Salesforce grants a stable connection and enables you to manage Salesforce tables without additional clients or learning new technologies.

You can test dotConnect for Salesforce under real workloads with a 30-day free trial. Download, install, and start building your applications!

dotConnect for Salesforce

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