Windows Form Application and SQL Server - c#

UPDATE 2
I fixed the error by adding System.Configuration to the reference file. I had already added it to my class with using System.Configuration;
I found the answer here: The name 'ConfigurationManager' does not exist in the current context
Any further issues will be addressed in a new question.
Original(ish) Post
I have Microsoft SQL Server Management Studio. In the studio I created a database called Logbook that exists locally on my computer.
I have also created a user interface using a Windows forms application in VS C# Express. I would like to connect it to my logbook database in order to update, select, delete, and insert entries into the database through the UI.
However, I cannot figure out how connect the two. I have played around with the "Add new data source" wizard to no avail. I also cannot find anything helpful in the MSDN or other tutorials online.
UPDATE
I created a new database and project to work with until I figure out how to properly do this so I don't accidently break anything in my project.
The Schema is:
Student(sid: int, fname: char(10), lname: char(10), age:int, major:char(10))
Course(cid:int, desc:char(50), dept:char(10))
Enrolled(sid:int, cid:int, quarter:char(10), grade:char(10))
Here is the connection string generated by the "Add Data Source" wizard
<add name="boathouseLogConnectionString"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename="C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\DATA\boathouseLog.mdf";Integrated Security=True;Connect Timeout=30;User Instance=True"
providerName="System.Data.SqlClient" />
I have successfully gotten my database into the project. However, when I try running a stored procedure I get this error Argument Exception was unhandled. Format of the initialization string does not conform to specification starting at index 0.
The error occurs on line 2.
DataTable dt = new DataTable();
SqlConnection sqlConn = new SqlConnection(selectedConnectionString);
SqlCommand myCommand = new SqlCommand("proc_getMember", sqlConn);
myCommand.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(myCommand);
the selectedConnectionString variable is set to boathouseLogConnectionString

Initial Hints
If you want to see some examples for windows forms connecting to a database i can recommend the forms over data video series. Video 2 is about how to connect to a database.
In the app.config file you can put your connection data
<connectionStrings>
<add name="OrderManager.My.MySettings.OMSConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\OMS.mdf;Integrated Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
To be able to help you better i need more details. If you connect in management studio you can take a look at your connections properties. What are the values here and so on.
Update
There is another question with a similar problem. May be you are running user instances. Please add more details:
add information about your connection string (i am assuming your are using file attached connnections with a local data file)
where do you click on your database? Are you clicking on the mdf file or are you using management studio or visual studio

There is two major ways, you can use Entity Framework or ADO.NET foundation.
For simple tasks you can use ado.net features. at first you have to create SqlConnection Object and pass your ConnectionString to the constructor. Second you have to use SqlCommand Object and set your desired Command Text for the command. and at last you have to Execute the Command. there are several ways for execution :
ExecuteNonQuery For Updates, Deletes and Inserts commands
ExuecuteReader For Select commands, this methods returns a SqlDataReader which you can get your result from it.

Related

Connect to a SQL Server database without a set file path

I am attempting to connect to a local SQL Server database in C#.
I am currently using the following connection string:
connectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\User\source\repos\majorWork\majorWork\gameStats.mdf;Integrated Security=True";
However, I do not want to use a hardcoded file path, as I wish to be able to use the application across multiple computers, where the file path will be different. How should I go about doing this?
Best way is set this connection in Web.Config file.
<Database>
<ConnectionString name="connection">Server=servername; Initial Catalog=dbname; Persist Security Info=False; User ID=username; Password=password; MultipleActiveResultSets=False; Encrypt=True; TrustServerCertificate=False; Connection Timeout=30;;</ConnectionString>
</Database>
Then add Add System.Configuration as a reference.
in C# you can call this
string constring = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
After that you can create new connection instance by passing this to
SqlConnection con = new SqlConnection(constring)
If u install SQL server express using the default instance, then you can connect using . as your server name anyone can use it with default instance as well.
1.then in visual studio, click on solution explorer
2. Connect database, follow the instruction for SQL server
3. When it gets to server name use . to connect and choose your database name which you have created already in ms SQl, then test your connection
4. After it successful, u can now click on the database name showing under solution explorer,
5.after u click the database name, at the button right corner, there will be a connection string, copy it and use
This will be declared publicly or globally
Sqlconnection con = new sqlconnection("paste the connection string");
And to use
Sqlcommand cmd = new sqlcommand("insert into......",con);
Con.open ();
Cmd.executenonquery();
Con.close();

Azure function using entity framework but connect string not working

I have a azure V1 function using a project dll that handles entity framework.
First I set connect string like
metadata=res://*/Dev.csdl|res://*/Dev.ssdl|res://*/Dev.msl;
provider=System.Data.SqlClient;
provider connection string='
data source={IP};initial catalog={DBName};
persist security info=True;
user id={User};password={PW};
MultipleActiveResultSets=True;
App=EntityFramework'
and I got
Keyword not supported: 'metadata'.
then I changed my connect string to
data source={IP};initial catalog={DBName};persist security info=True;user id={User};password={PW};
and I got
The context is being used in Code First mode with code that was generated from an EDMX file for either Database First or Model First development. This will not work correctly. To fix this problem do not remove the line of code that throws this exception. If you wish to use Database First or Model First, then make sure that the Entity Framework connection string is included in the app.config or web.config of the start-up project. If you are creating your own DbConnection, then make sure that it is an EntityConnection and not some other type of DbConnection, and that you pass it to one of the base DbContext constructors that take a DbConnection. To learn more about Code First, Database First, and Model First see the Entity Framework documentation here: http://go.microsoft.com/fwlink/?LinkId=394715
And here's my code
DevEntities db = new DevEntities();
var lstAcAccount = db.AcAccounts.ToList();
return req.CreateResponse(HttpStatusCode.OK, lstAcAccount);
DevEntities is from other dll project that using the connect string above.
So, what should I do to make this work?
You shouldn't use generated connection string, now you have all metadata files included in your solution. Instead try use in connection string section of app.config:
"data source=localhost\sqlexpress; initial catalog=sample; integrated security=True;MultipleActiveResultSets=True;"
If it is Database first:
Open the .edmx[Diagram] -> right click -> "Update Model from database"
And see if the will appear the "Add", "Refresh" and "Delete" tabs.
If doesn't... probably your connection is broken and the dialog for VS creates a new connection string will appear instead.
Hope it helps.

asp.net c# connect to local Db vs2008

I'm making an ASP.net with c# webapp using VS 2008, and I added a new sql database item to my project. I added tables to the databse. In the database explorer the test connection works. I guess I have two questions. One:In the application, how does one connect to the database using a connection string? or what connection string should I use? Second: How do I add a username and password to the database?
Right now I'm using this connection string in the web.config file, but when I run the app it times out and says it can't make a connection. The error is on the conn.open line.
add name="ReportsConnectionString" connectionString="Data Source=(local); Initial Catalog=REPORTS;Integrated Security=True" providerName="System.Data.SqlClient"
I have this code in one of my page's codebehind.
string sqlquery = "SELECT * FROM reportitems";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ReportsConnectionString"].ConnectionString))
{
conn.Open();
using (SqlCommand comm = new SqlCommand(sqlquery, conn))
{
using (SqlDataAdapter adapter = new SqlDataAdapter(comm))
{
DataSet ds = new DataSet();
adapter.Fill(ds, "reportitems");
DataRowCollection dra = ds.Tables["reportitems"].Rows;
foreach (DataRow dr in dra)
{
string DRZ = dr[0].ToString();
//more stuff here
}
}
}
}
Usually SqlServer Express is reachable on your local PC using this syntax for the Data Source parameter yourpcname\SQLEXPRESS. To be sure start Management Studio and look at the Server Name request.
For the security part of your question, I suppose that you don't want the Integrated Security option (Windows User), but you want a SQLServer user. In this case you could use the User ID and Password parameters for the connection string:
Data Source=MYPC\SQLEXPRESS;Initial Catalog=REPORTS;User Id=MYNAME;Password=MYPASS;
However, this works only after you have added this user to the SQLServer.
You could use the interface of Management Studio app or you could execute a script like this
USE [master]
GO
CREATE LOGIN [MYNAME] WITH PASSWORD=N'MYPASS', DEFAULT_DATABASE=[master]
GO
USE [REPORTS]
GO
CREATE USER [MYNAME] FOR LOGIN [MYNAME]
GO
The Integrated Security=True part of the connectionstring means that the server will use the credentials of the app pool running the site, and you don't need to specify username or password. The app pool identiy will, however, need to have access to your database.
Visit http://www.connectionstrings.com/ for a good primer on various ways to set the connection string for various applications. That'll show you why (local) didn't work but .\SQLEXPRESS did and how to add username and password to it. Here's an example lifted from http://www.connectionstrings.com/sql-server-2008
Data Source=myServerAddress;Initial Catalog=myDataBase;User
Id=myUsername;Password=myPassword;
As others have said, you need a SqlExpress engine running as .mdf is not a flat file. It is a SQL server express database file and you need to connect to it.
But what have not said is that a Database in your App_Data folder needs to be attached to the SqlServer instance. This step is only done once in the first connection.
In http://www.connectionstrings.com/sql-server-2008 you will find an example in the "Attach a database file, located in the data directory, on connect to a local SQL Server Express instance" section that looks like this:
Server=.\SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf; Database=dbname;Trusted_Connection=Yes;
Also you can read this: http://msdn.microsoft.com/en-us/library/ms247257.aspx
I believe that you will need to run some scripts and stuff like that to create a user and assign permissions to this user in this database, and then change the connection string (once the database attached), so I don't see a point in having the database in the App_Data folder. I believe it should be better if since the beginning you create your database using the SqlServer tools and connect to it from your application.

How do I store users in my SQLEXPRESS database in C# MVC?

I am just learning MVC and I wanted to store my data in SQLEXPRESS instead of the MDF file that's provided.
I went online and learned that I was supposed to change Web.config, so I commented out and replaced the connection string like so:
<connectionStrings>
<!--<add name="ApplicationServices"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />-->
<add name="ApplicationServices"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=BuySellDB"/>
</connectionStrings>
I was hoping that System.Security.Membership would automatically create a new database and table to hold my information, but it doesn't -- instead, it just barfs because it can't find a database there. How do I configure it to create a new database and table if none exists?
Edit: I was watching tutorial videos on asp.net/mvc and I saw how DropCreateDatabaseIfModelChanges can be used to auto-create or re-create the necessary database and schema. I was hoping there was some way to include the aspnet_* tables in that....
You have to create the database by yourself using the command promt.
Start that command promt and execute "aspnet_regsql". A Wizard will start
and help you create the database.
Here is nice sample =>
http://www.ezineasp.net/post/How-to-Create-Aspnetdb.aspx
If you want to give the project away. Think about
create the database as i told
create a sql script from that
build the database using SqlClient in your application on first startup
You could check if the database exists in the global.asax "Application_Start" Method
protected void Application_Start(Object sender, EventArgs e)
{
//... check if your database already exists, if not DO IT ;)
}
In the scenario that you want - your database IS a valid sql express MDF file.
This is usually the best way to share the solution otherwise you are going to have to worry about database config, setting up the db, which server, etc. If you still want to do that you'll want to right click on your data connection in the server explorer in visual studio and publish the database and generate scripts if you have anything custom otherwise use aspnet_regsql.
However I still strongly suggest if you are sharing this application you keep it in the app_Data folder and let other users choose if they want it to run elsewhere. They can publish it as they see fit using the same method.

Unable to open the physical file Operating system error 32

Well this i did the below to get the error, don't have a clue why the database connection fails.
Create a new ASP.NET Website
Add a new *.mdf database to App_Data
Add some tables to it using Server Explorer in Visual Studio
Right click DataBase and Copy Connection string. Insert it into WebConfig File like below
<connectionStrings>
<add name="DB" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=C:\inetpub\wwwroot\gs\App_Data\db.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
Add some code to get the data from
selectStatement = "select * from users";
SqlDataAdapter da = new SqlDataAdapter(selectStatement,
ConfigurationManager.ConnectionStrings["DB"].ConnectionString);
DataTable dtUsers = new DataTable();
da.Fill(dtUsers);
GridView1.DataSource = dtUsers.DefaultView;
GridView1.DataBind();
and zoot you get the error
I have a sneaky suspicion it has to do with permissions. Give full control to your "Authenticated Users".
In case you are wondering how to do this --- I am on Windows 7 and the steps go like this:
Right-click on the MDF file and click properties.
Select the "Security" tab and select your "Authenticated Users" (or
something that looks right).
Click "Edit" and select the "Allow" check-box for "Full Control".
OK all the way out.
HTH
The top result from Google seems to address your question:
Just in case if anybody is still looking for solution to this error, this works for me:
1) Open the VStudio project for which
you need to connect to a SQL database
2)Separately, Go to
Start->Run->Services.msc
3) Look for
SQL Server (SQLEXPRESS) service and
Stop it
4) Start it again
5) Try
connecting your database now.
Looks like the reason it works has
something to do with User Instance
discussion that is going on in this
thread.
I was struggling with this error to and I found that the error was in the database instance that was online so I took it offline from SQLserver management studio,I've shared the steps followed and the solution HERE
In my case, I had the database in instance MSSQLSERVER while trying to attach it to SQLEXPRESS. Dropping from the first instance freed the file.
About error: Operating system error 32, Open error ...
First off all, give permission to mdf file. In my case NETWORK SERVICE account have FULL ACCESS on data.mdf.
Well, my workspace:
SSMS have attached data.mdf
In same time in VS2010 I have open solution with same database file: data.mdf, but can not make successfully connection.
Solution: in CONNECTION PROPERTIES on USER INSTANCE change TRUE to FALSE and refresh connection inside VS on this database.
Finaly, no more opening error and you have access on same database file in same time from SSMS and VS2010.
Connection string example:
DataSource=.\SQLEXPRESS;AttachDbFilename=D:\Contracts\App_Data\data.mdf;Integrated Security=True;User Instance=False
Regards
Dražen-ZG

Categories