How to resolve "Ensure SQL Server Browser is running" , when it is - c#

I'm creating an Android App using Xamarin Forms in Visual Studio 2017. Since this includes storing data, I'm using SQL Server 2017 to accomplish this. When I run my code, and debug the line "conn.Open()", I get an error stating that I should ensure that SQL Server Browser is running. However, when I check SQL Configuration Manager, it is running.
Some things I've tried
- Making sure that the connection string in SQL Server matches the connection string in my code
- I've tried changing what the SQL Server Browser is logged into (Whether it's local system, local service, etc.)
- I've tried several different methods of implementing an insert statement in my code
public class ConnectionManager
{
public static SqlConnection NewCon;
public static string ConStr = #"Data Source=DESKTOP-V83O00S\SQLEXPRESS;Initial Catalog=ResourceSharing;Integrated Security=True";
public static SqlConnection GetConnection()
{
NewCon = new SqlConnection(ConStr);
return NewCon;
}
}
private void Button_Clicked(object sender, EventArgs e)
{
SqlConnection conn;
conn = ConnectionManager.GetConnection();
conn.Open();
string cmdString = "INSERT into Login values(#username,#password)";
SqlCommand sqlCommand = new SqlCommand(cmdString, conn);
sqlCommand.CommandType = CommandType.Text;
sqlCommand.Parameters.Add("#username", SqlDbType.Text).Value = "josh123";
sqlCommand.Parameters.Add("#password", SqlDbType.Text).Value = "pwd321";
sqlCommand.ExecuteNonQuery();
conn.Close();
}
Expected Result: 1 record in my Login table
Actual Result: Error asking me to ensure SQL Server Browser is running.
Any feedback or suggestions on either how to fix this problem or what alternative route I can take that would work?

Related

Connection String Not Working- Not Allowing Connection to Database made in VS (C# Visual Studio)

I am currently working on building an attendance tracker that will take the user's input data and add it to a database table. I'm running into an issue where my connection string will not connect to the database? I've copied it directly as is, and even tried a few different tutorials with alternative ways with no success. This is for an assignment however, our SQL portion was quite small and I'm not sure where to go from here. Please let me know if something in my code needs revisited.
When I run the code I get the "unable to connect" exception I created below. I need it to run and add the user input to the table.
I have also noticed that my database connection often disconnects unless I refresh, is this common?
namespace AttendanceTracker
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void signInButton_Click(object sender, EventArgs e)
{
string connectionString = null;
connectionString = #"Data Source=(LocalDB)\MSSQLLocalDB; AttachDbFilename = C:\Users\soupy\Desktop\AttendanceTracker\AttendanceTrackerDatabase.mdf; Integrated Security = SSPI";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = ("INSERT into AttendanceTrackerDatabase VALUES (#studentName,#studentID,#Date,#class)");
cmd.Parameters.AddWithValue("#Student_Name", nameTextBox.Text);
cmd.Parameters.AddWithValue("#Student_ID", studentIDTextBox.Text);
cmd.Parameters.AddWithValue("#Class", classDropDown.Text);
cmd.Parameters.AddWithValue("#Date", attendanceDate.Value);
try
{
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Your sign in has been recorded successfully!");
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Unable to open attendance tracker for updating.");
}
}
When using Parameter objects, you should ensure that the variable names are consistent.
Please modify your code as follows
cmd.CommandText = ("INSERT into AttendanceTrackerDatabase VALUES (#studentName,#studentID,#Date,#class)");
cmd.Parameters.AddWithValue("#studentName", nameTextBox.Text); // Modified to "studentName"
cmd.Parameters.AddWithValue("#studentID", studentIDTextBox.Text); // Modified to "studentID"
cmd.Parameters.AddWithValue("#Date", attendanceDate.Value);
cmd.Parameters.AddWithValue("#class", classDropDown.Text); // Modified to "class"

How do I connect to a Local MSSQL Database

EDIT: I've just tested it in ASP.NET and it works perfectly fine. So no issue with the connection string or anything. Guess Unity doesn't like this method? Maybe there's some more DLL's I need to copy? Any ideas?
So I'm making a game in Unity and I'm trying to use the System.Data.SqlClient library to connect to some stored procedures I have made for things such as registering a user.
I have copied the System.Data.dll from "C:\Program Files\Unity\Editor\Data\Mono\lib\mono\unity" and that has all worked fine.
I'm currently using this connection string, which works fine on an ASP.NET application but just using a different mdf:
private string connectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='C:\Users\uppy8\Desktop\Computer Science Project\Mining Game\Assets\MineRace.mdf';Integrated Security = True";
The problem occurs when running this code:
using System.Data.SqlClient;
using System.IO;
public void Login()
{
Crypto crypto = new Crypto();
using (SqlConnection conn = new SqlConnection(connectionString))
{
try
{
conn.Open();
} catch (Exception e)
{
Debug.Log(e);
}
SqlCommand command = new SqlCommand("USERS_LOGIN_USER", conn);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#Username", usernameInputField.text));
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
if (crypto.EncryptString(passwordInputField.text) == reader["password"].ToString())
{
UserAccountManager.instance.userInfo = FetchUserInfo((int)reader["id"]);
}
}
}
}
The problem happens on the line "conn.Open()", where Unity gives me the error:
System.Net.Sockets.SocketException: No such host is known.
Furthermore, without the try catch, the error occurs where I create a new SqlDataReader, where I get this issue:
InvalidOperationException: ExecuteReader requires an open connection to continue. This connection is closed.
I understand that this is an issue with the connection, in that it's not running or the connection isn't working properly, however I can't seem to find a solution and I have a sneaky suspicion that it's something to do with Unity not supporting this library.
Some more clarification just before I end off:
The user enters their credentials into the "usernameInputField" and "passwordInputField"
The user presses Login, which runs the "Login" method shown above
The error occurs.
If any more information is required please leave a comment.
Thanks!
What is the scope of connectionString? Do you need to pass the connectionString to the Login() function?
public void Login(string connectionString)
I am a DBA, not a .Net developer, so forgive me if my questions are too basic or if my .Net syntax is wrong.
You can try this
string connectionString = #"Data Source = (localdb)\MSSQLLocalDB; Initial Catalog ='C:\USERS\uppy8\Desktop\Computer Science Project\Mining Game\Assets\MineRace.mdf'; Integrated Security = True; Connect Timeout = 30; Encrypt = False; TrustServerCertificate = True; ApplicationIntent = ReadWrite; MultiSubnetFailover = False"
SqlConnection con = new SqlConnection();
if (con.State==ConnectionState.Open)
{
con.Close();
con.ConnectionString = connectionString;
con.Open();
cmd.Connection = con;
}
else
{
con.ConnectionString = connectionString;
con.Open();
cmd.Connection = con;
}

Open database into application c#

I have added a SQL Server .mdf database file to my C# application, but when I try to connect with this code, the program causes a connection error.
CODE:
DataSet data;
string con = "Data Source=dbinterno.mdf;";
string queryString = "Select * FROM Dati";
try
{
using (SqlConnection connection = new SqlConnection(con))
{
connection.Open();
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand command = new SqlCommand(queryString, connection);
command.ExecuteNonQuery();
data = new DataSet();
adapter.Fill(data);
MessageBox.Show(data.ToString());
connection.Close();
}
}
catch
{
MessageBox.Show("\n Problemi di connessione al database");
}
The error is:
ERROR IMAGE
Here are a couple observations:
Your connection string will need to be modified. Try using
string con = "Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;";
using Windows Authentication or this:
string con = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;
Password=myPassword;"; using standard security, Source: connectionstrings.com. This should be managed some other way than in code as well. Desktop applications can be de-compiled, and if the password changes, you would need a rebuild. In a ASP.NET application, Microsoft advises to use a web.config file or in the windows registry using a custom subkey.
You will want to use ExecuteReader() for a SELECT statement as ExecuteNonQuery() will not return a result set. See this answer that describes the differences in the types of SQL Server methods
you don't need connection.Close();, the using statement will handle that.

Getting Error while connecting to DB using c#

Is there anything wrong with this code? Please help me out.
protected void Button_Click(object sender, EventArgs e)
{
string cs = "Data Source=SFSIND0402;Initial Catalog=TestDB;Integrated Security=SSPI;Provider=Microsoft.ACE.OLEDB.12.0";
OleDbConnection conn = new OleDbConnection(cs);
conn.Open();
OleDbCommand insert = conn.CreateCommand();
insert.CommandText="insert into Employee(ID, Name, Sex, Salary) values('003','Vedpathi','M',25000)";
insert.Connection = conn;
insert.ExecuteNonQuery();
conn.Close();
}
I am getting the following error:
Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done
(on line 22:conn.Open();)
When connecting to an MS SQL database, use the MS SQL providers:
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
var cmd = new SqlCommand(commandText, connection);
cmd.ExecuteNonQuery();
}
In addition to the solution Luaan mentioned, you should store your connection string in the config file of the app and also encrypt it.
Even if you use SSL encryption when communicating with the DB, an ill-indended person can extract the string variables, if he / she runs the application on his / her machine.

ASP .net C# SqlConnection Error

I have a window hosting in 1and1.com. I try to connect the database with following code, but I get the error message. You can view error message here http://www.s499993321.onlinehome.us/Default.aspx
Does any one know happen? How to connect the database?
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection cn = new SqlConnection("Server=localhost; Database=db500148144; User Id=dbo500148144; Password=12345abc"))
{
cn.Open();
SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM people", cn);
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
rdr.Read();
Response.Write(rdr[0].ToString());
}
// Response.Write("How");
}
If SQL server is on the same machine use
SqlConnection cn = new SqlConnection(#"Server=.\MSSQLSERVER2012; Database=db500148144; User Id=dbo500148144; Password=12345abc")
MSSQLSERVER2012 is the instance name. One way to find out the name is by opening services.msc and checking the name of the sql server service running on your machine. for me it was
"SQL server(MSSQLSERVER2012)"
There is issue in your web.config file, Remove CustomeErrro tag from web.config , and try.

Categories

Resources