So i am making a website as part of a college project in c# web developer and i am getting this error, this is the web service and it has been connected to the database i cannot seem to find the error:
**Error 1 Type or namespace definition, or end-of-file expected
Source Error:
Line 278: }
Line 279: }
Line 280:}**
Now where can i go from here? Removing it messes up the entire site and adding another bracket does not help.
using System;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Collections;
using System.Data;
using System.Data.OleDb;
using System.Web.Services.Protocols;
using System.Xml.Linq;
[WebService(Namespace = "http://tempuri.org/")]
public class WebService : System.Web.Services.WebService
{
// Connection is initialized
OleDbConnection conn;
OleDbDataReader dbReader;
private void ConnectToDatabase()
{
// Creates a connection to the database
conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + Server.MapPath("App_Data\\Sports Car Auction Database.accdb"));
// Opens the connection
conn.Open();
}
private void DisconnectDatabase()
{
// The connection is closed
conn.Close();
}
[WebMethod]
public string Login(string userName)
{
// Connects to the database
ConnectToDatabase();
try
{
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = ("Select Password FROM [Buyer Information] WHERE UserName = '" + userName + "'");
dbReader = cmd.ExecuteReader();
dbReader.Read();
// The result is read from the datareader and returned to the calling method
string result = (string)dbReader["Password"];
return result;
}
catch (OleDbException)
{
// Nothing is returned if there are exceptions
return null;
}
}
[WebMethod]
public DataSet ForgetPass(string userName)
{
try
{
// Connect to database
ConnectToDatabase();
// Info from the database is selected via the data adapter
OleDbDataAdapter adapter = new OleDbDataAdapter(#"SELECT [Secret Question], [Answer] From [Buyer Information] Where [UserName] = '" + userName + "'", conn);
// Dataset stores results
DataSet ds = new DataSet();
adapter.Fill(ds);
// Dataset is returned to calling method
return ds;
}
catch
{
// Nothing is returned if there are exceptions
return null;
}
}
[WebMethod]
// Method defines what will be recieved from ChangePassword.aspx
public void ChangePass(string Pass, string userName)
{
// Connects to the database
ConnectToDatabase();
// Values in the database are updated
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = (#"UPDATE [Buyer Information] SET [Password] = '" + Pass + "' WHERE UserName = '" + userName + "'");
cmd.ExecuteNonQuery();
// The connection is closed
DisconnectDatabase();
}
[WebMethod]
// Method define what values will be recieved form register.aspx
public void RegisterCustomer(string UserName, string Address, string Tel, string Email, string Ques, string Ans, string Pass)
{
// Connects to thedatabase
ConnectToDatabase();
// Values are inserted into the database
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = #"INSERT INTO [Buyer Information] ([UserName], [Address], [Telephone], [Email], [Password], [Secret Question], [Answer]) VALUES ('" + UserName + "', '" + Address + "', '" + Tel + "', '" + Email + "', '" + Pass + "', '" + Ques + "', '" + Ans + "')";
cmd.ExecuteNonQuery();
// The connection is closed
DisconnectDatabase();
}
[WebMethod]
public DataSet ViewDetails(string userName)
{
try
{
// Connects to the database
ConnectToDatabase();
// The correct data is selected from the database using the data adapter
OleDbDataAdapter adapter = new OleDbDataAdapter(#" SELECT Address, Telephone, Email, [Secret Question], Answer FROM [Buyer Information] WHERE UserName = '" + userName + "'", conn);
// The sesults are stored in the dataset
DataSet ds = new DataSet();
adapter.Fill(ds);
// Dataset is returned to the calling method
return ds;
}
catch (OleDbException)
{
// Nothing is returned if there are exceptions
return null;
}
}
[WebMethod]
// This defines what values will be recieved from Details.aspx
public void UpdateCustomer(string userName, string Address, string Tel, string Email, string Ques, string Ans)
{
// Connects to the database
ConnectToDatabase();
// Updates the database
OleDbCommand cmd = new OleDbCommand(#"UPDATE [Buyer Information] SET [UserName] = '" + userName + "', [Address] = '" + Address + "', [Telephone] = '" + Tel + "', [Email] = '" + Email + "', [Secret Question] = '" + Ques + "', [Answer] = '" + Ans + "' WHERE [UserName] = '" + userName + "'", conn);
cmd.ExecuteNonQuery();
// The connection is closed
DisconnectDatabase();
}
[WebMethod]
public DataSet SelectItem()
{
try
{
ConnectToDatabase();
// Get the model values for the drop down list
OleDbDataAdapter da = new OleDbDataAdapter("SELECT Model FROM Car", conn);
DataSet ds = new DataSet();
da.Fill(ds, "Model");
return ds;
}
catch (OleDbException)
{
// Nothing is returned if there are exceptions
return null;
}
}
[WebMethod]
public DataSet selectCarInfo(string model)
{
try
{
// Connects to the database
ConnectToDatabase();
// Info is selected from the database via the data adapter
OleDbDataAdapter adapter = new OleDbDataAdapter(#"SELECT [Car Information].carID, [Car Information].Make, [Car Information].Description, [Car Information].[Starting Bid], [Car Information].[Closing Date] FROM [Car Information] WHERE Model = '" + model + "'", conn);
// The results are stored in dataset
DataSet ds = new DataSet();
adapter.Fill(ds);
// Dataset is returned to calling method
return ds;
}
catch
{
// Nothing is returned if there are exceptions
return null;
}
}
[WebMethod]
public decimal highestBidVal(int carID)
{
try
{
// Connects to the database
ConnectToDatabase();
// Selects highestBid to compare to Buyer Informations value
OleDbCommand cm = conn.CreateCommand();
cm.CommandText = ("SELECT [Bid Information].HighestBid FROM [Bid Information] WHERE carID = " + carID + "");
dbReader = cm.ExecuteReader();
dbReader.Read();
decimal highestBidValue = (decimal)dbReader["HighestBid"];
return highestBidValue;
}
catch (OleDbException)
{
// Nothing is returned if there are exceptions
return 0;
}
}
[WebMethod]
// Method that defines what will be recieved from AddNewItem.aspx
public void AddNewCar(string Make, string Model, string Description, decimal StartingBid, DateTime closeDate, string owner)
{
ConnectToDatabase();
OleDbCommand cmd = conn.CreateCommand();
// Values are inserted into the database
cmd.CommandText = (#" INSERT INTO [Car Information] ([Make], [Model], [Description], [Starting Bid], [Closing Date], [Owner]) VALUES ('" + Make + "', '" + Model + "', '" + Description + "', '" + StartingBid + "', '" + closeDate + "', '" + owner + "')");
cmd.ExecuteNonQuery();
// Closes the connection
DisconnectDatabase();
}
[WebMethod]
// Method that defines what will be recieved from PlaceBid.aspx
public void AddNewBid(int carid, string userName, decimal bidValue,
DateTime bidingDate)
{
ConnectToDatabase();
// Values are updated in the database
OleDbCommand cmd = new OleDbCommand(#"UPDATE [Bid Information] SET [carID] = '" + carid + "', [UserName] = '" + userName + "', [Highest Bid] = '" + bidValue + "', [Bid Date] = '" + bidingDate + "' WHERE [carID] = " + carid + "", conn);
cmd.ExecuteNonQuery();
// The connection is closed
DisconnectDatabase();
}
[WebMethod]
// Method that defines what values will be recieved from Placebid.aspx
public void AddBid(int carid, string userName, decimal bidValue, DateTime bidingDate)
{
ConnectToDatabase();
OleDbCommand cmd = conn.CreateCommand();
// Values are inserted into the database
cmd.CommandText = (#"INSERT INTO [Bid Information] ([carID], [UserName], [UserName], [HighestBid], [Biddate]) VALUES ('" + carid + "', '" + userName + "', '" + bidValue + "', '" + bidingDate + "')");
cmd.ExecuteNonQuery();
// Closes the connection
DisconnectDatabase();
}
}
}
The last closing bracket seems to be the one which would match the namespace. Removing it should do it.
You can try to format your code with control-k-d. If it works, then your brackets (and the amount of them) match.
If you still get an error, that means your code has more errors in it. You probably are indeed missing a using directive, but that is another error. You do need to remove that closing-bracket, since it has no open-bracket match.
Related
Tried to move data from one form to another and there is a problem with the table. Yes I found such themes with a mistake, and tried to correct himself, but something went wrong.
using (SqlConnection conn = new SqlConnection("Data Source=DESKTOP-R552818\\SQLEXPRESS;Initial Catalog=Fond;Integrated Security=True"))
{
SqlDataAdapter comm = new SqlDataAdapter("INSERT INTO Pacient (Name, id_diagnoz, Surname, Middle_name, Column__Passport, Legal_address_Clinic, Age) " +
"VALUES ('"+ tName.Text + "', (SELECT id_diagnoz FROM Diagnoz WHERE Name_diagnoz = '" + cbName.Text + "' and Stage = '" + cbStage.Text + "'), '" + tSurname.Text + "', '" + tMiddle.Text + "', '" + tPas.Text + "', '" + cbClinic.Text + "', '" + tAge.Text + "')", conn);
conn.Open();
DataSet ds = new DataSet();
//ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
comm.Fill(ds);
Form1 form = new Form1();
form.DataGrid.DataSource = ds.Tables[0]; //?
}
string connectionString = "Data Source=DESKTOP-R552818\\SQLEXPRESS;Initial Catalog=Fond;Integrated Security=True";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlTransaction transaction = connection.BeginTransaction();
SqlCommand command = connection.CreateCommand();
command.Transaction = transaction;
try
{
command.CommandText = "INSERT INTO Pacient (Name, id_diagnoz, Surname, Middle_name, Column__Passport, Legal_address_Clinic, Age) " +
"VALUES ('" + metroTextBox1.Text + "', (SELECT id_diagnoz FROM Diagnoz WHERE Name_diagnoz = '" + metroComboBox1.Text + "' and Stage = '" + metroComboBox2.Text + "'), '" + metroTextBox2.Text + "', '" + metroTextBox3.Text + "', '" + maskedTextBox1.Text + "', '" + metroComboBox3.Text + "', '" + metroTextBox5.Text + "')";
command.ExecuteNonQuery();
transaction.Commit();
MessageBox.Show("Added");
//here is a DataSet
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
transaction.Rollback();
}
}
You are expecting results to be returned from your query, but what you do is just INSERT statement.
For inserting values you should use ExecuteNonQuery method of SqlCommand (see this for reference).
Then, assign another command: SELECT to get the results, then you can fill DataSet with the result and then you can fill DataGridView with it.
Also: you are rpone to SQL injection, use parametrized query to prevent yourself from such threat (see this for reference).
I wrote a SQL command to save some items in my database. But when I run it, it gives an error message:
And here is my code:
public void Opslaan(string titel, string rVoornaam, string rAchternaam, decimal beoordeling, string a1Voornaam, string a1Achternaam, string a2Voornaam, string a2Achternaam, string a3Voornaam, string a3Achternaam)
{
if (beoordelingBest < beoordeling)
{
titelBest = titel;
beoordelingBest = beoordeling;
}
string queryString = "INSERT INTO Films (titel, beoordeling) VALUES('" + titel + "', " + beoordeling + ");" +
"INSERT INTO Acteurs (voornaam, achternaam, FilmID) VALUES('" + a1Voornaam + "' , '" + a1Achternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));" +
"INSERT INTO Acteurs (voornaam, achternaam, FilmID) VALUES('" + a2Voornaam + "' , '" + a2Achternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));" +
"INSERT INTO Acteurs (voornaam, achternaam, FilmID) VALUES('" + a3Voornaam + "' , '" + a3Achternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));" +
"INSERT INTO Regisseurs (voornaam, achternaam, FilmID) VALUES('" + rVoornaam + "' , '" + rAchternaam + "', (SELECT FilmID from Films where titel = '" + titel + "'));";
command = new SqlCommand(queryString, con);
Can someone please help me with this? I can't figure it out.
Use parametererized queries and do not use string concatination. This is to prevent sql injection attacks but also errors with the values like forgetting to make sure strins are escaped (if a string contains a ' for example).
If you have multiple queries each unique parameter value should have its own parameter name/value
Wrap your ado.net database types (SqlConnection, SqlCommand, etc) in using blocks if they are disposable
Never reuse connections as global objects, create, use, and destroy them when needed.
Here is the updated code with 1 statement, you can append additional statements to this and add more parameters as necessary.
var query = "INSERT INTO Acteurs (voornaam, achternaam, FilmID) SELECT #a1Voornaam, #a1Achternaam, FilmID from Films WHERE titel = #title";
using(var con = new SqlConnection("connection string here"))
using(var command = new SqlCommand(queryString, con))
{
command.Parameters.Add(new SqlParameter("#a1Voornaam", SqlDbType.VarChar){Value = a1Voornaam});
command.Parameters.Add(new SqlParameter("#achternaam", SqlDbType.VarChar){Value = achternaam});
command.Parameters.Add(new SqlParameter("#title", SqlDbType.VarChar){Value = title});
con.Open();
command.ExecuteNonQuery();
}
Perhaps one of your values is ');
That would terminate the INSERT statement early, and cause the error.
|
V
INSERT INTO Films (titel, beoordeling) VALUES('');,'anything');
You should use SqlParameters instead of string concatenation.
Are you using TextBoxes? I can't tell for sure. Try something like this, and change to suit your specific needs.
using System.Data.SqlClient;
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(System.Configuration.
ConfigurationManager.ConnectionStrings["con"].ToString());
try
{
string query = "insert into UserDetail(Name,Address)
values('" + txtName.Text + "','" + txtAddress.Text + "');";
SqlDataAdapter da = new SqlDataAdapter(query, con);
con.Open();
da.SelectCommand.ExecuteNonQuery();
con.Close();
lblmessage.Text = "Data saved successfully.";
}
catch
{
con.Close();
lblmessage.Text = "Error while saving data.";
}
}
My SQLite query hangs then locks during my ExecuteNonQuery() in WriteToDB() below. It only seems to lock during the UPDATE and has no problem with the INSERT. This is only running in a single thread. When it hangs, I can see the journal being created in the SQLite database directory as if it keeps trying to write. It throws a SQLiteException with ErrorCode=5, ResultCode=Busy.
public String WriteToDB()
{
String retString = "";
//see if account exists with this email
String sql = "";
bool aExists = AccountExists();
if (!aExists)
{
sql = "INSERT INTO accounts (email, password, proxy, type, description) VALUES ('" + Email + "', '" + Password + "', '" + Proxy + "', 'dev', '" + Description + "');";
retString = "Added account";
}
else
{
sql = "UPDATE accounts SET password='" + Password + "', proxy='" + Proxy + "', description='" + Description + "' WHERE (email='" + Email + "' AND type='dev');";
retString = "Updated account";
}
using (SQLiteConnection dbconn = new SQLiteConnection("Data Source=" + Form1.DBNAME + ";Version=3;"))
{
dbconn.Open();
using (SQLiteCommand sqlcmd = new SQLiteCommand(sql, dbconn))
{
sqlcmd.ExecuteNonQuery(); //this is where it locks. Only on update.
}
}
return retString;
}
//Test to see if Email exists as account
public bool AccountExists()
{
int rCount = 0;
String sql = "SELECT COUNT(email) FROM accounts WHERE email='" + Email + "' AND type='dev';";
using (SQLiteConnection dbconn = new SQLiteConnection("Data Source=" + Form1.DBNAME + ";Version=3;"))
{
dbconn.Open();
using (SQLiteCommand sqlcmd = new SQLiteCommand(sql, dbconn))
{
rCount = Convert.ToInt32(sqlcmd.ExecuteScalar());
}
}
if (rCount > 0)
return true;
return false;
}
Oh man I feel dumb. I thought I posted all relevant code but all the code I posted works just fine. I had:
SQLiteDataReader dbReader = sqlcmd.ExecuteReader()
instead of
using (SQLiteDataReader dbReader = sqlcmd.ExecuteReader())
In another function. I thought it was an issue with the UPDATE because that was the place where the lock took place. Thanks for the responses and hopefully this reminds reminds everyone to use using() blocks with SQLite the first time!
i decided to code a contact program which will connect to SQL server.
Nearly i have completed to codes and program runs good.
But i have a problem.
When user wants to delete a contact from this program , he should enter Family Name of contact whom he wants to delete then press Delete button in the form.
Well this way is not very good because it is possible that there were for example 5 guys with the same family name.
i decided to Add a field in the SQL server in the name of Code.
This code is unique for every contacts.
But i have a problem. how should i code program that whenever user type the information of contact and click save , this unique code add automatically to the Code field in the SQL server ?
here is my codes you can see :
namespace Contact
{
class Operation
{
SqlConnection cn;
public Operation()
{
cn = new SqlConnection(Connection.Server);
}
public DataTable Show()
{
SqlCommand cmd = new SqlCommand("select * from tblContact ", cn);
SqlDataAdapter da = new SqlDataAdapter(cmd.CommandText, cn);
DataTable dt = new DataTable();
da.Fill(dt);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
return dt;
}
public void Add(string Name , string FamilyName , string Work , string Fax , string Phone , string Home)
{
SqlCommand cmd = new SqlCommand("insert into tblContact(Name,FamilyName,Work,Fax,Phone,Home) values ('" + Name + "' , '" + FamilyName + "' , '" + Work + "' , '" + Fax + "' , '" + Phone + "' , '" + Home + "')", cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
public void Delete(string FamilyName)
{
SqlCommand cmd = new SqlCommand("delete from tblContact where FamilyName = '" + FamilyName + "'", cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
public void Update (string Name , string FamilyName , string Work , string Fax , string Phone , string Home)
{
SqlCommand cmd = new SqlCommand("update tblContact set FamilyName = '" + FamilyName + "' ,Work = '" + Work + "' , Fax = '" + Fax + "' , Name = '" + Name + "' , Home = '" + Home + "' where Phone = '" + Phone + "'",cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}
}
For having a unique column in a table, the best way is to create a column (Named ID for exmaple) with int type or bigint and set the Identity property to true. In this case you have a column that the value is started from 1 and increments automatically for each new row. You can set this column to primary key too, because it is unique and not null.
Then for delete purpose you can use this column only.
DELETE FROM tblContact WHERE ID = (Your Parameter)
Just set the Parameter.
You should first find deleting row based on familyname or any other column, then get the ID value from that row and call delete for that row.
The better way for this purpose is that you show the list of contacts to the user (in a grid for example and hide the ID column) and the user selects the row for delete. At that time you have the ID from that row and pass that to this function:
public void Delete(int ID)
{
SqlCommand cmd = new SqlCommand("delete from tblContact where ID = " + ID + "'", cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
protected void save_Click(object sender, EventArgs e)
{
OleDbConnection conn = null;
try
{
string connString = "Provider=OraOLEDB.Oracle;Data Source=127.0.0.1;User ID=SYSTEM;Password=SYSTEM;Unicode=True";
conn = new OleDbConnection(connString);
conn.Open();
string strQuery = "update login set fname ='" + TextBox4.Text + "' and lname='" + TextBox5.Text + "' and place='" + TextBox6.Text + "' and dob='" + TextBox7.Text + "' where uname='" + Label1.Text + "'";
OleDbCommand obCmd = new OleDbCommand(strQuery, conn);
OleDbDataReader obReader = obCmd.ExecuteReader();
}
catch (OleDbException ex)
{
Response.Write("Send failure: " + ex.ToString());
}
catch (Exception exe)
{
Response.Write(exe.Message);
}
finally
{
if (null != conn)
{
conn.Close();
}
}
}
the update query syntax is wrong.
You cannot use AND while setting multiple columns. It should be seperated by comma.
string strQuery = "update login set fname ='" + TextBox4.Text + "',lname='" +
TextBox5.Text + "',place='" + TextBox6.Text + "',dob='" + TextBox7.Text +
"' where uname='" + Label1.Text + "'";
The values must be separated with a comma and there is one big problem in this code. Imagine what happens when someone puts the following into TextBox4:
' where 1 = 1 --
The result would be a table where all entries would be overwritten
update login set fname ='' where 1 = 1 --', lname='bla' ....
Use DbParameter instead:
string strQuery = #"
update LOGIN set
FNAME = :FNAME,
LNAME = :LNAME,
PLACE = :PLACE,
DOB = :DOB
where
UNAME = :UNAME
";
OleDbCommand obCmd = new OleDbCommand(strQuery, conn);
obCmd.Parameters.AddWithValue(":FNAME", TextBox4.Text);
obCmd.Parameters.AddWithValue(":LNAME", TextBox5.Text);
obCmd.Parameters.AddWithValue(":PLACE", TextBox6.Text);
obCmd.Parameters.AddWithValue(":DOB", TextBox7.Text);
obCmd.Parameters.AddWithValue(":UNAME", Label1.Text);
OleDbDataReader obReader = obCmd.ExecuteReader();
For Oracle the : should indicate a parameter (it's a # for Sybase and MS SQL). I named all params like the target columns, but you can use other names of course.