Convert dataset into integer - c#

look i have this code:
private void obtengoUltimoComienzoColocado()
{
ManejoUsuarios lAdm = new ManejoUsuarios();
lblTodoOK.Text = lAdm.LevantoUltimoIDBarco().ToString();
}
public int LevantoUltimoIDBarco()
{
ConexionBD lP = new ConexionBD();
try
{
string lQuery = "Select Max(idBarco) as UltimoID From Comienzos;";
Convert.ToInt32(lP.ObtenerRegistro(lQuery));
return 1;
}
catch (Exception ex)
{
return 0;
}
}
public DataSet ObtenerRegistro(string SqlQuery)
{
DataSet lResult;
SqlConnection lSqlConnection = new SqlConnection("Data Source=SEBA-PC\\sqlexpress;Initial Catalog=Batalla_Naval;Integrated Security=True");
SqlCommand lSqlCommand = null;
try
{
lSqlCommand = new SqlCommand();
lSqlCommand.CommandText = SqlQuery;
lSqlCommand.CommandType = CommandType.Text;
SqlDataAdapter lAdapter = new SqlDataAdapter(lSqlCommand);
lResult = new DataSet();
lSqlConnection.Open();
lSqlCommand.Connection = lSqlConnection;
lAdapter.Fill(lResult);
}
catch (Exception)
{
throw;
}
finally
{
lSqlConnection.Close();
}
return lResult;
}
As you can see i use three functions to go to the database and get the max ID from the table Comienzos, but when i want to convert the data set to int32 the function LevantoUltimoIDBarco returns me 0,

You have to select the first value from the dataset, you can not convert a complete dataset to integer:
Convert.ToInt32(lP.ObtenerRegistro(lQuery).Tables[0].Rows[0][0]);
or simpler (since the query returns an integer in the dataset):
(Int32)(lP.ObtenerRegistro(lQuery).Tables[0].Rows[0][0]);
And then you have to return or save the result instead of just returning 1.

My friend you should use ExecuteScalar to return a single value, and not an adapter and fill a dataset.
SqlConnection lSqlConnection = new SqlConnection("Data Source=SEBA-PC\\sqlexpress;Initial Catalog=Batalla_Naval;Integrated Security=True");
SqlCommand lSqlCommand = null;
try
{
lSqlCommand = new SqlCommand();
lSqlCommand.CommandText = SqlQuery;
lSqlCommand.CommandType = CommandType.Text;
var result = lSqlCommand.ExecuteScalar();
int MyID = Convert.ToInt32(result);
}
catch(ex)
{
// DO SOMETHING
}

Looking at how you retrieve your data, then the correct code to read that integer (MAX()) is the following
string lQuery = "Select Max(idBarco) as UltimoID From Comienzos;";
DataSet ds = lP.ObtenerRegistro(lQuery);
return Convert.ToInt32(ds.Tables[0].Rows[0][0] == DBNull.Value ? 0 : ds.Tables[0].Rows[0][0]);
However, if your table has no record the MAX(idBarco) will return DBNull as result

Related

How do i execute a stored procedure in wcf module c#

I am creating a wcf module that i would like to execute a stored procedure and return the results. This is what i have so far
public static class Provder
{
private const string CommandSchema_FullName = "Table3";
public static IEnumerable<ProviderModel> Get(Func<ProviderModel> )
{
var query = new StringBuilder();
query.AppendFormat("SELECT * FROM {0}", CommandSchema_FullName);
if (criteria != null)
return ExecuteQuery(query.ToString()).Where(criteria).ToArray();
return ExecuteQuery(query.ToString());
//i can read from a table like above,im not sure how to add in a new stored procedure that i would like to call
}
private static IEnumerable<ProviderModel> ExecuteQuery(string query)
{
var result = new List<ProviderModel>();
using (var sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["netTiersConnectionString"].ToString()))
{
sqlConnection.Open();
var reader = new SqlCommand(query, sqlConnection).ExecuteReader();
while (reader.Read())
{
result.Add(new ProviderModel
{
});
}
sqlConnection.Close();
}
return result;
}
private static bool ExecuteCommand(string command)
{
var result = false;
using (var sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["netTiersConnectionString"].ToString()))
{
sqlConnection.Open();
try
{
var recordsAffected = new SqlCommand(command, sqlConnection).ExecuteNonQuery();
result = true;
}
catch (SqlException)
{
result = false;
}
finally
{
sqlConnection.Close();
}
}
return result;
}
}
public class ProviderModel
{
}
This is the stored procedure i want to call in the above methods
CREATE PROCEDURE GetListCodes
AS
BEGIN
select concat(p.CourseName,s.LeagueTitle,' ',p.Abbreviation) As Result,p.ProgramCode
FROM Table1 p inner join Table2 s on p.Code=s.Code
END
GO
I am not sure how to call the sp GetListCodes in the above wcf model. I dont have any parameters to pass,i would just like to execute the stored procedure and get the results.
What you need to exceute a store procedure, on the command is a simple line
cmd.CommandType = CommandType.StoredProcedure;
In your case, you would have to replace the line
var recordsAffected = new SqlCommand(command,
sqlConnection).ExecuteNonQuery();
with
var cmd= new SqlCommand(command, sqlConnection);
cmd.CommandType = CommandType.StoredProcedure;
var recordsAffected = cmd.ExecuteNonQuery();
There is a nice little tutorial you can find at https://csharp-station.com/Tutorial/AdoDotNet/Lesson07
And Miscrosoft also has an article located at https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/executing-a-command

How can I return/How can I convert dataset to a list of objects (List<ComponenetData>) in C#?

How can I return/How can I convert dataset to a list of objects (List) in C#?
public static DataSet GetComponentData(int CustomerId, int UserId)
{
string connectionString = ConfigurationReader.ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand command = new SqlCommand("GetComponentData", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#CustomerID", SqlDbType.Int).Value = CustomerId;
command.Parameters.Add("#UserId", SqlDbType.Int).Value = UserId;
da.SelectCommand = command;
try
{
da.Fill(ds);
connection.Close();
return ds;
}
catch (Exception ex)
{
string strError = ex.ToString();
return ds = null;
}
finally
{
da = null;
command = null;
connection.Close();
}
}
}
I need to return the result as a list eg.List. I have done this by :
public static string GetGenericListData(string folderName, int CustomerId)
{
//--------------------------------------------------------
// List<Device>lstDevices=new List<Device>();
Devices lstDevices = new Devices();
DataSet ds=new DataSet();
try
{
ds = GetComponentData(CustomerId, UserId);
if(ds.Tables[0].Rows.Count >0)
{
foreach(DataRow dr in ds.Tables[0].Rows)
{
Device _PptDevices=new Device();
_PptDevices.Country = ((dr["Country"]) != null) ? Convert.ToString(dr["Country"]) : "";
_PptDevices.Area = ((dr["Area"]) != null) ? Convert.ToString(dr["Area"]) : "";
_PptDevices.Branch = ((dr["Branch"]) != null) ? Convert.ToString(dr["Branch"]) : "";
_PptDevices.SalesOffice = ((dr["Sales Office"]) != null) ? Convert.ToString(dr["Sales Office"]) : "";
_PptDevices.CustomerNumber = ((dr["Customer Number"]) != null) ? Convert.ToString(dr["Customer Number"
lstDevices.Add(_PptDevices);
_PptDevices = null;
}
}
}
catch
{
}
finally
{
}
string strStatus = "";
if (lstDevices.Count > 0)
{
string FilePath = ConfigurationReader.FileLocation;
XmlSerializer serializer = new XmlSerializer(typeof(Devices));
MemoryStream memStream = new MemoryStream();
serializer.Serialize(memStream, lstDevices);
FileStream file = new FileStream (folderName "\\ComponentData.xml", FileMode.Create, FileAccess.ReadWrite);
memStream.WriteTo(file);
file.Close();
strStatus = "1"; //Success
}
else
{
strStatus = "0"; //Failure
}
return strStatus;
}
Here what I am doing is getting dataset from one function and converting it as a list using another function. Is there any direct method to convert dataset to list more easier? Or how can we assign the result set directly to the list..
Is there any other simple solution?
Let the Student be the class, then you can do something like the following:
dTable = ds.Tables[0];
List<Device> studentList=dTable.AsEnumerable().Select(x => new Device() {
Country =x["column_id"]!=null?x.Field<string>("column_id"):"",
Area = x["Area"]!=null?x.Field<string>("Area"):""
Branch = x["Branch"]!=null?x.Field<string>("Branch"):"",
SalesOffice = x["Sales Office"]!=null?x.Field<string>("Sales Office"):"",
CustomerNumber = x["Customer Number"]!=null?x.Field<string>("Customer Number"):""
}).ToList();
You don't even need to convert it to DataSet if you are interested in List<>, you could directly convert it from reader.
var reader = command.ExecuteReader();
var list = reader.Select(r => new Propertyclass() // specify the class name
{
Id = r["id"] is DBNull ? null : r["id"].ToString(),
Name = r["name"] is DBNull ? null : r["name"].ToString()
})
.ToList();

I need a Common function to fill combobox using stored procedure in WPF

I need a common method for filling combobox from database with a default value.
Try this method....I think this will help you
public bool fillComboBox(System.Windows.Controls.ComboBox combobox, string procedureName, string dTable, string dDisplay, string dValue, string defaultValue)
{
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter sqladp = new SqlDataAdapter();
DataSet ds = new DataSet();
try
{
using (SqlConnection _sqlconTeam = new SqlConnection(DBCon.conStr))
{
sqlcmd.Connection = _sqlconTeam;
sqlcmd.CommandType = CommandType.StoredProcedure;
sqlcmd.CommandText = procedureName;
_sqlconTeam.Open();
sqladp.SelectCommand = sqlcmd;
sqladp.Fill(ds, dTable);
DataRow nRow = ds.Tables[dTable].NewRow();
nRow[dDisplay] = defaultValue;
nRow[dValue] = "-1";
ds.Tables[dTable].Rows.InsertAt(nRow, 0);
combobox.ItemsSource = ds.Tables[dTable].DefaultView;
combobox.DisplayMemberPath = ds.Tables[dTable].Columns[1].ToString();
combobox.SelectedValuePath = ds.Tables[dTable].Columns[0].ToString();
combobox.SelectedIndex = 0;
}
return true;
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
return false;
}
finally
{
sqladp.Dispose();
sqlcmd.Dispose();
}
}

Assign DataSet to Local Variables

I am running a SQL Query and returning a DataSet - I want to iterate the info in the DataSet and assign the values to local variables. I have confirmed that my DataSet returns rows but my variables are not getting assigned for some reason. Can someone look at my syntax and assist with why this is occurring?
protected void GetSomeData()
{
string employeeid = this.txtemployeeid.Text;
DataSet empinfo = new DataSet();
empinfo = RunSqlQuery(employeeid);
this.txtemployeefirstname = empinfo.Tables[0].Rows[0]["employeefirstname"].ToString());
this.txtemployeelastname = empinfo.Tables[0].Rows[1]["employeelastname"].ToString());
this.txtemployeeaddress = empinfo.Tables[0].Rows[2]["employeeaddress"].ToString());
this.txt.employeephone = empinfo.Tables[0].Rows[3]["employeephone"].ToString());
}
public DataSet RunSqlQuery(string employeeid)
{
string sqlQuery = "Select employeefirstname, employeelastname, employeeaddress, employeephone from abcd where employeeid = "+employeeid+" and employeeid is not null";
try
{
connectionString = System.Configuration.ConfigurationManager.AppSettings[connectionString].ToString();
sqlDatabaseConnection = new SqlConnection(connectionString);
sqlCommand = new SqlCommand(sqlQuery, sqlDatabaseConnection);
sqlDatabaseConnection.Open();
sqlCommand.CommandTimeout = 0;
dataSet = new DataSet();
sqlDataAdapter = new SqlDataAdapter(sqlCommand);
sqlDataAdapter.Fill(dataSet, "Data");
return dataSet;
}
catch (Exception exception)
{
throw exception;
}
finally
{
sqlDatabaseConnection.Close();
sqlCommand.Dispose();
sqlDataAdapter.Dispose();
}
}
EDIT
By variables not getting assigned, I mean when I step through my code, it seems that the value returned from the database is not being populated into the empinfo.Tables[0].Rows[0]["employeefirstname"].ToString()); they are always null.
You're assigning the value to the textbox (at least, I assume txtemployeefirstname is a textbox). I think you mean txtemployeefirstname.text?

How to get data from DB, store as List<>, and display the results to view

I am trying to get data as a list from the database but it is not showing any results. I tried to debug but after this line it doesn't let me to step over / F10:
DataSet ds = new DataSet();
da.Fill(ds);
I am trying to do this by following this example on here: link 1 and here link 2 but finding it difficult hence I thought that I should ask here.
Can someone please explain why it is not displaying the results and as such what I may be doing wrong here? how do I work around and achieve it to display the data?
Here's the full controller code for your inspection:
public static List<DBTrack> GetListOfTracks()
{
if (DBTrackData == null)
{
string myConnectionString = "Data Source="; // I have taken off the source
string mySelectString = "SELECT TrackID, AddedDate, TrackName, ArtistName from TBL_Track";
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
da.Fill(ds);
OleDbConnection myConnection = new OleDbConnection(myConnectionString);
OleDbCommand myCommand = new OleDbCommand(mySelectString, myConnection);
myCommand.Connection.Open();
OleDbDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
List<DBTrack> list = new List<DBTrack>();
while (myReader.Read())
{
DBTrack data = new DBTrack();
data.TrackID = (Guid)(myReader["TrackID"]);
data.AddedDate = (DateTime)myReader["AddedDate"];
data.TrackName = (string)myReader["TrackName"];
data.ArtistName = (string)myReader["ArtistName"];
list.Add(data);
};
}
return DBTrackData;
}
EDIT:
SqlConnection mySQLconnection = new SqlConnection(#"Data Source=server-2\SQLExpress;Initial Catalog=End;Integrated Security=False;User ID=test1;Password=**");
SqlCommand mySelectString = new SqlCommand("SELECT TrackID, AddedDate, TrackName, ArtistName from TBL_Track");
using (SqlConnection connection = new SqlConnection("context connection=true"))
{
connection.Open();
using (SqlCommand myCommand = new SqlCommand // The best overload method System.Data.SqlClient.SqlCommand.SqlCommand has some invalid arguments
(mySelectString, mySQLconnection)) // Cannot convert from System.Data.SqlClient.SqlCommand to 'string'
{
You should set the DBTrackData to the result of the list:
while (myReader.Read())
{
...
}
DBTrackData = list;
You could also directly edit the DBTrackData in your code:
private static List<DBTrack> DBTrackData
public static List<DBTrack> GetListOfTracks()
{
if (DBTrackData == null)
{
...
DBTrackData = new List<DBTrack>();
while (myReader.Read())
{
DBTrack data = new DBTrack();
...
DBTrackData.Add(data);
};
}
return DBTrackData;
}
So, in full it should be:
public static List<DBTrack> GetListOfTracks()
{
try
{
if (DBTrackData == null)
{
string myConnectionString = "Data Source="; // I have taken off the source
string mySelectString = "SELECT TrackID, AddedDate, TrackName, ArtistName from TBL_Track";
using (OleDbConnection myConnection = new OleDbConnection(myConnectionString))
{
myConnection.Open();
using (OleDbCommand myCommand = new OleDbCommand(mySelectString, myConnection))
{
OleDbDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
List<DBTrack> list = new List<DBTrack>();
while (myReader.Read())
{
DBTrack data = new DBTrack();
data.TrackID = (Guid)(myReader["TrackID"]);
data.AddedDate = (DateTime)myReader["AddedDate"];
data.TrackName = (string)myReader["TrackName"];
data.ArtistName = (string)myReader["ArtistName"];
list.Add(data);
}
DBTrackData = list;
}
}
}
return DBTrackData;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return DBTrackData;
}
Your main problem is that you are using two different ways of getting the data, but the first is only partially implemented. You are using a data adapter and a data reader. Your data adapter isn't even being passed a connection or query, so this is why it is not working. So you can just remove that part of the code.
It's also easier to read if you immediately return when DBTrackData is not null rather than have a big if block over the whole code. You will then have something like:
public static List<DBTrack> GetListOfTracks()
{
if (DBTrackData != null) return DBTrackData;
string myConnectionString = "Data Source="; // I have taken off the source
string mySelectString = "SELECT TrackID, AddedDate, TrackName, ArtistName from TBL_Track";
OleDbConnection myConnection = new OleDbConnection(myConnectionString);
OleDbCommand myCommand = new OleDbCommand(mySelectString, myConnection);
myCommand.Connection.Open();
OleDbDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
List<DBTrack> list = new List<DBTrack>();
while (myReader.Read())
{
DBTrack data = new DBTrack();
data.TrackID = (Guid)(myReader["TrackID"]);
data.AddedDate = (DateTime)myReader["AddedDate"];
data.TrackName = (string)myReader["TrackName"];
data.ArtistName = (string)myReader["ArtistName"];
list.Add(data);
};
//Setting DBTrackData means these values will get returned on every call to GetListOfTracks for this instance of the class
DBTrackData = list;
return list;
}

Categories