Error While Adding DataSource in Data Connections - c#

When I tried to add a connection it is showing the following error as shown in the attachment. “Unable to open the physical file. Access is Denied” .
When I searched about it, it suggest for adding the SQL Server’s account to the folder. Then, using the following query I found that the account is “LocalSystem”. When I tried to add “LocalSystem” to ACL of the folder, such an account is not available. How do we resolve it and add the connection to DBML?
Note: When I used DataReader with the database name in a C# program, it worked well.
Query Used:
declare #sqlser varchar(20)
EXEC master..xp_regread #rootkey='HKEY_LOCAL_MACHINE',
#key='SYSTEM\CurrentControlSet\Services\MSSQLSERVER',
#value_name='objectname', #value=#sqlser OUTPUT
SELECT convert(varchar(30),#sqlser)
Working C# Program:
SqlDataReader rdr = null;
SqlConnection con = null;
SqlCommand cmd = null;
try
{
// Open connection to the database
string ConnectionString = "server=D088DTRV;integrated security=true; database=BankAccount";
con = new SqlConnection(ConnectionString);
con.Open();
string CommandText = "SELECT * FROM Account";
cmd = new SqlCommand(CommandText);
cmd.Connection = con;
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
string test = rdr["AccountType"].ToString();
}
}

The problem was related to Data Connections.
In the advanced window, when I checked, it was trying for ./SQLExpress. I modified it with ".".
I restarted the machine. I also stopped the SQLExpress in the services.msc
Data Source=.;AttachDbFilename=C:\DevTEST\Databases\LibraryReservationSystem.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True

Related

Connect to MySQL remotely with C#

I have an assignment for IT at school, where I need to collect data for a database.
I made a C# app that allows user input, then stores it into mt database, problem being I can't seem to get it to connect.
I have a DNS: maliciouzzhd.ddns.net.
I have port 3306 open, and forwarded.
I just don't know what to do after this.
I am using XAMPP.
Here is my code:
string CommandText = $"INSERT INTO UserData (FirstName, LastName, BirthDay, BirthMonth, BirthYear, UserName, EMail, Password, Admin, IP) values ('{FirstNameInput.Text}', '{LastNameInput.Text}', {BirthDayInput.Text}, '{BirthMonthInput.Text}', {BirthYearInput.Text}, '{UserNameInput.Text}', '{EMailInput.Text}', '{PasswordInput1.Text}', 0, '{IPTextBox.Text}')";
string ConnectionString = "server=maliciouzzhd.ddns.net;database=***********;uid=***********;pwd=**************;";
using (var mysqlconnection = new MySqlConnection(ConnectionString))
{
mysqlconnection.Open();
using (MySqlCommand cmd = mysqlconnection.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = 300;
cmd.CommandText = CommandText;
object objValue = cmd.ExecuteScalar();
}
mysqlconnection.Close();
}
If anyone knows what I can do to get it to connect, that would be great.
Thanks
EDIT: Forgot to mention that this works on localhost, when I change Server=maliciouzzhd.ddns.net to Server=10.0.0.1 or Server=127.0.0.1, but I need it to be remote.
First of a add the mysql library.
Project->Add Reference->Browse the dll file.
then import the class by using
using MySql.Data.MySqlClient;
MySql Connection code :
MySqlConnection conn;
conn = new MySqlConnection("SERVER=server_name;DATABASE=database_name;UID=database_username;PASSWORD=database_password");
to open connection
conn.Open();
to close connection
conn.Close();

SQL Exception in Windows CE device

I'm working on Windows CE application, I was trying to connect to server database from the device and fetch some information from db on button click, below is the code I tried,
SqlConnection conn = new SqlConnection("Data Source=192.168.0.0;Initial Catalog=DashReport;Integrated Security=SSPI; User ID=SA;Password=Admin#123;");
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT STORE, YEAR,DATE FROM TOPSALES WHERE MONTH = " + txtcode.Text + ";";
// cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
conn.Open();
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count > 0)
{
gvDataGrid.DataSource = dt;
}
else
{
MessageBox.Show("No data found");
}
}
conn.Close();
but while running the application I'm getting a SqlException. It seems there is something wrong with the connection string. What is the right method to do it?
You cannot have both the integrated security and specify a specific user id and password at the same time. Since you have the Integrated Security=SSPI;, that will take precedence and your connection tries to connect with the currently logged in Windows user.
Most likely, from a Windows CE device, you want to use the specific User I
string connStr = "Data Source=192.168.0.0;Initial Catalog=DashReport;User ID=SA;Password=Admin#123;"
SqlConnection conn = new SqlConnection(connStr);
And another word of caution from long time SQL Server users, admins, and programmers: you should NEVER EVER use the built-in sa account! Just don't do it - use another account (possibly one you create specifically for this application).
Have you tried using the Server Explorer of Visual Studio, then connect to the database, get the Connection String via Properties Window, and use it as your connection string?
Just some kind of assurance that your connection to the database is the same as your code.

Connecting to SQL Server database using C#

I am using VS 2012 Express for web, I have created a website project and I am trying to connect integrated SQL Server with on the .aspx page of the website but I am getting an error
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
I have gone through various websites and tried to connect via web.config as well as c# but its does not seem to be possible.
What I have tried so far
web.config file:
<connectionStrings>
<add name="CnStr"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;"
providerName="System.Data.SqlClient"/>
</connectionStrings>
C# code:
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["CnStr"].ConnectionString;
SqlConnection conn = new SqlConnection("connectionString");
SqlCommand cmd = new SqlCommand("select * from user_login ",conn);
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
GridView1.DataSource = rdr;
GridView1.DataBind();
conn.Close();
The other way I have tried is:
SqlConnection conn = new SqlConnection("Data Source=(LocalDB)\v11.0;Database=Visual Studio 2012\\App_Data\\Database.mdf;Integrated Security=True");
SqlCommand cmd = new SqlCommand("select * from user_login ",conn);
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
GridView1.DataSource = rdr;
GridView1.DataBind();
conn.Close();
I have made database using following steps
right click on project
selecting SQL Server database to App_Data folder with name Database.mdf
Also If I try using add connections from data connections in database explorer, it's not accessing the database.mdf file and load only the templates e.g master, temp etc and not the folder in my App_Data folder and giving same error.
I have gone through many questions in stack overflow and tried using them as well
This is not code error, but a SQL configuration error. Follow steps in this excellent article for troubleshooting.
http://blog.sqlauthority.com/2009/05/21/sql-server-fix-error-provider-named-pipes-provider-error-40-could-not-open-a-connection-to-sql-server-microsoft-sql-server-error/
try this code instead!!!
string str = "Data Source=(LocalDB)\\v11.0;Database=Visual Studio 2012\\App_Data\\Database.mdf;Integrated Security=True";
using(SqlConnection conn = new SqlConnection(str));
{
conn.Open();
using(SqlCommand cmd = new SqlCommand("select * from user_login ",conn);
{
SqlDataReader rdr = cmd.ExecuteReader();
GridView1.DataSource = rdr;
GridView1.DataBind();
}
conn.Close();
}

c# localdb v11 not saving to file

I want to create a program for my school, handling marks and certificates.
To save the data I have to use a "local" network shared database-file, because we are using Citrix and there is no possibility to setup an seperate SQL-Server.
I tried it with localdb v11 with the following code:
string connectionString = #"Data Source=(LocalDB)\v11.0; AttachDbFilename=D:\_prog\TestNoten\TestNoten\bin\Debug\Database1.mdf; Integrated Security=True;Connect Timeout=3;";
SqlConnection connection = new SqlConnection(connectionString);
string sql = "INSERT INTO test(name) VALUES('lal')";
SqlCommand cmd = new SqlCommand(sql, connection);
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();
DataTable table = new DataTable();
SqlDataAdapter adp = new SqlDataAdapter("Select * from test", connection);
connection.Open();
adp.Fill(table);
MessageBox.Show(table.Rows[0][1].ToString());
The MessageBox says "lal", but when I restart the program with "lala" instead of "lal", it will show "lala" and not the expected "lal".
So when closing the program, the database won't be saved correctly. I also opened the file over VSs Data Connections, and the testing table is empty.
Is there something I missed?

Sql connetion doesn't open in windows service

I have a simple windows service and within this service I'm trying to connect to a sql server in a timer block (I tried to do that only once in onStart method -> same result).
For the moment I'm trying just to execute a select, using the following code:
using (SqlConnection sc = new SqlConnection())
{
var sqlConnection = new SqlConnection(_sqlConnectionString);
string commanda = "SELECT Moneda, SimbolMoneda FROM NomMoneda WHERE Moneda != '' AND SimbolMoneda != ''";
SqlCommand command = new SqlCommand(commanda, sqlConnection);
command.CommandType = System.Data.CommandType.Text;
IDataReader reader;
sc.ConnectionString = _sqlConnectionString;
sc.Open();
reader = command.ExecuteReader(CommandBehavior.CloseConnection);
}
I attached the service to debug, and I noticed that it didn't pass by this line of code sc.Open().
The service is not on the same machine as the sql server, but I have tried to install it under different users, LocalSystem, NetworkService, user within the same domain with the sql server, but with no result.
Any help would be appreciated.
It looks like you may have a logical error in this code. You are using sc for the SqlConnection, but when you create the command object you use sqlConnection, which is never actually opened.
This line is the problem:
SqlCommand command = new SqlCommand(commanda, sqlConnection);
Try the following instead:
SqlCommand command = new SqlCommand(commanda, sc);
EDIT at 10:22 following user comment
Just to confirm that you have made the change as indicated, I've re-jigged your code. Could you try the following:
using (SqlConnection sc = new SqlConnection())
{
sc.ConnectionString = _sqlConnectionString;
sc.Open();
string commanda = "SELECT Moneda, SimbolMoneda FROM NomMoneda WHERE Moneda != '' AND SimbolMoneda != ''";
SqlCommand command = new SqlCommand(commanda, sc);
command.CommandType = System.Data.CommandType.Text;
IDataReader reader;
reader = command.ExecuteReader();
}
I would expect that whatever the issue is it would be easier to figure out if you had a logging mechanism in place to catch and log unhandled exceptions. Due to the fact that Windows Services do not have a user interface you should implement logging from the beginning. Otherwise you will get to a point where the service terminates unexpectedly and what little information you gather from the system logs won't be enough to help you.
In short, add file logging and you'll probably figure out the issue immediately.
The problem was simple, but hard to detect. My connection string wasn't prefixed with the # char:
ex: _connectionString = #"Data Source =.......";

Categories