Calling a Method to a List - c#

So i need to pass a list from this method:
[WebMethod]
public List<SLA_ClassLibrary.SLA_Class.ReadAtm> ReadAtm()
{
var AtmReadList = new List<SLA_ClassLibrary.SLA_Class.ReadAtm>();
using (SqlConnection Conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SLAdb"].ConnectionString))
{
using (Conn)
{
Conn.Open();
string SQLReadAtm = "Select * from ATM;";
SqlCommand ReadAtmCmd = new SqlCommand(SQLReadAtm, Conn);
SqlDataReader reader = ReadAtmCmd.ExecuteReader();
while (reader.Read())
{
AtmReadList.Add(new SLA_ClassLibrary.SLA_Class.ReadAtm
{
idatm = reader.GetInt32(reader.GetOrdinal("IDATM")),
District_Region = reader.GetString(reader.GetOrdinal("District_Region")),
Local = reader.GetString(reader.GetOrdinal("Local")),
IsUp = reader.GetBoolean(reader.GetOrdinal("IsUp"))
});
}
}
return AtmReadList;
}
}
to a website table in MVC, but i'm having problems on how to go about doing this.
I can't pass the "return AtmReadList" to a List<> so i have no idea on how to do this.
Any way to do this?

Related

SQLDataReader issue with reading null values

I am having problem with SQLDataReader when it comes into situation that I have one row of data, and one or tho columns (fields) have null value.
Can anybody help with this? Null values are related to string, float and datetime datatype.
First method is:
public class SpajanjeCollection:ObservableCollection<Spajanje>
{
public static SpajanjeCollection GetAllSpajanjes()
{
SpajanjeCollection spajanjes = new SpajanjeCollection();
Spajanje spajanje = null;
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager.ConnectionStrings["ConnString"].ToString();
conn.Open();
SqlCommand command = new SqlCommand("SELECT Ponude.IdPonude, Ponude.SifraProizvoda, Proizvodi.Naziv, Proizvodi.Opis, Proizvodi.PocetnaCijena, Ponude.PocetakAukcije, Users.UserName, Ponude.PonudjenaCijena, Ponude.ZavrsetakAukcije, Ponude.Status FROM Ponude LEFT OUTER JOIN Users ON Ponude.Kupac = Users.UserName INNER JOIN Proizvodi ON Ponude.SifraProizvoda = Proizvodi.Id", conn);
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
spajanje = Spajanje.GetSpajanjeFromResultSet(reader);
spajanjes.Add(spajanje);
}
}
}
return spajanjes;
}
}
Second method for data reading is:
public static Spajanje GetSpajanjeFromResultSet(SqlDataReader reader)
{
Spajanje spajanje = new Spajanje(Convert.ToInt16(reader["IdPonude"]), Convert.ToInt16(reader["SifraProizvoda"]), Convert.ToString(reader["Naziv"]), Convert.ToString(reader["Opis"]), float.Parse(reader["PocetnaCijena"].ToString()), (DateTime?)reader["PocetakAukcije"], Convert.ToString(reader["UserName"]), float.Parse(reader["PonudjenaCijena"].ToString()), (DateTime?)reader["ZavrsetakAukcije"], Convert.ToString(reader["Status"]));
return spajanje;
}

C# SqlDataReader keeps reading

I have a method for getting data out of my SQL Server database. I'm using a reader to get all the data. The problem is that the reader keeps reading and the application doesn't pop up. It is like an infinite loop or something.
public static List<Reservering> GetReserverings()
{
Reservering res = new Reservering();
using (var conn = new SqlConnection(ConnectionString))
{
conn.Open();
const string query = "select b.boekingid, k.naam, bk.incheckdatum, bk.uitcheckdatum, b.hotelid, b.aantal_gasten from boeking b join klant k on k.klantid = b.boekingid join boekingkamer bk on b.boekingid = bk.boekingid where bk.incheckdatum is not null and bk.uitcheckdatum is not null";
SqlCommand selectReserveringen = new SqlCommand(query, conn);
SqlDataReader reader = selectReserveringen.ExecuteReader();
while (reader.Read())
{
res.Id = (int)reader["boekingid"];
res.Naam = (string)reader["naam"];
res.Incheck_datum = (DateTime)reader["incheckdatum"];
res.Uitcheck_datum = (DateTime)reader["uitcheckdatum"];
res.Hotel = (int)reader["hotelid"];
res.Aantal_personen = (int)reader["aantal_gasten"];
}
reader.Close();
}
return GetReserverings();
}
Does anyone know how to fix this problem?
You've got an infinite recursion by calling the method itself at the end:
return GetReserverings();
You could've discovered this by setting a breakpoint in your method and stepping through your code.
You want to return a list of reservations instead:
var result = new List<Reservering>();
// your code...
return result;
And within your while() loop, you'd want to instantiate a new Reservering each iteration, and Add it to the result list.
You should create an instance of Reservering for each record read and store these instances in the List<Reservering>:
public static List<Reservering> GetReserverings() {
List<Reservering> result = new List<Reservering>();
using (var conn = new SqlConnection(ConnectionString)) {
conn.Open();
const string query =
#"select b.boekingid,
k.naam,
bk.incheckdatum,
bk.uitcheckdatum,
b.hotelid,
b.aantal_gasten
from boeking b join
klant k on k.klantid = b.boekingid join
boekingkamer bk on b.boekingid = bk.boekingid
where bk.incheckdatum is not null
and bk.uitcheckdatum is not null";
using (SqlCommand selectReserveringen = new SqlCommand(query, conn)) {
using (SqlDataReader reader = selectReserveringen.ExecuteReader()) {
while (reader.Read()) {
Reservering res = new Reservering();
result.Add(res);
res.Id = Convert.ToInt32(reader["boekingid"]);
res.Naam = Convert.ToString(reader["naam"]);
res.Incheck_datum = Convert.ToDateTime(reader["incheckdatum"]);
res.Uitcheck_datum = Convert.ToDateTime(reader["uitcheckdatum"]);
res.Hotel = Convert.ToInt32(reader["hotelid"]);
res.Aantal_personen = Convert.ToInt32(reader["aantal_gasten"]);
}
}
}
}
return result;
}
Edit: You can try to simplify while loop with a help of object initializing:
...
while (reader.Read()) {
result.Add(new Reservering() {
Id = Convert.ToInt32(reader["boekingid"]),
Naam = Convert.ToString(reader["naam"]),
Incheck_datum = Convert.ToDateTime(reader["incheckdatum"]),
Uitcheck_datum = Convert.ToDateTime(reader["uitcheckdatum"]),
Hotel = Convert.ToInt32(reader["hotelid"]),
Aantal_personen = Convert.ToInt32(reader["aantal_gasten"])
});
}
public static List<Reservering> GetReserverings()
{
List<Reserving> reservings = new List<Reservings>();
using (var conn = new SqlConnection(ConnectionString))
{
conn.Open();
const string query = "select b.boekingid, k.naam, bk.incheckdatum, bk.uitcheckdatum, b.hotelid, b.aantal_gasten from boeking b join klant k on k.klantid = b.boekingid join boekingkamer bk on b.boekingid = bk.boekingid where bk.incheckdatum is not null and bk.uitcheckdatum is not null";
SqlCommand selectReserveringen = new SqlCommand(query, conn);
SqlDataReader reader = selectReserveringen.ExecuteReader();
while (reader.Read())
{
Reservering res = new Reservering();
res.Id = (int)reader["boekingid"];
res.Naam = (string)reader["naam"];
res.Incheck_datum = (DateTime)reader["incheckdatum"];
res.Uitcheck_datum = (DateTime)reader["uitcheckdatum"];
res.Hotel = (int)reader["hotelid"];
res.Aantal_personen = (int)reader["aantal_gasten"];
reservings.add(res);
}
reader.Close();
}
return reservings;
}

How can I return a stored procedure's result as XML?

I coded a web service connecting to MS-Sql server and getting the results from a stored procedure. My below code is getting only the first result of procedure, but I need all results in the response xml file. I think that I need to use data adapter, data reader, data fill, etc.. something like this. But I could not succeed. I would appreciate any help:
PS: Info.cs class already created.
[WebMethod]
public Info NumberSearch2(string no)
{
Info ourInfo = new Info();
string cs = ConfigurationManager.ConnectionStrings["DBBaglan"].ConnectionString;
using (SqlConnection Con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand(cmdText: "NumberSearch", connection: Con)
{
CommandType = CommandType.StoredProcedure
};
SqlParameter parameter = new SqlParameter
{
ParameterName = "#no",
Value = no
};
cmd.Parameters.Add(parameter);
Con.Open();
SqlDataReader dr = cmd.ExecuteReader();
DataSet ds = new DataSet();
while (dr.Read())
{
ourInfo.PartNo = dr["PartNo"].ToString();
ourInfo.BrandNo = dr["BrandNo"].ToString();
ourInfo.Manufacturer = dr["Manufacturer"].ToString();
ourInfo.Country = dr["Country"].ToString();
ourInfo.ReferenceNo = dr["ReferenceNo"].ToString();
}
}
return ourInfo;
}
After #David 's recommendation:
[WebMethod]
//public Info NumberSearch2(string no)
public List<Info> NumberSearch2(string no)
{
Info ourInfo = new Info();
var ourInfos = new List<Info>();
string cs = System.Configuration.ConfigurationManager.ConnectionStrings["DBBaglan"].ConnectionString;
using (System.Data.SqlClient.SqlConnection Con = new System.Data.SqlClient.SqlConnection(cs))
{
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(cmdText: "NumberSearch", connection: Con)
{
CommandType = System.Data.CommandType.StoredProcedure
};
System.Data.SqlClient.SqlParameter parameter = new System.Data.SqlClient.SqlParameter
{
ParameterName = "#no",
Value = no
};
cmd.Parameters.Add(parameter);
Con.Open();
System.Data.SqlClient.SqlDataReader dr = cmd.ExecuteReader();
DataSet ds = new DataSet();
while (dr.Read())
{
var ourInfos = new Info();
ourInfo.PartNo = dr["PartNo"].ToString();
ourInfo.BrandNo = dr["BrandNo"].ToString();
ourInfo.Manufacturer = dr["Manufacturer"].ToString();
ourInfo.Country = dr["Country"].ToString();
ourInfo.ReferenceNo = dr["ReferenceNo"].ToString();
ourInfos.Add(ourInfo);
}
}
return ourInfos;
}
You're returning a single Info object. If you want a collection of them, return a List<Info> instead. Change the method signature:
public List<Info> NumberSearch2(string no)
Declare the object to return:
var ourInfos = new List<Info>();
Within your loop, add each record to the list:
while (dr.Read())
{
var ourInfo = new Info();
ourInfo.PartNo = dr["PartNo"].ToString();
ourInfo.BrandNo = dr["BrandNo"].ToString();
ourInfo.Manufacturer = dr["Manufacturer"].ToString();
ourInfo.Country = dr["Country"].ToString();
ourInfo.ReferenceNo = dr["ReferenceNo"].ToString();
ourInfos.Add(ourInfo);
}
And return the list:
return ourInfos;

get all row and column data using SELECT - C#

I'm trying to get all data from an SQL table and store it in a List using the C# programming language.
the SQL statement I'm using is:
private string cmdShowEmployees = "SELECT * FROM Employees;";
This is being used in the same class as a function
public List<string> showAllIdData()
{
List<string> id = new List<string>();
using (sqlConnection = getSqlConnection())
{
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = cmdShowEmployees;
SqlDataReader reader = sqlCommand.ExecuteReader();
while (reader.Read()) {
id.Add(reader[0].ToString());
}
return id;
}
}
and here
public List<string> showAllActiveData()
{
List<string> active = new List<string>();
using (sqlConnection = getSqlConnection())
{
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = cmdShowEmployees;
SqlDataReader reader = sqlCommand.ExecuteReader();
while (reader.Read()) {
active.Add(reader[1].ToString());
}
return active;
}
I would have to create 9 more functions this way in order to get all the data out of the Employees table. This seems very inefficient and I was wondering if there was a more elegant way to do this.
I know using an adapter is one way to do it but I don't think it is possible to convert a filled adapter to a list, list list etc.
SqlDataAdapter adapter = sqlDataCollection.getAdapter();
DataSet dataset = new DataSet();
adapter.Fill(dataset, "idEmployees");
dataGridView1.DataSource = dataset;
dataGridView1.DataMember = "idEmployees";
Any ideas?
If you must use the reader in this way, why not create an object which holds the table row data.
public class SomeComplexItem
{
public string SomeColumnValue { get; set;}
public string SomeColumnValue2 { get; set;}
public string SomeColumnValue3 { get; set;}
public string SomeColumnValue4 { get; set;}
}
That way you can loop through with your reader as follows:
public List<SomeComplexItem> showAllActiveData()
{
List<SomeComplexItem> active = new List<SomeComplexItem>();
using (sqlConnection = getSqlConnection())
{
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = cmdShowEmployees;
SqlDataReader reader = sqlCommand.ExecuteReader();
while (reader.Read())
{
var someComplexItem = new SomeComplexItem();
someComplexItem.SomeColumnValue = reader[1].ToString();
someComplexItem.SomeColumnValue2 = reader[2].ToString();
someComplexItem.SomeColumnValue3 = reader[3].ToString();
active.Add(someComplexItem);
}
return active;
}
You could use two select statements to populate two List<string> as shown in the example below where the key between reads is reader.NextResult();.
The database used is the standard Microsoft NorthWind database.
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
namespace SQL_Server_TwoList
{
public class DataOperations
{
public List<string> Titles { get; set; }
public List<string> Names { get; set; }
/// <summary>
/// Trigger code to load two list above
/// </summary>
public DataOperations()
{
Titles = new List<string>();
Names = new List<string>();
}
public bool LoadData()
{
try
{
using (SqlConnection cn = new SqlConnection(Properties.Settings.Default.ConnectionString))
{
string commandText = #"
SELECT [TitleOfCourtesy] + ' ' + [LastName] + ' ' + [FirstName] As FullName FROM [NORTHWND.MDF].[dbo].[Employees];
SELECT DISTINCT [Title] FROM [NORTHWND.MDF].[dbo].[Employees];";
using (SqlCommand cmd = new SqlCommand(commandText, cn))
{
cn.Open();
SqlDataReader reader = cmd.ExecuteReader();
// get results into first list from first select
if (reader.HasRows)
{
while (reader.Read())
{
Names.Add(reader.GetString(0));
}
// move on to second select
reader.NextResult();
// get results into first list from first select
if (reader.HasRows)
{
while (reader.Read())
{
Titles.Add(reader.GetString(0));
}
}
}
}
}
return true;
}
catch (Exception)
{
return false;
}
}
}
}
Form code
namespace SQL_Server_TwoList
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DataOperations dataOps = new DataOperations();
if (dataOps.LoadData())
{
listBox1.DataSource = dataOps.Names;
listBox2.DataSource = dataOps.Titles;
}
}
}
}
You could always add it all to a dataset or datatable instead of looping through using datareader to add to an array, dataset allows you to access data in similar way to array anyway.
Connstr = "Data Source = " + SelectedIP + "; Initial Catalog = " + dbName + "; User ID = " + txtUsername.Text +"; Password = "+ txtPassword.Text +"";
conn = new SqlConnection(Connstr);
try
{
string contents = "SELECT * FROM ..."
conn.Open();
SqlDataAdapter da_1 = new SqlDataAdapter(contents, conn); //create command using contents of sql file
da_1.SelectCommand.CommandTimeout = 120; //set timeout in seconds
DataSet ds_1 = new DataSet(); //create dataset to hold any errors that are rturned from the database
try
{
//manipulate database
da_1.Fill(ds_1);
if (ds_1.Tables[0].Rows.Count > 0) //loop through all rows of dataset
{
for (int i = 0; i < ds_1.Tables[0].Rows.Count; i++)
{
//rows[rownumber][column number/ "columnName"]
Console.Write(ds_1.Tables[0].Rows[i][0].ToString() + " ");
}
}
}
catch(Exception err)
{}
conn.Close();
}
catch(Exception ex)
{}

Refactoring techniques for data access layer

I've got a data access layer to which I am binding some controls. Currently I have something along the lines of
public List<Race> GetRaces()
{
List<Race> raceList = new List<Race>();
using (var con = new SqlConnection(this.ConnectionString))
{
using (var cmd = new SqlCommand("spGetRace",con))
{
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Race r = new Race();
r.RaceId = Convert.ToInt32(rdr["raceId"]);
r.RaceDescription = rdr["RaceDescription"].ToString();
raceList.Add(r);
}
}
return raceList;
}
}
public List<Ses> GetSes()
{
List<Ses> sesList = new List<Ses>();
using (var con = new SqlConnection(this.ConnectionString))
{
using (var cmd = new SqlCommand("spGetSes",con))
{
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Ses s = new Ses();
s.SesId = Convert.ToInt32(rdr["SesId"]);
s.SesDescription = rdr["SesDescription"].ToString();
sesList.Add(s);
}
}
return sesList;
}
}
which will be bound to drop down lists in my presentation layer. Instead of having to type the lion's share of this ADO.NET code over and over, what are some useful refactoring techniques for this basic type of data access? Can I do this by refactoring with a SqlConnection, SqlCommand, and one of my custom types Race/Ses as a parameter?
public enum SqlCommandNames
{
spGetRace,
spGetSes ,
spGetOthers
}
public class myobj{
public int id {get;set;}
public string description {get;set}
}
public List<myobj> GetObj(SqlCommandNames sqlcmd)
{
List<myobj> objList = new List<myobj>();
using (var con = new SqlConnection(this.ConnectionString))
{
using (var cmd = new SqlCommand(sqlcmd.ToString(),con))
{
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
myobj r = new myobj();
r.id = = reader.GetInt32(0);
r.description = reader.IsDBNull(1) ? "" : reader.GetString(1);
objList.Add(r);
}
}
return objList;
}
}
Additional advice will be to cache lists
List<myobj> objList = (List<myobj>)HttpContext.Current.Cache[sqlcmd.ToString()];
if (objList == null)
{
List<myobj> objList = new List<myobj>();
HttpContext.Current.Cache.Insert(sqlcmd.ToString(), objList);
....
....
}
//and caching all on start up
protected void Application_Start()
{
foreach (SqlCommandNames x in Enum.GetValues(typeof(SqlCommandNames)))
{
GetObj(x);
}
}

Categories

Resources