.NET run stored procedure, get output - asp.net

I am running this stored procedure with .NET like so:
public List<showWhatClass> showWhatMethod(string deviceWhat, int tagWhat, Decimal latit, Decimal longit, int Process, string CallNext, int CallNextVar)
{
showWhatCell = new List<showWhatClass>();
try
{
using (connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand("iosShowWhat", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#DeviceId", deviceWhat);
command.Parameters.AddWithValue("#TagId", tagWhat);
command.Parameters.AddWithValue("#Latitude", latit);
command.Parameters.AddWithValue("#Longitude", longit);
command.Parameters.AddWithValue("#Process", Process);
command.Parameters.AddWithValue("#CallNext", CallNext);
command.Parameters.AddWithValue("#CallNextVar", CallNextVar);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
showWhatClass item = new showWhatClass();
item.CallNext = reader.GetValue(0).ToString();
item.CallNextVar = (int)reader.GetValue(1);
showWhatCell.Add(item);
}
}
}
}
finally
{
connection.Close();
}
return showWhatCell;
}
The stored procedure returns the following message:
When I run this I get the following returned:
<ArrayOfshowWhatClass xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/WebServiceAPI.Models"/>
which is empty
my question is what am I doing wrong, how come nothing is returning when I run this with .NET but does return the message in SQL Server.
Here is my showWhatClass
public class showWhatClass
{
public string CallNext { get; set; }
public int CallNextVar { get; set; }
}

Try to change your parameters:
command.Parameters.AddWithValue("#DeviceId", deviceWhat);
to the following:
command.Parameters.Add("#DeviceId", SqlDbType.Int).Value = deviceWhat;

Related

Web API to query SQL Server and return result is not working as expected

I am trying to connect to SQL Server from the Web API and return a result set as JSON. But my code shown here is not working as expected. I am trying to return the entire query response as a JSON:
[HttpGet]
public HttpResponseMessage Getdetails(string ROOM)
{
string commandText = "SELECT * from [TDB].[dbo].[results_vw] where ROOM = #ROOM_Data";
string connStr = ConfigurationManager.ConnectionStrings["TDBConnection"].ConnectionString;
var jsonResult = new StringBuilder();
using (SqlConnection connection = new SqlConnection(connStr))
{
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.Add("#ROOM_Data", SqlDbType.VarChar);
command.Parameters["#ROOM_Data"].Value = ROOM;
connection.Open();
var reader = command.ExecuteReader();
if (!reader.HasRows)
{
jsonResult.Append("[]");
}
else
{
while (reader.Read())
{
jsonResult.Append(reader.GetValue(0).ToString());
}
}
var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
response.Content = new StringContent(jsonResult.ToString());
connection.Close();
return response;
}
}
This code returns this result:
333838362692368203368203368203362692368203359544362692368203362692368203362692368203368203
Where I am expecting the JSON as
{"data":
[
{"R_ID":"368203","ROOM":"K2"},
{"R_ID":"368203","ROOM":"K2"}
]}
Now I created a model class called DatabaseResult to store the response but I am not sure how I can store the result in to the model class in the controller
public class DatabaseResult
{
public int r_id { get; set; }
public string room { get; set; }
}
The current result is because you are only return the the value from the first column of each row and adding it to the string builder.
Create a new instance of the model and populate it using the values from the reader for each row.
[HttpGet]
public IHttpActionResult Getdetails(string ROOM) {
string commandText = "SELECT * from [TDB].[dbo].[results_vw] where ROOM = #ROOM_Data";
string connStr = ConfigurationManager.ConnectionStrings["TDBConnection"].ConnectionString;
var jsonResult = new StringBuilder();
using (SqlConnection connection = new SqlConnection(connStr)) {
using (SqlCommand command = new SqlCommand(commandText, connection)) {
command.Parameters.Add("#ROOM_Data", SqlDbType.VarChar);
command.Parameters["#ROOM_Data"].Value = ROOM;
connection.Open();
List<DatabaseResult> records = new List<DatabaseResult>();
using (var reader = command.ExecuteReader()) {
while (reader.Read()) {
var row = new DatabaseResult {
r_id = (int)reader["r_id"],
room = (string)reader["room"],
//...other properties.
};
records.Add(row);
}
return Ok(records);
}
}
}
}
The above uses the column names as the indexer to get the values from the reader.

Chnage format return of DotNet

I created web API using dotNet. It work but i got a little problem.
This is my controller
WaybillDataAccessLayer objway = new WaybillDataAccessLayer();
public IEnumerable<Waybill> Get(string id_wb)
{
List<Waybill> lstWaybill = new List<Waybill>();
lstWaybill = objway.GetWaybill(id_wb).ToList();
return lstWaybill;
}
and my Models(WaybillDataAccessLayer)
public IEnumerable<Waybill> GetWaybill(String id_wb)
{
List<Waybill> lswaybill = new List<Waybill>();
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("spGetWaybill", con); //Stored procedure on database
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#waybill", id_wb);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read()) //foreach
{
Waybill wb = new Waybill();
wb.waybill = rdr["waybill"].ToString();
wb.deskripsi = rdr["deskripsi"].ToString();
wb.tanggal = rdr["tanggal"].ToString();
wb.pengirim = rdr["pengirim"].ToString();
wb.lokasi = rdr["lokasi"].ToString();
wb.penerima = rdr["penerima"].ToString();
lswaybill.Add(wb);
}
con.Close();
}
return lswaybill;
}
when i run this API,the output will be like this
[
{
"waybill": "00000093",
"deskripsi": "SPARE PARTS",
"tanggal": "19990727",
"pengirim": "JIEP",
"lokasi": "HO",
"penerima": "JKHO"
}
]
My Question is
how to remove that [] ?
how to add another information like
{
"status" : "sucess",
"data" { }
}
Thankyou for your help.
You're returning a list of WayBill objects. If you don't want the resulting JSON to be an array, then you need to just return a single WayBill, not a List. And if you want to wrap that in more data, then create a type to represent that information, populate an instance of it, and return it.
Since you're retrieving these objects by ID, I'm assuming there should be only one WayBill for any given ID. Thus you can simplify your data access layer.
public Waybill GetWaybill(String id_wb)
{
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand("spGetWaybill", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#waybill", id_wb);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
rdr.Read();
Waybill wb = new Waybill();
wb.waybill = rdr["waybill"].ToString();
wb.deskripsi = rdr["deskripsi"].ToString();
wb.tanggal = rdr["tanggal"].ToString();
wb.pengirim = rdr["pengirim"].ToString();
wb.lokasi = rdr["lokasi"].ToString();
wb.penerima = rdr["penerima"].ToString();
return wb;
}
}
And add the type to wrap your response:
class GetWayBillResponse()
{
public string Status { get; set;}
public WayBill WayBill { get; set; }
}
Note that adding a status here isn't really all that helpful if you're seeing the object, you can assume it was successful. Also, the API would have responded with an HTTP 200 OK status code. So it's really superfluous.
Now your controller becomes:
WaybillDataAccessLayer objway = new WaybillDataAccessLayer();
public GetWayBillResponse Get(string id_wb)
{
GetWayBillResponse response = new GetWayBillResponse();
response.Status = "Success";
response.WayBill = objway.GetWaybill(id_wb);
return response;
}
Note that you can simplify your data access even further. You're manually assigning the result columns to the WayBill object. That's repetitive and boring. If you use an Object Relational Mapper such as Dapper, you can remove a lot of that boiler plate code.
Here's what it'd look like using Dapper:
public Waybill GetWaybill(String id_wb)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
return con.QuerySingle<WayBill>("spGetWaybill", new { waybill = id_web }, commandType: CommandType.StoredProcedure);
}
}

web service page System.IndexOutOfRangeException

public class GetAreaFromCity : System.Web.Services.WebService
{
[WebMethod]
public GetAreaByCityId ClassForGetCIty(int City_Id)
{
string CS =ConfigurationManager.ConnectionStrings["FOODINNConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("spGetCityById",con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter parameter = new SqlParameter("#ID", City_Id);
//To assiate this parameter object with cmd object
cmd.Parameters.Add(parameter);
GetAreaByCityId GETAreaByCityId =new GetAreaByCityId();
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
//as WeakReference read data wewant ToString retrive Column value & then polute this property City_Id values
while (reader.Read()){
GETAreaByCityId.City_Id = Convert.ToInt32(reader["City_Id"]);
GETAreaByCityId.Area_Id = Convert.ToInt32(reader["Area_Id"]);
}
return GETAreaByCityId;
//ToString return sql
}
}
}
that's my codes for service page
public class GetAreaByCityId
{
public int Ca_Id {get;set; }
public int City_Id { get; set; }
public int Area_Id { get; set; }
}
that's the class for getting the Area by city
Create Proc [dbo].[spGetCityById]
#ID int
as
Begin
Select Area_Id from
CITIES_AREA where City_Id = #ID
End
GO
and above the database procedure which is data can be retrieve
System.IndexOutOfRangeException: City_Id
at System.Data.ProviderBase.FieldNameLookup.GetOrdinal(String fieldName)
at System.Data.SqlClient.SqlDataReader.GetOrdinal(String name)
at System.Data.SqlClient.SqlDataReader.get_Item(String name)
at WebApplication1.GetAreaFromCity.ClassForGetCIty(Int32 City_Id) in c:\Users\Mudassir\Documents\Visual Studio 2013\Projects\WebApplication1\WebAppli
the above error i dont know whats the problem
Your stored procedure is returning only Area_Id. Your code in the "while loop" while (reader.Read()){ is attempting to read data from two columns:
City_Id
Area_Id
You could add the column City_Id to the result set for your stored procedure query, BUT you already have that value because you are passing it to the stored procedure as a parameter.
Easiest fix is probably to just change this line:
GETAreaByCityId.City_Id = Convert.ToInt32(reader["City_Id"]);
to this:
GETAreaByCityId.City_Id = City_Id;

Losing first record and the values keep changing when loading reader to datatable

I load reader to my table like this
connection.Open();
sqlCmd = new SqlCommand(sqlCmd.CommandText, connection);
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
DataTable dt = new DataTable();
sqlReader.Read();
dt.Load(sqlReader);
But it looks like I cannot retrieve the first record of fetch data.
The second problem is when I call the reader several times after that:
string comName = dt.Rows[0]["companyName"].ToString();
//To get address
sqlCmd.CommandText = addr;
sqlCmd.Parameters.AddWithValue("companyName", comName);
using (var addressReader = sqlCmd.ExecuteReader())
{
if (addressReader.Read())
{
Label1.Text = Label1.Text + " " + addressReader["address"].ToString();
}
}
//To get keyProcesses
sqlCmd.Parameters.Clear();
sqlCmd.CommandText = keyProcesses;
sqlCmd.Parameters.AddWithValue("companyName", comName);
using (var keyProcessesReader = sqlCmd.ExecuteReader())
{
if (keyProcessesReader.Read())
{
Label1.Text = Label1.Text + " " + keyProcessesReader.GetString(0);
}
}
But I find out that these reading also may changes the value of my datatable dt above! How could I only load data to dt at the first reading and keep it there without changing any more ?
Ps: In attempt to overcome the second problem, I am trying to store dt values in list
public class CompanyModel
{
public string compnName { get; set; }
public string compnAddress { get; set; }
public string compnKeyProcesses { get; set; }
public string compnStandards { get; set; }
}
then
List<CompanyModel> companies = new List<CompanyModel>();
for(int i = 0; i < dt.Rows.Count; i++)
{
companies.Add(new CompanyModel
{
compnName = dt.Rows[i]["companyName"].ToString(),
compnAddress = dt.Rows[i]["address"].ToString()
});
}
companyRepeater.DataSource = companies;
companyRepeater.DataBind();
Now, how do I access each company name in the list to make query on that name value accordingly, then input the new result to the list?
I tried:
foreach(List<Component> compnName in companies.Contains("companyName")
{
sqlCmd.CommandText = getKey;
sqlCmd.Parameters.AddWithValue("companyName", compnName);
using (var keyReader = sqlCmd.ExecuteReader())
{
if (keyReader.Read())
{
companies.Add(new CompanyModel compnKeyProcesses = keyReader.GetString("key"));
}
}
sqlCmd.CommandText = getstandard;
sqlCmd.Parameters.AddWithValue("companyName", compnName);
using (var standardReader = sqlCmd.ExecuteReader())
{
if (standardReader.Read())
{
companies.Add(new CompanyModel compnStandards = keyReader.GetString("standards"));
}
}
Try this for your first problem
SqlDataAdapter sdr = new SqlDataAdapter(sqlCmd.CommandText, connection);
DataTable dt=new DataTable();
sdr.Fill(dt);
you can display this whole data as a matter of confirmation by taking a datagridview
dataGridView1.DataSource=dt;

Asp.Net: Returning a DataSet from a Class

I've decided to start another thread based on the responses I got in this thread:
Asp.Net: Returning a Reader from a Class
I was returning a reader, but members have suggested I'd be better off returning a Dataset instead and also try to seperate the data access tier from the presentation tier.
This is what I have so far:
//my class methods
public DataSet GetSuppliers()
{
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("con_spSuppliersList", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#blogid", HttpContext.Current.Request.QueryString["p"]);
return FillDataSet(cmd, "SuppliersList");
}
//my FillDataSet method
private DataSet FillDataSet(SqlCommand cmd, string tableName)
{
SqlConnection conn = new SqlConnection(connectionString);
cmd.Connection = conn;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
adapter.Fill(ds, tableName);
}
finally
{
conn.Close();
}
return ds;
}
// on my ascx page I call the method like so:
protected void Page_Load(object sender, EventArgs e)
{
//instantiate our class
MyClass DB = new MyClass();
// grab the table of data
DataTable dt = DB.GetSuppliers().Tables["SuppliersList"];
//loop through the results
foreach (DataRow row in dt.Rows)
{
this.supplierslist.InnerHtml += Server.HtmlEncode(row["Address"].ToString()) + "<br/>";
this.supplierslist.InnerHtml += "<b>Tel: </b>" + Server.HtmlEncode(row["Telephone"].ToString()) + "<p/>";
}
}
}
Would anyone like to suggest improvements?
Is my loop 'data tier' or 'presentation tier', should the loop be inside the class and I just return a formatted string instaed of a dataset?
Thanks for all the great advice
I also would use a Typed DataSet or create your own class that holds the properties so you are not dealing with strings like row["Address"] you would say object.Address and get compile time checking.
DataSets have a lot of built in functionality that is nice but also caries with it a lot of overhead that might not be needed in something simple. Creating a simple class with properties and passing that out of your data access layer is probably the simplest way to implement what you want.
Something like this on the DAL (Data Access Layer) side:
//Also pass in the blogID dont have the DAL get the value from the UI layer..
//make the UI layer pass it in.
public IList<Supplier> GetSuppliers(string connectionString, int blogID)
{
IList<Supplier> suppliers = new List<Supplier>();
//wrap with the using statements
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("con_spSuppliersList", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#blogid", blogID);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
suppliers.Add(new Supplier
{
Address = reader.GetString(0),
Telephone = reader.GetString(1)
});
}
}
}
return suppliers;
}
}
public class Supplier
{
//I would have Address an object....but you have as string
//public Address Address { get; set; }
public string Address { get; set; }
public string Telephone { get; set; }
}
//Example if you went with Address class...
public class Address
{
//Whatever you want in the address
public string StreetName { get; set; }
public string Country { get; set; }
public string Region { get; set; }
public string City { get; set; }
}
One thing you should get in the habit of doing is calling Dispose() on your SqlConnection. The best pattern to do this is to use the using statement, which will automatically dispose of it for you. It looks like this:
private DataSet FillDataSet(SqlCommand cmd, string tableName)
{
using(SqlConnection conn = new SqlConnection(connectionString))
{
cmd.Connection = conn;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
conn.Open();
adapter.Fill(ds, tableName);
}
finally
{
conn.Close();
}
return ds;
}
}
What you have in the foreach loop in Page_Load, is presentation logic (layout), and IMO this should not be in the code-behind of your page, but in the markup.
I'd suggest that instead of using a foreach loop to construct the HTML output, you should use a databound control (such as a asp:Repeater, DataList or GridView). Then you can bind the repeater to your dataset or datatable and have all the markup where it belongs (in the ASCX file). See this page for an example.
As a general note: you can find lots of tutorials on www.asp.net, e.g. about data access: http://www.asp.net/%28S%28pdfrohu0ajmwt445fanvj2r3%29%29/learn/data-access/

Resources