Getting data from a table to ASP.NET web application - c#

I'm using Visual Studio 2010 to build an ASP.NET web application, I'm working on dynamically populating (part) of the site map from information in a database. Right now I just have a dummy table in my App_Data folder, called DrugTest.mdf. The table is just called DrugTest1, which only has one field, DrugName. Where I'm hitting a wall is actually getting the data out of that table. Part of what I'm confused about is the connection string. I've looked at a lot of different information about connection strings, most notably http://www.connectionstrings.com/ but I'm a little confused as to how to actually apply said information to this project.
EDIT: I'm using SQL Server 2008 RC.
For example: Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
Password and User Id are pretty self-explanatory, but as far as I know I didn't get either one of those, I just added a table to the App_Data folder and filled it with dummy data. ServerAddress is a little confusing, because this information isn't really stored on a server, it's just stored locally. And I'm honestly not sure what Initial Catalog means.
Here's the code to populate the sub-tree. You'll notice the connection string is left blank.
string connString = ""; // get the connection string
string commandString = "SELECT drugName FROM DrugTable1";
SqlConnection connection = new SqlConnection(connString); // connect to db
SqlCommand command = new SqlCommand(commandString, connection); // set up the command
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataSet drugs = new DataSet();
adapter.Fill(drugs);
foreach (DataRow row in drugs.Tables[0].Rows)
{
string drugName = row["Name"] + "";
SiteMapNode node = new SiteMapNode(this, drugName,
"~/PlaceHolderUrl?path=" + drugName,
drugName);
AddNode(node, root);
}
Furthermore, I've got a nagging suspicion that I'm not going about this the right way. I think this will be the proper implementation once the database is up and running, but for right now I just want to get it working so it's ready to go - just slap in the proper connection string and table/field names.
So, finally, my question(s): How would I go about connecting to this local table? What format should my connection string be? I noticed there's a lot of them. Is there a better way to do this/am I doing this wrong?

Another way of getting the right connection string check this out in the ServerExplorer window
On the Menu click on View->Server Explorer
In the Server Explorer window locate DrugTest.mdf
Right click the file and select Properties
You can see the right connection string in the properties
Copy the connection string and use
Note: that the file location was hard-coded. You might need to use |DataDirectory| later

Try replacing the Initial Catalog portion of your connection string with AttachDbFilename=|DataDirectory|DrugTest.mdf.
Also, if you're using SQL Server Express, you might need to include the instance in the Data Source, so might try Data Source=mySeverAddress\SQLExpress, where SQLExpress is the instance name.
BTW, at the http://www.connectionstrings.com site, you can find this information in the SQL Server 2008 page if you scroll down a bit to the section titled "Attach a database file, located in the data directory, on connect to a local SQL Server Express instance."

Related

"C:\USERS\ME\DATABASE.MDF" requested by the login. The login failed. Login failed for user 'me-PC\me'

Basically every time I run my game MS SQL database crashes and returns this error message.
Cannot open database "C:\USERS\ME\SOURCE\REPOS\A GIRL CALLED LORRY\A GIRL CALLED LORRY\DATABASE.MDF" requested by the login. The login failed.
Login failed for user 'me-PC\me'.
I did not change any of the SQL or C# code in my project to cause this error. All I did was simply modify a table within my database by adding a new column of type string.
I've tried using SMSS to open my DataBase.mdf file within my project to see if my user has privileges to access it, however I was unable to open my DataBase.mdf file because it wouldn't even show up within SMSS. So I'm not sure how I can get privileges to access my database again. I also tried removing all the changes I've added to the DB which caused the error in the first place however the error still persists.
As I've said, the error was caused by modifying a table within my database, but there is a small piece of code where the game crashes as soon as I attempt to open the database to remove data:
//this method is used to initialize the database.
public static void createSave() {
//database stuff:
con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\me\\source\\repos\\A Girl Called Lorry\\A Girl Called Lorry\\Database.mdf;Integrated Security=True");
adp = new SqlDataAdapter();
ds = new DataSet();
Console.WriteLine("we are in!");
//the below code only initializes if isNewGame is set to true.
removeAllFromInventory();
rewriteCurrentObjects();
loadDefaultNpcs();
}
//removeAllFromInventory is where it crashes.
//removes all items from inventory:
public static void removeAllFromInventory() { //this only applies if
//isNewGame is set to true since we want to wipe the inventory in a new game
if (!isNewGame) return;
con.Open(); //here is where it crashes.
adp.SelectCommand = new SqlCommand("DELETE FROM curInventoryItems", con);
adp.SelectCommand.ExecuteNonQuery();
con.Close();
}
However I was unable to open my DataBase.mdf file because it wouldn't even show up within SMSS. So I'm not sure how I can get privileges to access my database again. I also tried removing all the changes I've added to the DB which caused the error in the first place however the error still persists.
There is confusing part in your question, when you unable to connect .MDF how could you remove changes that was added into DB.
However, following steps might be helpful to get your database back to normal:
Verify the account (me-PC\me) has permissions on C:\USERS\ME\SOURCE\REPOS\A GIRL CALLED LORRY\A GIRL CALLED LORRY\DATABASE.MDF
If doesn't work after the permissions, you can troubleshoot the SQL Localdb connections using these steps
Install SQL Express (as it's difficult to manage with LocalDB database engine), and attach Database.mdf into SQL Express engine. You can do this using following command via SSMS
Once your database ready at SQL Express, you can change your connection string to "Data Source=Localhost\\SQLEXPRESS;Initial Catalog=YourNewDBName;Integrated Security=True"
In case issue even with SQL Express, you may follow these steps..
--- You need to move "Database.mdf" and ".ldf" files into "C"\SQLData" folder before executing the command
CREATE DATABASE YourDatabase
ON (FILENAME = 'C:\SQLData\Database.mdf'),
(FILENAME = 'C:\SQLData\Database_log.ldf')
FOR ATTACH;

Does instantiating a DataSet object automatically create a connection to a SQL service-based database for CRUD operations?

Here is everything that I did:
In a visual studio 2013 C# project, I created a service database (.mdf file). Note: I changed the name from Database1.mdf to fghLocalDB.mdf.
I opened this database in the server explorer.
I created 2 tables called Country and CarbonDioxide using the table designer.
I added an entry to the Country table as shown by the Data Table of the Country table.
I did the following to create a DataSet my application can use. I created a Data Source by clicking on the "Project" option on the top menu bar and clicking on the "Add New Data Source ..." option from the drop down.
This is what my project files looked like at this point.
I wrote the following code in the main method thinking that this would be all I need to write to the database.
// Create a connection to the DataSet and TableAdapters that will communicate with our
// local database to handle CRUD operations.
fghLocalDBDataSet dataSet = new fghLocalDBDataSet();
fghLocalDBDataSetTableAdapters.CountryTableAdapter countryTableAdapter =
new fghLocalDBDataSetTableAdapters.CountryTableAdapter();
try
{
// Insert a row into Country table. EDIT 1 Will comment after first program run.
Console.WriteLine(countryTableAdapter.Insert("United States"));
// Actually writeback information to the database?
// dataSet.AcceptChanges(); EDIT 2 commented this as LeY suggested it was not needed.
// EDIT 3 Validation code as suggested by Ley.
var dt = new fghLocalDBDataSet.CountryDataTable();
var adapter = new fghLocalDBDataSetTableAdapters.CountryTableAdapter();
adapter.Fill(dt);
foreach (var row in dt)
{
// This does not get executed after a second run of the program.
// Nothing is printed to the screen.
Console.WriteLine("Id:" + row.Id + "----Name: " + row.Name);
}
Console.Read();
}
catch(SqlException exception){
Console.WriteLine("ERROR: " + exception.ToString());
}
Console.ReadLine();
I ran the program and everything seemed fine.
I opened the tables by right clicking on these tables in the server explorer and pressing "Show Data Table".
The "United States" row was not added as wanted.
I think it has to do with the connectionstring. I right clicked on my project and opened properties.
Here I made sure the connection string matched that of the local database by looking at the string in the properties of the database. They are the same.
I copied and pasted the actual text for each connection string:
Connection string of project:
Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\fghLocalDB.mdf;Integrated Security=True
Connection string of actual database (.mdf file):
Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\gabriel\Source\Workspaces\Capstone\Sandbox\aduclos\QueryDataMarketConsole\QueryDataMarketConsole\fghLocalDB.mdf;Integrated Security=True
I am assuming |DataDirectory| is equal to C:\Users\gabriel\Source\Workspaces\Capstone\Sandbox\aduclos\QueryDataMarketConsole\QueryDataMarketConsole\fghLocalDB.mdf; since in the picture above when I clicked on the button to expand the Value of the connection string the connection properties window opened up and had this path for the database file name.
My question in a nutshell is does instantiating a DataSet object in the code automatically create a connection to a SQL service-based database for CRUD operations?
If not how do I connect my DataSet object to my sql database so that way I can actually write to the database when using the TableAdapters?
I read the following links:
Insert method of TableAdapter not working?
TableAdapter Insert not persisting data
Use connectionstring from web.config in source code file
Do I need an actual SqlConnection object? and how to I connect this to the DataSet & TableAdapters?
I never used tableadpter.insert() method. But I tried it on my local machine, and it works.
I can't figure out your problem based on the information you provided, sorry, but I can point you a direction.
If you created everything from wizard, you don't need to worry about the connection, the table Adapters will handle the connection for you. The connection string (you circled) will be added to your app.config file as well as your setting class automaticly. That is how your application (or you) uses it.
var countryTableAdapter = new CountryTableAdapter();
countryTableAdapter.Insert("United States");
This 2 lines of code are enough to insert the row into database if there is no exception thrown, I don't know why it doesn't work for you. Maybe the way you verify it somehow goes wrong, but you can verify it in another way.
The countryTableAdapter.Insert method will return the number of row get affected, in your case , should be one. So put the following code in , and set a breakpoint after it. if the rowAffected == 1, then the insertion works.
var rowAffected = countryTableAdapter.Insert("Test2")
If you need more confirmation , try this.
var dt = new fghLocalDBDataSet.CountryDataTable();
var adapter = new CountryTableAdapter();
adapter.fill(dt);
foreach (var row in dt){
Console.WriteLine("Id:" + row.Id + "----Name: " + row.Name);
}
Console.Read();
you will see all the records in your table.
I hope this will help.
By the way, from your code
dataSet.AcceptChanges();
The line of code above doesn't update the database at all. It only modify your local data storage.
it overwrites your dataRow original version using current version and change the current version row state to unchanged.
Only the tableadapters can talk to database (not true I know, but I just want to make a point that Dataset can not talk to database directly).
And I usually only need tableadapte.Update method and pass the dataSet or dataTable in with correct RowState.
The tableAdapter.update method will call AcceptChanges on each row eventually if it successfully updated the database.
You should never need to call AcceptChanges explicitly unless you only want update your dataset in memory.
I recommend you to read ADO.NET Architecture to get the big picture how DataSet and TableAdapter worked.
It was my connection string after all. In my original post, I said I had two connection strings:
Connection string in project settings:
Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\fghLocalDB.mdf;Integrated Security=True
Actual connection string in fghLocalDB.mdf file:
Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\gabriel\Source\Workspaces\Capstone\Sandbox\aduclos\QueryDataMarketConsole\QueryDataMarketConsole\fghLocalDB.mdf;Integrated Security=True
Something went wrong with
|DataDirectory| = C:\Users\gabriel\Source\Workspaces\Capstone\Sandbox\aduclos\QueryDataMarketConsole\QueryDataMarketConsole\fghLocalDB.mdf;
in my App.config.
My Solution:
What I did was copy the actual connection string of the .mdf file from the .mdf properties panel and paste it into the project properties => Settings => Value field of the connection string set up.
Afterwards I ran my code again and sure enough the data persisted in the tables.
I did not need dataSet.AcceptChanges(); as #LeY pointed out. I also did not need a TableAdapter.Update(dataset) call as posted in other solutions. I just needed the TableAdapter.Insert("...") call.
EDIT: ALSO Most importantly to answer my original question, instantiation a DataSet does not create a connection with the local database. Instead instantiating a TableAdapter does establish a connection with the database!

How to save DataSet after adding data?

Yes, I know that this questions has been asked at least 5-10 times in here, but I can't for the life of me get any of the methods to save the data.
The idea is to create a new row in table Companies in column Name (there is only one column) with value "asdf"`.
I've tried combinations of the following:
DatabaseDataSetTableAdapters.CompaniesTableAdapter adapter = new DatabaseDataSetTableAdapters.CompaniesTableAdapter();
DatabaseDataSet ds = new DatabaseDataSet();
adapter.Insert("asdf");
adapter.Fill(ds.Companies);
adapter.Update(ds.Companies);
ds.AcceptChanges();
ds.Companies.AddCompaniesRow("asdf");
ds.Companies.AcceptChanges();
ds.Companies.AddCompaniesRow("asdf");
ds.Companies.Rows[0]["Name"] = "asdf";
adapter.Update(ds.Companies);
I'm using C# WPF .NET 4.5.1
It does add the data, but it doesn't save it when I exit the program - I know that it adds data, because if I call this method twice it crashes, because the value is no longer unique.
Here is the DatabaseDataSetTableAdapters:
http://pastebin.com/gNsaRFD5
This did not work either:
SqlConnection myConnection = new SqlConnection(global::AliBabaMailer.Properties.Settings.Default.DatabaseConnectionString);
myConnection.Open();
SqlCommand myCommand = new SqlCommand("INSERT INTO Companies (Name) " +
"Values ('string')", myConnection);
myCommand.ExecuteNonQuery();
myConnection.Close();
Ok so your problem is the Connection String:
Properties.Settings.Default.DatabaseConnectionString
This connection string is of the form:
“Data Source=ServerName;AttachDbFilename=|DataDirectory|\DataBaseName;Integrated Security=True”
The |DataDirectory| is usually here:
C:\Users\UserName\AppData
When you save the data it is being saved to a database file at `|DataDirectory| location but when you try to view the data using Server Explorer you are trying to view from a database file which is in your project's folder, that is why If you try to save and then view the data on run time it will work fine because then you will be querying the same database you are storing your data into.
|DataDirectory|:
|DataDirectory| (enclosed in pipe symbols) is a substitution string that indicates the path to the database. It eliminates the need to hard-code the full path which leads to several problems as the full path to the database could be serialized in different places. |DataDirectory| also makes it easy to share a project and also to deploy an application.
For example, instead of having the following connection string:
"Data Source= c:\program files\MyApp\Mydb.sdf"
Using DataDirectory, you can have the following connection string:
“Data Source = |DataDirectory|\Mydb.sdf”
To set the DataDirectory property, call the AppDomain.SetData method. If you do not set the DataDirectory property, the following default rules will be applied to access the database folder:
For applications that are put in a folder on the user's computer, the database folder uses the application folder.
For applications that are running under ClickOnce, the database folder uses the specific data folder that is created.
Link
Coding Advice:
Try to dispose your Command and Connection Objects like this:
using(SqlConnection myConnection = new SqlConnection(global::AliBabaMailer.Properties.Settings.Default.DatabaseConnectionString))
using(SqlCommand myCommand = new SqlCommand("INSERT INTO Companies (Name) " + "Values ('string')", myConnection))
{
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
}

Changing dataset connectionstring at runtime vs2010

I found a solution that must be for a older version then vs2010. I would like to know how to do this for vs2010? Does anyone know?
http://www.csharpbydesign.com/2008/01/overriding-dataset-settings-co.html
Let me explain little more detail.
I have a c# generated dataset. How can I change the connection string so I can use the dataset with another (identically structured yet differently populated) database? This has to occur at runtime as I do not know the server or database name at compile time. i AM USING vs2010 and SQL Server 2008 R2 Express
I think there is no simple way and you cannot change the Connection-String programmatically for the entire DataSet since it's set for every TableAdapter.
You need to use/create the partial class of the TableAdapter to change the connection-string since the Connection property is internal (if your DAL is in a different assembly). Don't change the designer.cs file since it will be recreated automatically after the next change on the designer. To create it just right-click the DataSet and chose "show code".
For example (assuming the TableAdapter is named ProductTableAdapter):
namespace WindowsFormsApplication1.DataSet1TableAdapters
{
public partial class ProductTableAdapter
{
public string ConnectionString {
get { return Connection.ConnectionString; }
set { Connection.ConnectionString = value; }
}
}
}
Now you can change it easily:
var productTableAdapter = new DataSet1TableAdapters.ProductTableAdapter();
productTableAdapter.ConnectionString = someOtherConnectionString;
Here's a screesnhot of my sample DataSet and the created file DataSet1.cs:
There's actually a much easier way to change the connection string.
Go to the Settings screen, where the connection string is displayed as a connection string.
First mark and copy the connection string that's displayed.
Then change the type from connection string to string. The text for the string will change to include xml.
Then paste the copied connection string over the xml text.
Then change the scope from Application to User.
When I want to change the connection string, I use the following code.
// assign the path to use to the variable fullpath (or whatever)
string newConnection = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}", fullpath);
Properties.Settings.Default.HootConnectionString = newConnection;
Properties.Settings.Default.Save();
In my case, I have a global Dataset active, so I have to make that the data is reread by the tableadapter. And, of course, you'll have to add error control to make sure the database is still there.
You'll notice that this will not change what is displayed in Application Settings. Those are defaults.
This works for an Access database; so your mileage and requirements may vary.
EDIT: Caveat. As it works out, when installed, the connection string works well for opening and reading database content, but it complains about not having a connection string when trying to update a database.

How to get SSRS Data Source credentials and open an SQL Connection in .NET

I am using an ASP.Net and C# front end to run some reports. I want to open an SQL Connection to the data source used by the report.
When the report uses integrated security it is easy enough to create a connection, however I want to create a connection when the user name and password are stored by the reporting server.
I can get SQL Server path and initial catalogue, using
DataSource[] dataSources;
DataSourceReference dsReference;
DataSourceDefinition dsDefinition;
string dsPath;
ReportingService2005 rs = new ReportingService2005();
dataSources = rs.GetItemDataSources(reportPath);
if (dataSources.Length > 0)
{
dsReference = (DataSourceReference)dataSources[0].Item;
dsPath = dsReference.Reference;
dsDefinition = rs.GetDataSourceContents(dsPath);
// ....
}
I can also get the user name using
username = dsDefinition.UserName;
however if I use
password = dsDefinition.Password;
password = null, and can't be used to open the Sql Connection.
Is there a way to create an SQLConnection that uses the connection string and username and password credentials of a data source?
I am using Reporting Services 2008, and .NET 3.5 with web references to ReportService2005.asmx and ReportExecution2005.asmx
I really don't think it's possible, as this would pretty much constitute a security hole. I know this isn't the answer you are looking for, but I would parameterise the location of your reports (i.e. the IP/name of your MSRS server) and store them in your web.config along with a matching SQL instance. While it's not exactly what you're after, I think that's about as close as you are going to get.
I think you should read this page:
http://msdn.microsoft.com/en-us/library/reportservice2005.datasourcedefinition_properties.aspx
it shows the password field is write-only, so you can't set its value,but read it only.

Categories

Resources