I'm using Xamarin to connect to SQL Server while making a mobile application. The application runs on iOS. I am using sql client to establish a connection with the server, but I'm running into weird errors and have exhausted most of my options.
Please do not warn me about security issues of direct connections. This is not the concern.
The error I'm receiving is this: provider: tcp provider, error: 40 - could not open a connection to sql server)
Here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using System.Data;
using System.Data.SqlClient;
namespace EmployeeSnapshot
{
// Learn more about making custom code visible in the Xamarin.Forms previewer
// by visiting https://aka.ms/xamarinforms-previewer
[DesignTimeVisible(false)]
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
void Button_Clicked(System.Object sender, System.EventArgs e)
{
var EmployeeID = UserInput.Text;
Console.WriteLine(EmployeeID);
string con = "Data Source ={Server}; Initial Catalog ={database}; Integrated Security = False; User ID ={username}; Password ={password}";
string matchingPerson;
using (SqlConnection connection = new SqlConnection(con))
{
string oString = "SELECT something FROM table WHERE employeeid = @employeeID";
SqlCommand command = new SqlCommand(oString, connection);
command.Parameters.AddWithValue("@employeeID", EmployeeID);
connection.Open();
Console.WriteLine("State: {0}", connection.State);
using (SqlDataReader reader = command.ExecuteReader())
{
matchingPerson = reader["name"].ToString();
}
command.Connection.Close();
}
Console.WriteLine(matchingPerson);
}
}
}
The code errors out at the Connection.open() line.
What I've tried:
- changed the connection string around, messed with integrated security, ensured the servers are up and running, etc.
- I am making this app on a MacBook. I have parallels, so I can use a virtual machine to go into windows. I decided to take advantage of this, and copied my connection string and pasted it into visual studio on the windows side. I performed a basic select statement and retrieved the data no problem, so the connection string doesn't seem to be the issue.
- I almost feel like it has something to do with Xamarin or with the fact I'm on a MacBook.