I'm a student doing an assignment which is an appointment system, I'm using Management Studio for the database, I detached it and linked Visual Studio with the .mdf file.
I can't find where the error is and never solved this type of error before.
Code:
DataClasses1DataContext db = new DataClasses1DataContext();
public frmAccountCreation()
{
InitializeComponent();
}
private void btnCreateAccount_Click(object sender, EventArgs e)
{
string email = txtEmail.ToString();
string fullname = txtFullname.ToString();
string username = txtUsername.ToString();
string password = txtPassword.ToString();
int userlevel;
string contactnumber =txtContactNumber.ToString();
if(ckbAdmin.Checked)
{
userlevel = 1;
}
else
{
userlevel = 0;
}
tblUserAccount account = new tblUserAccount
{
Username = username,
Passcode = password,
UserPrivelage = userlevel
};
tblVet vet = new tblVet
{
Email = email,
FullName = fullname,
ContactNumber = contactnumber
};
db.tblUserAccounts.InsertOnSubmit(account);
db.tblVets.InsertOnSubmit(vet);
db.SubmitChanges();//Error Is here
}
}
Error:
An unhandled exception of type 'System.Data.SqlClient.SqlException'
occurred in System.Data.Linq.dll
Additional information: 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
Looking at this line:
DataClasses1DataContext db = new DataClasses1DataContext("C:\\Users\\Luke\\Desktop\\OOP Assignment\\OOP_Database.mdf");
You are trying to open the MDF file directly. You cannot do that. You need a running SQL server instance (which can be on your development machine, like SQL Express), and you will need a connection string to connect to that server.
I solved the problem by uninstalling everything related to visual studio community 2015 and my antivirus avg after i reinstalled everything worked perfectly fine
It seems your SQL Server Service is not running.
In Windows, search for "Services" and there should be a Windows application with the same name.
In the application keep scrolling untill you find "SQL Server (MSSQLSERVER)" and make sure it's running.
Related
when i tried to run this program in visual studio 2010 its shows an error. Like this "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:Named pipes Provider,error:40-could not open a connection to SQL Server)"
public partial class tcregistration : Form
{
SqlConnection conn = new SqlConnection("Data Source=./SQLEXPRESS;AttachDbFilename=C:/Users/dce 3/documents/visual studio 2010/Projects/TC_Maker/TC_Maker/TC_REG.mdf;Integrated Security=True;User Instance=True");
public tcregistration()
{
InitializeComponent();
}
private void insert_Click(object sender, EventArgs e)
{
string gender = string.Empty;
if (rbmale.Checked)
{
gender = "M";
}
else if (rbfemale.Checked)
{
gender = "F";
}
string tcrecieved = string.Empty;
if (rbyes.Checked)
{
tcrecieved = "Y";
}
else if (rbno.Checked)
{
tcrecieved = "N";
}
try
{
if (conn.State == ConnectionState.Closed)
conn.Open();
SqlCommand cmd = new SqlCommand ("TCAddorUpdate",conn);
cmd.CommandType=CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#mode","Add");
cmd.Parameters.AddWithValue("#tcnumber",txttcno.Text.Trim());
cmd.Parameters.AddWithValue("#name",txtname.Text.Trim());
cmd.Parameters.AddWithValue("#dob",dtpdob);
cmd.Parameters.AddWithValue("#religion",txtrelig.Text.Trim());
cmd.Parameters.AddWithValue("#caste",txtcaste.Text.Trim());
cmd.Parameters.AddWithValue("#sex",gender);
cmd.Parameters.AddWithValue("#doa",dtpdoa);
cmd.Parameters.AddWithValue("#regno",txtregno.Text.Trim());
cmd.Parameters.AddWithValue("#dor",dtpdor);
cmd.Parameters.AddWithValue("#dept",txtdept.Text.Trim());
cmd.Parameters.AddWithValue("#sem", combosem);
cmd.Parameters.AddWithValue("#ifqulify",txtqualified.Text.Trim());
cmd.Parameters.AddWithValue("#conduct",txtconduct.Text.Trim());
cmd.Parameters.AddWithValue("#applieddate",dtpdoapp);
cmd.Parameters.AddWithValue("#ifrecieved",tcrecieved);
cmd.Parameters.AddWithValue("#receiveddate",dtpdor);
cmd.ExecuteNonQuery();
MessageBox.Show("Data Inserted Successfully");
}
catch(Exception ex)
{
MessageBox.Show(ex.Message,"Error Message");
}
finally
{
conn.Close();
}
}
}
}
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:Named pipes Provider,error:40-could not open a connection to SQL Server)
This is not a programming Problem, but a networking/connection string one.
Connection Strings are their own area of experetise, way outside the normal programmers knowledge. Luckily there is a page for it: https://www.connectionstrings.com/sql-server/
It turns out even when attaching, you have to supply a database name: "Why is the Database parameter needed? If the named database have already been attached, SQL Server does not reattach it. It uses the attached database as the default for the connection."
And as others mentioned, you got the wrong kind of slashes too.
Pretty off topic, but exception handling is a pet peeve of mine. And yours has some of the serioues mistakes. Like catching exception and only exposing the message. Those are 2 Cardinal sins. Thee are two article on the thematic I link often:
https://blogs.msdn.microsoft.com/ericlippert/2008/09/10/vexing-exceptions/
https://www.codeproject.com/Articles/9538/Exception-Handling-Best-Practices-in-NET
I am trying to write a program which interacts with my SQL Server database. I am programming in C# on Parallels on my Mac and SQL Server is running via Docker.
But I just can't connect. I am just getting the same error every time I try.
I have already tried to allow the remote access on SQL Server with:
EXEC sp_configure 'remote access', 1 ;
GO
RECONFIGURE ;
GO
but this does not solve my problem.
Here is my C# code:
main Class
Database database;
public Form1()
{
InitializeComponent();
database = new Database("localhost\\MSSQLSERVER", "user1", "topsecret", "master"); // \
}
private void connect_button_Click(object sender, EventArgs e)
{
database.Connect();
}
Database class:
class Database
{
SqlConnectionStringBuilder builder;
SqlConnection connection;
public Database(string source, string userid, string password, string initialcatalog){
this.builder = new SqlConnectionStringBuilder();
this.builder.DataSource = source;
this.builder.UserID = userid;
this.builder.Password = password;
this.builder.InitialCatalog = initialcatalog;
}
public void Connect()
{
try
{
// Connect to SQL
Console.WriteLine("Connecting to SQL Server ... ");
this.connection = new SqlConnection(this.builder.ConnectionString);
connection.Open();
Console.WriteLine("Connected");
}
catch(SqlException sqle)
{
Console.WriteLine(sqle.Message);
}
}
}
And I am always getting this error:
Network-related or instance-specific error when connecting to SQL Server. The server was not found or can not be accessed. Verify that the instance name is correct and that SQL Server allows remote connections. (provider: SQL Network Interfaces, error: 25 - connection string invalid)
The MSSQLSERVER is the instance name of the unnamed, default instance on your machine - you must not use this in the connection string.
Instead, try this line of code:
database = new Database("localhost", "user1", "topsecret", "master");
Just specify no explicit instance name at all - just localhost (or (local), or .) for the current machine - that's all you need!
It was Problem with Parallels, because Paralles can not access to localhost. So i had to define the IP from Parallels in Visual Studio like this:
database = new Database("10.211.55.2", "user1", "topsecret", "Time");
This question already has answers here:
Cannot Connect to Server - A network-related or instance-specific error
(54 answers)
Closed 4 years ago.
I'm trying to run this sample codes - https://marcominerva.wordpress.com/2017/10/25/using-sqlclient-apis-and-dapper-with-fall-creators-update-sdk/
I imported their database as well but not sure why it keep appearing System.Data.SqlClient.SqlException.
enter image description here
I already clean and build my solution and it doesn't work still
public sealed partial class MainPage : Page
{
// public string ConnectionString { get; set; } =
private string connectionString =#"Data Source=LAPTOP-IQQCR1C1;Initial Catalog = DatabaseDemo; Persist Security Info=True;User ID = xxxx Password=xxxxxxx";
//public string ConnectionString { get => connectionString; set => connectionString = value; }
public MainPage()
{
this.InitializeComponent();
}
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
var cities = await GetCitiesAsync(); //THIS LINE OF CODES GIVE THE SYSTEM.DATA.SQLCLIENT.SQLEXCEPTION
CitiesComboBox.ItemsSource = cities;
CitiesComboBox.SelectedIndex = 0;
base.OnNavigatedTo(e);
}
It still runs. But can't read the data for the dropdown and when searched, cannot read images from database.
Output:
sample
What I want:
sample
The SqlException with the error 40 means, that you can't connect to your SQL Server.
It seems that you have a wrong configuration on your server or the server is offline.
check if the service "SQL Server (INSTANCENAME)" is running on your machine
check in the Configuration Manager (SQL Server) if TCP/IP is enabled
check in the SQL Management Studio if the Server properties if remote connections are enabled.
if the SQL Server is not on your local machine, make sure the ports for communication are opened
Here you can find a detailed description on how to do the steps above.
EDIT: It only took a week but I eventually found out the issue, primarily due to pure luck and another error with a more specific fix.
The issue was with the connStr I had made, which for some reason on this machine gave me the error randomly of "System.ArgumentException: Keyword not supported: 'datasource'." during runtime. I then found out a fix for that was to rename the connStr as follows:
connStr = #"server = (server name); Initial Catalog = AutoTestDB; Integrated Security = true";
Should you have this error as I have, try that method of connection. END EDIT
I'm currently working on Automated Testing using Katalon Automated Testing, essentially Selenium for Chrome, and whenever I'm attempting to add the results of the test to our Test Results Database the SQL Exception "A network-related or instance-specific error occurred while establishing a connection to SQL Server. " keeps popping up. TCP/IP is open, as is firewall and remote connections, and I have the SQL-SMS open and running while I run the database with the SQL connection.
However it only happens whenever I'm using a certain machine to access the database which is stored within the machine itself, as it is with every other machine that I use and they all work perfectly fine. The only difference I can think of for this machine is that it uses SQL Express while all the others that I use have the full version of Microsoft SQL-SMS-17.
It's a genuine case of "It works on my machine", except with the caveat that it works on several others and even across different users as we are all working on this automated testing, this machine is the lone exception for this code not working, with the only difference being that it uses SQL Express which should be accounted for with the \\SQLExpress.
C# code with SQL connetions to edit the values into an already made table within the database.
public void testDBAdd(String testName, Boolean pass, String testComment)
{
SqlConnection con;
SqlDataAdapter daAutoTest;
DataSet dsAutoTestDB = new DataSet();
SqlCommandBuilder cmdBAutoTest;
String connStr, sqlAutoTest;
connStr = #"datasource = .\\sqlexpress; Initial Catalog = AutoTestDB; Integrated Security = true";
con = new SqlConnection(connStr);
sqlAutoTest = #"SELECT * FROM TestResults";
daAutoTest = new SqlDataAdapter(sqlAutoTest, connStr);
cmdBAutoTest = new SqlCommandBuilder(daAutoTest);
daAutoTest.FillSchema(dsAutoTestDB, SchemaType.Source, "AutoTest");
daAutoTest.Fill(dsAutoTestDB, "AutoTest");
foreach (DataRow drAutoTest in dsAutoTestDB.Tables["AutoTest"].Rows)
{
if (pass == true && drAutoTest["testName"].ToString() == testName)
{
drAutoTest.BeginEdit();
drAutoTest["testName"] = testName;
drAutoTest["testResult"] = 1;
drAutoTest["testComment"] = testComment;
drAutoTest.EndEdit();
daAutoTest.Update(dsAutoTestDB, "AutoTest");
}
else if (pass == false && drAutoTest["testName"].ToString() == testName)
{
drAutoTest.BeginEdit();
drAutoTest["testName"] = testName;
drAutoTest["testResult"] = 0;
drAutoTest["testComment"] = "Exception: " + testComment;
drAutoTest.EndEdit();
daAutoTest.Update(dsAutoTestDB, "AutoTest");
}
}
}
Code which runs the actual test and gathers if it has passed or failed due to the presence of certain elements, in this case is a certain page displayed when the user logs in and clicks a button.
public void settingTest<TestNumber>()
{
IWebDriver driver = new ChromeDriver();
ChromeOptions options = new ChromeOptions();
options.AddArguments("--start-maximized");
driver = new ChromeDriver(options);
String testName = "<Test Number>", testComment = "";
Boolean pass = false;
try
{
settingsLogin(driver);
settingsClick(driver);
Assert.IsTrue(driver.FindElement(ElementLocator).Displayed);
if (driver.FindElement(ElementLocator).Displayed == true)
{
testComment = "Pass";
pass = true;
testDBAdd(testName, pass, testComment);
}
}
catch (Exception ex)
{
testComment = "" + ex.TargetSite + "" + ex.Message;
testDBAdd(testName, pass, testComment);
}
finally
{
driver.Close();
}
}
Not sure, but I think your connection string has an extraneous backslash. You've prefaced the string with a "#" but then used "\\" in the Data Source. You might also try "(localdb)\SQLExpress" as the data source.
It only took a week but I eventually found out the issue, primarily due to pure luck and another error with a more specific fix. The issue was with the connStr I had made, which for some reason on this machine gave me the error randomly of "System.ArgumentException: Keyword not supported: 'datasource'." during runtime. I then found out a fix for that was to rename the connStr as follows:
connStr = #"server = (server name); Initial Catalog = AutoTestDB; Integrated Security = true";
Should you have this error as I have, try that method of connection. And thanks to the users who tried to help in both the comments of the post and in the answers section of this post.
I am using ActiveX in my web application in one page, it is working properly in my PC, i am passing the connection string from the web page that has the activex in it as following:
This is the javascript code in the page that passing the connection string to the activex:
<script language="javascript" type="text/javascript">
function Connect() {
var doc = document.forms[0];
var PrinterControl = document.applets('PrinterObject1');
PrinterControl.UserText = document.form1.hdnConString.value + ',' + document.form1.hdnCategory.value + ',' + document.form1.hdnLoginID.value + ',' + document.form1.hdnPassword.value + ',' + document.form1.hdnCategoryType.value;
}
</script>
.
.
.
.
and in the activeX code i receive the connection string and other values as following:
public String UserText
{
get
{
return conString;
}
set
{
conString = value;
string[] arrID = conString.Split(',');
conStr = Convert.ToString(arrID[0]);
category = Convert.ToString(arrID[1]);
loginID = Convert.ToString(arrID[2]);
password = Convert.ToString(arrID[3]);
categoryType = Convert.ToString(arrID[4]);
}
}
Every thing working properly in my pc, but when i install this application in customer's server, the page that using activex generating error although it is working in my pc and i tested it in other pcs in my company over network still working ok, the customer using Windows2008 with sql server 2012.
The following is the error message generating in the page that using activex, when the page trying to load activex:
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: Named Pipes Provider, error: 40 = could not open a connection to SQL Server)
Please help
Thank you