DataAdapter.Update not updating - sql

hey hope someone can help, going crazy :-)
doing a little program that gets dataset and updates it again, i have the following SQLclass. Dataset is traversing fine and values are changed but it dosnt commit to DB.
class SQLConnection
{
private string SQL_String;
private string strCON;
System.Data.SqlClient.SqlDataAdapter da_1;
public string Sql {
set { SQL_String = value; }
}
public string connection_string
{
set { strCON = value; }
}
public System.Data.DataSet Getconnection
{
get { return Getmydataset(); }
}
private System.Data.DataSet Getmydataset()
{
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(strCON);
con.Open();
da_1 = new System.Data.SqlClient.SqlDataAdapter(SQL_String, con);
System.Data.DataSet dat_set = new System.Data.DataSet();
da_1.Fill(dat_set, "Table_Data_1");
return dat_set;
}
public void UpdateDatabase(System.Data.DataSet ds)
{
System.Data.SqlClient.SqlCommandBuilder cb = new System.Data.SqlClient.SqlCommandBuilder(da_1);
int test = cb.DataAdapter.Update(ds.Tables[0]);
}
}
}
When i call the class and try to do update the DataAdapter returns 0
static public void Main(string[] args)
{
GetClosedComputers();
}
getclosedcomputers
public static DataSet GetClosedComputers()
{
try
{
SQLConnection objConnect = new SQLConnection();
conString = Properties.Settings.Default.Connectionstring;
objConnect.connection_string = conString;
//call stored procedure
objConnect.Sql = Properties.Settings.Default.GetNextClosedComputers;
ds = objConnect.Getconnection;
ds.Tables[0].Columns["State"].Expression = "'1'";
objConnect.UpdateDatabase(ds);
}
catch (Exception e)
{
ErrorString = e.Message;
}
return ds;
}

Hmm seemed like i had to issues, first of i couldnt use an UpdateProcedure, which i not sure why and also the ".Expression" could be used, this solved it.
objConnect = new SQLConnection();
conString = Properties.Settings.Default.Connectionstring;
objConnect.connection_string = conString;
// use sql query instead of stored procedure!!!
objConnect.Sql = Properties.Settings.Default.Test;
//Dataset with all computers
ds = objConnect.Getconnection;
//DataSet results = StartStopVM.StartVirtualMachines(ds);
DataTable dt = ds.Tables[0];
//this didnt work
//ds.Tables[0].Columns["State"].Expression = "'1'";
//
foreach(DataRow dr in dt.Rows)
{
dr["State"] = 1;
}
objConnect.UpdateDatabase(ds);

Related

Can't use retrieved data from one query into another one?

I need to use a variable (edifcodigo) which assigned value is retrieved from one query to insert it in a table by using other query but there is a error that says this variable is not available in actual context. I'm kind of new in aspnet, could anybody know how to figure this out?
This is the code I have:
//Connect to db
string connetionString = #"myconexionstring";
string sql = "SELECT TOP 1 id_proyecto AS codigo FROM DNN_SCO_PROY_CO_PROYECTO_TBL WHERE nombre_proyecto= '"+ uedif +"'";
//find building code by querying the database
try
{
using (SqlConnection conexion = new SqlConnection(connetionString))
{
conexion.Open();
using (SqlCommand query = new SqlCommand(sql, conexion))
{
SqlDataReader result = query.ExecuteReader();
while (result.Read())
{
string edifcodigo = result["codigo"].ToString();
}
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
//Save referer friend
try
{
using (SqlConnection conn = new SqlConnection(connetionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("DNN_SVI_SCO_DATOS_RECOMIENDA_AMIGO_SP", conn))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add("#DRA_PROYECTO_CLIENTE", System.Data.SqlDbType.VarChar).Value = edifcodigo; ;
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
That's because you declared the variable inside a different code block. Every time you open a curly bracket, you open a new code block. Every time you close the curly bracket, you close the current code block. Each code block have it's own scope - it can access variables declared in the surrounding code block, but not variables declared in "sibling" code blocks.
Also, please read about parameterized queries and how they protect you from SQL injection, and change your queries accordingly.
Also, you don't need to close the connection between the two commands, and you can reuse a single command instance in this case. Here is an improved version of your code:
//Connect to db
var connetionString = #"myconexionstring";
var sql = "SELECT TOP 1 id_proyecto AS codigo FROM DNN_SCO_PROY_CO_PROYECTO_TBL WHERE nombre_proyecto = #nombre_proyecto";
//find building code by querying the database
try
{
using (var conexion = new SqlConnection(connetionString))
{
conexion.Open();
using (var cmd = new SqlCommand(sql, conexion))
{
cmd.Parameters.Add("#nombre_proyecto", SqlDbType.NVarChar).Value = uedif;
var edifcodigo = cmd.ExecuteScalar();
//Save referer friend
cmd.Parameters.Clear();
cmd.CommandText = "DNN_SVI_SCO_DATOS_RECOMIENDA_AMIGO_SP";
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add("#DRA_PROYECTO_CLIENTE", System.Data.SqlDbType.VarChar).Value = edifcodigo; ;
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
You are declaring the string variable inside your while loop, it loses scope once you exit the while loop, move it's declaration above with:
string connetionString = #"myconexionstring";
string sql = "SELECT TOP 1 id_proyecto AS codigo FROM DNN_SCO_PROY_CO_PROYECTO_TBL WHERE nombre_proyecto= '"+ uedif +"'";
string edifcodigo = "";
You are trying to use a variable that declared in another scope. edifcodigo should be declared in the parent scope of both try blocks.
//Connect to db
string connetionString = #"myconexionstring";
string sql = "SELECT TOP 1 id_proyecto AS codigo FROM DNN_SCO_PROY_CO_PROYECTO_TBL WHERE nombre_proyecto= '"+ uedif +"'";
string edifcodigo=""; // YOU SHOULD DECLARE edifcodigo HERE
and than rest of code will come
//find building code by querying the database
try
{
using (SqlConnection conexion = new SqlConnection(connetionString))
{
conexion.Open();
using (SqlCommand query = new SqlCommand(sql, conexion))
{
SqlDataReader result = query.ExecuteReader();
while (result.Read())
{
edifcodigo = result["codigo"].ToString();
}
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
//Save referrer friend
try
{
using (SqlConnection conn = new SqlConnection(connetionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("DNN_SVI_SCO_DATOS_RECOMIENDA_AMIGO_SP", conn))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add("#DRA_PROYECTO_CLIENTE", System.Data.SqlDbType.VarChar).Value = edifcodigo; ;
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}

The data isn't being loaded into datagrid view. What am i missing?

I think this is one of those times where I'm looking at the code and it all seems fine because my eye's think it will be. I need a fresh set of eyes to look at this code and tell me way it's not loading into the first datagrid view. Thank you for any help your able to provide.
private DataSet DataSetRentals { get; set; }
public DataRelationForm()
{
InitializeComponent();
}
private void DataRelationForm_Load(object sender, EventArgs e)
{
DataSet relationship = new DataSet("relationship");
/////
SqlConnection conn = Database.GetConnection();
SqlDataAdapter adapter = new SqlDataAdapter("Select * From Car", conn);
DataSet DataSetRentals = new DataSet("Relationship");
adapter.FillSchema(DataSetRentals, SchemaType.Source, "Car");
adapter.Fill(DataSetRentals, "Car");
adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
adapter.Fill(DataSetRentals, "Car");
DataTable Car;
Car = DataSetRentals.Tables["Car"];
foreach (DataRow drCurrent in Car.Rows)
{
Console.WriteLine("{0} {1}",
drCurrent["au_fname"].ToString(),
drCurrent["au_lname"].ToString());
}
////////////////////////////////////
SqlDataAdapter adapter2 = new SqlDataAdapter("Select * From CarRental", conn);
adapter.FillSchema(DataSetRentals, SchemaType.Source, "Rentals");
adapter.Fill(DataSetRentals, "Rentals");
adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
adapter.Fill(DataSetRentals, "Rentals");
DataTable CarRental;
CarRental = DataSetRentals.Tables["Rentals"];
foreach (DataRow drCurrent in CarRental.Rows)
{
Console.WriteLine("{0} {1}",
drCurrent["au_fname"].ToString(),
drCurrent["au_lname"].ToString());
}
/////
SqlDataAdapter adapter3 = new SqlDataAdapter("Select * From Customer", conn);
adapter.FillSchema(DataSetRentals, SchemaType.Source, "Customer");
adapter.Fill(DataSetRentals, "Customer");
adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
adapter.Fill(DataSetRentals, "Customer");
DataTable Customer;
Customer = DataSetRentals.Tables["Customer"];
foreach (DataRow drCurrent in Customer.Rows)
{
Console.WriteLine("{0} {1}",
drCurrent["au_fname"].ToString(),
drCurrent["au_lname"].ToString());
}
////////////////////////
DataSetRentals.Tables.Add(Customer);
DataSetRentals.Tables.Add(CarRental);
DataSetRentals.Tables.Add(Car);
DataRelation Step1 = new DataRelation("Customer2CarR",
Customer.Columns["CustomerNo"], CarRental.Columns["CustomerNo"]);
DataSetRentals.Relations.Add(Step1);
DataRelation Step2 = new DataRelation("CarR2Car",
Car.Columns["CarID"], CarRental.Columns["CarID"]);
DataSetRentals.Relations.Add(Step2);
////////////////////////
CustomerGrid.DataSource= DataSetRentals.Tables["Customer"];
CarRGrid.DataSource = DataSetRentals.Tables["CarRental"];
CarGrid.DataSource = DataSetRentals.Tables["Car"];
CustomerGrid.SelectionChanged += new EventHandler(Customer_SelectionChanged);
CarRGrid.SelectionChanged += new EventHandler(CarR_SelectionChanged);
}
private void Customer_SelectionChanged(Object sender, EventArgs e)
{
if (CustomerGrid.SelectedRows.Count > 0)
{
DataRowView selectedRow =
(DataRowView)CustomerGrid.SelectedRows[0].DataBoundItem;
DataSetRentals.Tables["CarRental"].DefaultView.RowFilter =
"CustomerNo = " + selectedRow.Row["CustomerNo"].ToString();
}
else
{
}
}
private void CarR_SelectionChanged(Object sender, EventArgs e)
{
if (CarRGrid.SelectedRows.Count > 0)
{
DataRowView selectedRow =
(DataRowView)CarRGrid.SelectedRows[0].DataBoundItem;
DataSetRentals.Tables["Car"].DefaultView.RowFilter =
"CarID = " + selectedRow.Row["CarID"].ToString();
}
}
And this is the code for the Database.GetConnection() method:
SqlConnectionStringBuilder stringBuilder = new SqlConnectionStringBuilder();
bool OnUni;
OnUni = (System.Environment.UserDomainName == "SOAC") ? true : false;
stringBuilder.DataSource = (OnUni) ? #"SOACSQLSERVER\SHOLESQLBSC" : "(local)";
stringBuilder.InitialCatalog = "CarRental_P117365";
stringBuilder.IntegratedSecurity = true;
return new SqlConnection(stringBuilder.ConnectionString);
It looks like you may have forgotten to call SqlConnection.Open() to actually open the connection. I would also recommend wrapping your connection in a using and explicitly calling SqlConnection.Close() at the end of it, so you don't accidentally leave it open:
using(SqlConnection conn = Database.GetConnection())
{
conn.Open();
/*
rest of code here
*/
conn.Close();
}
For some other good information/examples of properly opening/disposing of SqlConnections, you can also take a look at these SO questions:
Close and Dispose - which to call?
Do I have to Close() a SQLConnection before it gets disposed?
in a "using" block is a SqlConnection closed on return or exception?
youre not binding your data to any datasoruce.
try something like this
using(SqlConnection conn = Database.GetConnection())
try
{
{
------your code here up to DataTable Car-----
DataTable Car;
Car = DataSetRentals.Tables["Car"];
gridview.Datasource = Car;
}
}
catch (SqlException sqlex )
{
string msg = "Fetch Error:";
msg += sqlex.Message;
throw new Exception(msg);
}
Theres no need to open or close the SQL connection as this is done using the using statement at the top where it opens, and when its finishes closes \ disposes of the connection

Loading data from SQL Server into C# application

I have some problem accessing my data from a SQL Server database via C# application. I have a small project to make and I can't go further because my data is loading in. I try to load it in a DataGridView.
Here are some code examples:
public List<Country> GetCountryList()
{
string query = "SELECT * FROM Orszag", error = string.Empty;
SqlDataReader rdr = ExecuteReader(query, ref error);
List<Country> countryList = new List<Country>();
if (error == "OK")
{
while (rdr.Read())
{
Country item = new Country();
item.CountryId = Convert.ToInt32(rdr[0]);
item.CountryName = rdr[1].ToString();
countryList.Add(item);
}
}
CloseDataReader(rdr);
return countryList;
}
This is where I put my data in a list
private void FillDgvGames()
{
dgvGames.Rows.Clear();
List<Country> CountryList = m_Country.GetCountryList();
foreach (Country item in CountryList)
{
dgvGames.Rows.Add(item.CountryId,item.CountryName);
}
}
And this is where I retrieve it ... I have to make the same thing with 8 more tables but this is the simplest and I thought it's easier this way.... if someone can help me I'd appreciate it ...
PS:
This is the execute reader
protected SqlDataReader ExecuteReader(string query, ref string errorMessage)
{
try
{
OpenConnection();
SqlCommand cmd = new SqlCommand(query, m_Connection);
SqlDataReader rdr = cmd.ExecuteReader();
errorMessage = "OK";
return rdr;
}
catch (SqlException e)
{
errorMessage = e.Message;
CloseConnection();
return null;
}
}
And this is the connection string
protected string m_ConnectionString = "Data Source=SpD-PC;Initial Catalog=master;Integrated Security=SSPI";
Are you setting the data source of your DataGridView?
dgvGames.DataSource = CountryList;

how to enable SQL Application Role via Entity Framework

I'm now developing big government application with entity framework. at first i have one problem about enable SQL application role. with ado.net I'm using below code:
SqlCommand cmd = new SqlCommand("sys.sp_setapprole");
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = _sqlConn;
SqlParameter paramAppRoleName = new SqlParameter();
paramAppRoleName.Direction = ParameterDirection.Input;
paramAppRoleName.ParameterName = "#rolename";
paramAppRoleName.Value = "AppRole";
cmd.Parameters.Add(paramAppRoleName);
SqlParameter paramAppRolePwd = new SqlParameter();
paramAppRolePwd.Direction = ParameterDirection.Input;
paramAppRolePwd.ParameterName = "#password";
paramAppRolePwd.Value = "123456";
cmd.Parameters.Add(paramAppRolePwd);
SqlParameter paramCreateCookie = new SqlParameter();
paramCreateCookie.Direction = ParameterDirection.Input;
paramCreateCookie.ParameterName = "#fCreateCookie";
paramCreateCookie.DbType = DbType.Boolean;
paramCreateCookie.Value = 1;
cmd.Parameters.Add(paramCreateCookie);
SqlParameter paramEncrypt = new SqlParameter();
paramEncrypt.Direction = ParameterDirection.Input;
paramEncrypt.ParameterName = "#encrypt";
paramEncrypt.Value = "none";
cmd.Parameters.Add(paramEncrypt);
SqlParameter paramEnableCookie = new SqlParameter();
paramEnableCookie.ParameterName = "#cookie";
paramEnableCookie.DbType = DbType.Binary;
paramEnableCookie.Direction = ParameterDirection.Output;
paramEnableCookie.Size = 1000;
cmd.Parameters.Add(paramEnableCookie);
try
{
cmd.ExecuteNonQuery();
SqlParameter outVal = cmd.Parameters["#cookie"];
// Store the enabled cookie so that approle can be disabled with the cookie.
_appRoleEnableCookie = (byte[]) outVal.Value;
}
catch (Exception ex)
{
result = false;
msg = "Could not execute enable approle proc." + Environment.NewLine + ex.Message;
}
But no matter how much I searched I could not find a way to implement on EF.
Another question is: how to Add Application Role to Entity data model designer?
I'm using the below code for execute parameter with EF:
AEntities ar = new AEntities();
DbConnection con = ar.Connection;
con.Open();
msg = "";
bool result = true;
DbCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
var d = new DbParameter[]{
new SqlParameter{ ParameterName="#r", Value ="AppRole",Direction = ParameterDirection.Input}
, new SqlParameter{ ParameterName="#p", Value ="123456",Direction = ParameterDirection.Input}
};
string sql = "EXEC " + procName + " #rolename=#r,#password=#p";
var s = ar.ExecuteStoreCommand(sql, d);
When run ExecuteStoreCommand this line return error:
Application roles can only be activated at the ad hoc level.
I do it the following way (assuming Database First):
I create the DbContext from the db and call it MyEntitiesBase
I inherit from MyEntitiesBase to create MyEntities with the following code:
public partial class MyEntities : MyEntitiesBase
{
private byte[] appRoleCookie;
private void SetAppRole()
{
try
{
appRoleCookie = Database.SqlQuery<byte[]>(
#"
DECLARE #cookie VARBINARY(8000)
DECLARE #r INT
EXEC sp_setapprole 'user', 'pass', #fCreateCookie = true, #cookie = #cookie OUTPUT
SELECT #cookie").First();
}
catch
{
throw new AuthenticationException();
}
}
private void UnSetAppRole()
{
bool failed = Database.SqlQuery<bool>("DECLARE #result BIT; EXEC #result = sp_unsetapprole #cookie = " + appRoleCookie.ToHexadecimalString() + "; SELECT #result").First();
if (failed)
throw new SecurityException();
}
public MyEntities() : base()
{
Database.Connection.Open();
SetAppRole();
}
private bool disposed = false;
protected override void Dispose(bool disposing)
{
if (disposed)
return;
UnSetAppRole();
Database.Connection.Close();
disposed = true;
base.Dispose(disposing);
}
}
Where ToHexadecimalString is an extension method for IEnumerable<byte>, as follows:
public static class BytesExtensions
{
public static string ToHexadecimalString(this IEnumerable<byte> bytes)
{
return "0x" + string.Concat(bytes.Select(b => b.ToString("X2")));
}
}
And that's it. Works with connection pooling on and everything. You just use this inherited version instead of the one generated by EF.
Basically what you are doing is calling a stored procedure.
Entity Framework has functionality to excute stored procedures. Here is an explaination with a video: http://msdn.microsoft.com/en-us/data/gg699321.aspx
If your scrol down to the section "Using Import Functions to Map Stored Procedures" you will find the part that is relevant for you.

silverlight C# code

This is coded in Service.svc.cs file
[OperationContract]
public List<Branch> GetAllBranch()
{
List<Branch> Br = new List<Branch>();
using (SqlConnection con = new SqlConnection(myConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "GetBranch";
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Branch BrName = new Branch();
BrName.Name = Convert.ToString(dr["BranchName"]);
Br.Add(BrName);
}
dr.Close();
}
}
return Br;
}
public class Branch
{
public string Name { get; set; }
}
End of Service file Code----
This is coded in the Form
ServiceClient client= new ServiceClient();
test.GetAllBranchCompleted += (s, ea) =>
{
cboBranch.ItemsSource = ea.Result;
};
client.GetAllBranchAsync();
My requirement is I want to populate all the Names of the Branches that are present in my database.With this code the combobox for BranchName is getting populated but not with the Database records but something like this CRUD.ServiceReference1.ServiceBranch.
CRUD is my solution Name.
Please correct me with this..
Thanks
To get just the name to appear in your ComboBox you need to result a List<string>. Here you are returning a List<Branch>.
So you either need to rework your service code or just extract a list of strings from your ea.Result.
cboBranch.ItemsSource = ea.Result.Select(b => b.Name).ToList();
(from memory)