SQL Data Reader into Label - Value doesn't display - sql

DB-Acess.cs
This is where the Public SqlDataReader getEmail is initialised.
public SqlDataReader getEmail(string UserName)
{
if (conn.State.ToString() == "Closed")
{
conn.Open();
}
//string noemail ="noemailsaved";
SqlCommand newCmd = conn.CreateCommand();
newCmd.Connection = conn;
newCmd.CommandType = CommandType.Text;
newCmd.CommandText = "Select Email from dbo.EMPLOYEE where Username ='" + UserName + "'";
SqlDataReader reader = newCmd.ExecuteReader();
while (reader.Read())
{
string email = reader["EMPLOYEE.Email"].ToString();
}
conn.Close();
reader.Close();
return reader;
}
I'm using OOP and calling the function in asp.net page and want to display the value in a label. Below is the code I'm using to call the function.
SqlDataReader reader = dba.getEmail(pname);
lblEmail.Text = reader.ToString();
lblEmail.DataBind();
Instead of seeing the Email address of the Employee i'm seeing System.Data.SqlClient.SqlDataReader
Please help in correcting this error.
Thank you in advance.

So there are so many issues going on, I decided to write this comment as the beginning to an appropriate solution.
First your method is called getEmail -- shouldn't it return the email (in other words, a string instead).
public string GetEmail(string UserName)
{
string email = string.Empty;
if (conn.State.ToString() == "Closed")
{
conn.Open();
}
//string noemail ="noemailsaved";
SqlCommand newCmd = conn.CreateCommand();
newCmd.Connection = conn;
newCmd.CommandType = CommandType.Text;
newCmd.CommandText = "Select Email from dbo.EMPLOYEE where Username ='" + UserName + "'";
SqlDataReader reader = newCmd.ExecuteReader();
while (reader.Read())
{
email = reader["EMPLOYEE.Email"].ToString();
}
conn.Close();
reader.Close();
return email;
}
Then all you have to do is:
lblEmail.Text = db.GetEmail(pname);
That should at least get you going. You should also look into using parameterized queries as well as the using statement.
Why do we always prefer using parameters in SQL statements?

There are a few things going wrong here:
1) You are setting the string email to the value of the reader. Which because you are declaring it inside the reader, will never be able to be used. You will lose scope immediately.
2) You are doing this:
lblEmail.Text = reader.ToString();
lblEmail.DataBind();
This is setting the label to the name of the reader (the instance), not the value the reader is producing. No reason to bind, either.
A better way to do it is
lblEmail.Text = email;
Make sure you declare the email variable outside the reader

ERRORS
Return type of the function getEmail is SqlDataReader and you are expecting String i.e. an Email.
Declaration of email in string email = reader["EMPLOYEE.Email"].ToString(); is inside while loop. Therefore, email becomes local to the while loop. It will not recognize outside the loop.
And you are returning reader' an instance ofSqlDataReader,but you were expecting aString`.
In you second code block, what your doing is not wrong(it won't give error) but that is not what you are expecting to get. You should be declaring a String variable eg. email and assign the function to it(or you can directly assign it to lblEmail Text property.
SUGGESTION
The way you are checking ConnectionState in if(conn.State.ToString() == "Closed") may give you the desired result but is not recommended. Instead you should check like this if (conn.State == ConnectionState.Closed).
Now the most awaiting part: The improvised code: lol!
UPDATE
public string getEmail(string UserName){
if (conn.State == ConnectionState.Closed){
conn.Open();
}
//string noemail ="noemailsaved";
string email="";
using(SqlCommand newCmd = new SqlCommand()){
newCmd.Connection = conn;
newCmd.CommandType = CommandType.Text;
newCmd.CommandText = "Select Email From dbo.EMPLOYEE Where Username = #uname";
newCmd.Parameters.AddWithValue("#uname",UserName);
using(SqlDataReader reader = newCmd.ExecuteReader()){
while (reader.Read()){
email = reader["Email"].ToString();
}
}
}
conn.Close();
//reader.Close();
return email ;
}
For setting the Label Text
lblEmail.Text = dba.getEmail(pname);

Yes that's cause you are calling ToString() on reader object and thus it just printing the classname fully qualified reader.ToString().
Moreover, you are dong it wrong. Current code shouldn't work since you are returning reader which has already been closed and thus you can't read from it. Rather, you should change your method to return the email and use it like
public string getEmail(string UserName)
{
if (conn.State.ToString() == "Closed")
{
conn.Open();
}
//string noemail ="noemailsaved";
SqlCommand newCmd = conn.CreateCommand();
newCmd.Connection = conn;
newCmd.CommandType = CommandType.Text;
// Hopefully your query returns a single email record
newCmd.CommandText = "Select Email from dbo.EMPLOYEE where Username ='" + UserName + "'";
SqlDataReader reader = newCmd.ExecuteReader();
string email = string.Empty;
while (reader.Read())
{
email = reader["EMPLOYEE.Email"].ToString();
}
conn.Close();
reader.Close();
return email;
}
Moreover if your query returns a single email value then use ExecuteScalar() rather like
string email = newCmd.ExecuteScalar() as string;
Now you can assign it in caller
lblEmail.Text = dba.getEmail(pname);

string q,d;
int ano=0;
SqlConnection con = new SqlConnection("Data Source=SANDEESQLEXPRESS;Initial Catalog=agent demo;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("select * from po where agentno=#ano", con);
cmd.Parameters.AddWithValue("ano",ano);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
d = dr["date1"].ToString();
}
dr.Close();
Label1.Text = d+ "";
does not show value of date in lablel

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);
}

Cannot insert numeric value into my SQL table

I currently have 2 tables in my database, 1 with an autonumeric value called ZoekcriteriaID which is the primary key off the table Zoekcriteria.
I want to add the primary key (ZoekcriteriaID) to my other table called Resultaten as a forgeign key but I keep getting the same error.
It seems like cmd1.Parameters.AddWithValue("#ZoekcriteriaID",Convert.ToInt32(sqlZoekcriteriaID)); keeps trying to add the entire query as a numeric value and I can't seem to figure out why.
Could anyone help me?
namespace Proftaak
{
class Mysearch
{
public string zoekterm = "";
int resultaat = 1;
public string Zoekterm
{
get
{
return zoekterm;
}
set
{
zoekterm = value;
}
}
public void InsertZoekcriteria()
{
OleDbConnection connection = new OleDbConnection();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\martijn\Dropbox\Proftaak Periode 2 Identity\Database11.accdb;
Persist Security Info=False;";
connection.Open();
string sqlstring = "INSERT INTO Zoekcriteria (ZoekCriteria) values ('" + Zoekterm + "')";
OleDbCommand cmd = new OleDbCommand(sqlstring, connection);
cmd.ExecuteNonQuery();
connection.Close();
}
public void searchding()
{
const string apiKey = "AIzaSyDIm9ZOWD8Zd-2tHy5r3c0R-_XjdEFaXGE";
const string searchEngineId = "003470263288780838160:ty47piyybua";
string query = zoekterm;
CustomsearchService customSearchService = new CustomsearchService(new Google.Apis.Services.BaseClientService.Initializer() { ApiKey = apiKey });
Google.Apis.Customsearch.v1.CseResource.ListRequest listRequest = customSearchService.Cse.List(query);
listRequest.Cx = searchEngineId;
Search search = listRequest.Execute();
OleDbConnection connection = new OleDbConnection();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\martijn\Dropbox\Proftaak Periode 2 Identity\Database11.accdb;
Persist Security Info=False;";
connection.Open();
string sqlZoekcriteriaID = "SELECT ZoekcriteriaID from Zoekcriteria where Zoekcriteria='" + query + "'";
OleDbCommand cmdZoekcriteria = new OleDbCommand(sqlZoekcriteriaID, connection);
cmdZoekcriteria.ExecuteNonQuery();
foreach (var item in search.Items)
{
string sqlstring1 = #"INSERT INTO Resultaat (ResultatenID,ZoekcriteriaID, Titel, Webadress) VALUES (#ResultatenID,#ZoekcriteriaID, #Titel, #Webadress)";
OleDbCommand cmd1 = new OleDbCommand(sqlstring1, connection);
cmd1.Parameters.AddWithValue("#ResultatenID", resultaat);
cmd1.Parameters.AddWithValue("#ZoekcriteriaID",Convert.ToInt32(sqlZoekcriteriaID));
cmd1.Parameters.AddWithValue("#Titel", item.Title);
cmd1.Parameters.AddWithValue("#Webadress", item.Link);
// string sqlstring2= "INSERT INTO Resultaat(Titel) values ('"+item.Title+"')";
// OleDbCommand cmd2 = new OleDbCommand(sqlstring2, connection);
resultaat++;
cmd1.ExecuteNonQuery();
}
connection.Close();
That's because it does:
string sqlZoekcriteriaID = "SELECT ZoekcriteriaID from Zoekcriteria where Zoekcriteria='" + query + "'";
cmd1.Parameters.AddWithValue("#ZoekcriteriaID",Convert.ToInt32(sqlZoekcriteriaID));
What you want is use the result of the query. What you should do is described in the answer to this question.
You should also rethink the naming of your variables; queryis not a query, for example, just a search condition.
Before close the connection, recover the identity number, like this:
OleDbCommand cmd = new OleDbCommand(sqlstring, connection);
cmd.ExecuteNonQuery();
cmd.CommandText = "SELECT ##IDENTITY";
integer ZoekcriteriaID = cmd.ExecuteScalar()
connection.Close();
Than you can use the ZoekcriteriaID on the other insert.
Refer to this link

Retrieve SQL Statement Does Not Go Into While Loop

I am having problem when doing retrieve function in 3-tier in C#. Here is the codes:
public DistributionStandardPackingUnits getSPUDetail(string distributionID)
{
DistributionStandardPackingUnits SPUFound = new DistributionStandardPackingUnits();
using (var connection = new SqlConnection(FoodBankDB.connectionString))
{
SqlCommand command = new SqlCommand("SELECT name, description, quantity FROM dbo.DistributionStandardPackingUnits WHERE distribution = '" + distributionID + "'", connection);
connection.Open();
using (var dr = command.ExecuteReader())
{
while (dr.Read())
{
string name = dr["name"].ToString();
string description = dr["description"].ToString();
string quantity = dr["quantity"].ToString();
SPUFound = new DistributionStandardPackingUnits(name, description, quantity);
}
}
}
return SPUFound;
}
When I run in browser, it just won't show up any retrieved data. When I run in debugging mode, I realized that when it hits the while loop, instead of executing the dr.Read(), it simply just skip the entire while loop and return null values. I wonder what problem has caused this. I tested my query using the test query, it returns me something that I wanted so I think the problem does not lies at the Sql statement.
Thanks in advance.
Edited Portion
public static SqlDataReader executeReader(string query)
{
SqlDataReader result = null;
System.Diagnostics.Debug.WriteLine("FoodBankDB executeReader: " + query);
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(query, connection);
connection.Open();
result = command.ExecuteReader();
connection.Close();
return result;
}

Returning a specific value from a database ASP.NET/C#

My question involves returning a specific value from a table in a database. I want to have it where after you login, it displays the name of the user's first and last name.
The table looks like this.
Person
UID(PK), FName, LName, Uname, Upass
How do I return just the Fname and LName so I can place it in a label?
Here is my current code. Keep in mind this is for the master page.
string strConn = WebConfigurationManager.ConnectionStrings["cloud2"].ConnectionString;
protected void btnlogin2_Click(object sender, EventArgs e)
{
string strCmd = "Select * From Person Where uname = #uname and upass = #upass";
SqlConnection objConn = new SqlConnection(strConn);
SqlCommand objCmd = new SqlCommand(strCmd, objConn);
objCmd.Parameters.AddWithValue("#uname", txtusername.Text);
objCmd.Parameters.AddWithValue("#upass", txtpassword.Text);
using (objConn)
{
objConn.Open();
SqlDataReader objDR = objCmd.ExecuteReader();
if (objDR.HasRows)
{
btnlogin2.Visible = false;
txtusername.Visible = false;
txtpassword.Visible = false;
Response.Redirect("member.aspx");
lblLogin.Text = "Logged in as: Test " ; //Display login name?
}
else
{
btnlogin2.Text = "Failed";
}
}
}
First I'd refactor your logic a bit to maintain UI VS database calls a bit separate. Secondly refactor your code to retrieve first and last name that uses code for your connection string, username, password, and outputs firstname and lastname.
string firstName, lastName;
if(ValidateUser(txtusername.Text, txtpassword.Text, out firstName, out lastName)
{
//put your UI Logic and redirect in here
lblLogin.Text = "Welcome: " + firstName + " " + " lastName;
}
else
{
//login faild code
}
private bool ValidateUser(string strConn, string username, string password, out string firstName, out string lastName)
{
firstName = string.Empty;
lastName = string.Empty;
using (var con = new SqlConnection(strConn))
using (var cmd = con.CreateCommand())
{
cmd.CommandText = "Select * From Person Where uname=#uname and upass=#upass";
cmd.Parameters.AddWithValue("#uname", username);
cmd.Parameters.AddWithValue("#upass", password);
con.Open();
using (var r = cmd.ExecuteReader())
{
if (r.Read())
{
firstName = r["FName"].ToString();
lastName = r["LName"].ToString();
return true;
}
else
{
return false;
}
}
}
}
I would do three things:
separate your UI logic from the database logic - don't access your database directly in the middle of a button_Click event handler......
if you only need first and last name, then only select those two columns from the table!
put all the disposable objects like SqlConnection, SqlCommand, SqlDataReader into using(...) {...} blocks so that they will be properly disposed after use
So my code would look something like this:
UI layer:
protected void btnlogin2_Click(object sender, EventArgs e)
{
// call the database layer to get the first and last name
FirstAndLastName data = GetFirstAndLastName(txtusername.Text, txtpassword.Text);
if (data != null) // something was returned - show it
{
lblLogin.Text = string.Format("You're logged in as {0} {1}",
data.FirstName, data.LastName);
}
else
{
lblLogin.Text = "Not logged in....";
}
}
Database layer:
string strConn = WebConfigurationManager.ConnectionStrings["cloud2"].ConnectionString;
internal class FirstAndLastName
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
protected FirstAndLastName GetFirstAndLastName(string userName, string password)
{
FirstAndLastName result = null;
// if you only need FName und LName - then only select those two columns!
// don't just use SELECT * all the time because it's easy and because you're lazy
string strCmd = "SELECT FName, LName FROM dbo.Person WHERE uname = #uname AND upass = #upass";
// wrap everything into using blocks
using(SqlConnection objConn = new SqlConnection(strConn))
using(SqlCommand objCmd = new SqlCommand(strCmd, objConn))
{
objCmd.Parameters.AddWithValue("#uname", userName);
objCmd.Parameters.AddWithValue("#upass", password);
objConn.Open();
using(SqlDataReader objDR = objCmd.ExecuteReader())
{
if (objDR.Read())
{
result = new FirstAndLastName();
result.FirstName = objDR.GetString(objDR.GetOrdinal("FName"));
result.LastName = objDR.GetString(objDR.GetOrdinal("LName"));
}
}
}
return result;
}
string Name=objDR ["FName"].ToString() + ["LName"].ToString()
lblLogin.Text = "Logged in as:"+Name
You can read the instance of SqlDataReader in following way:
WebConfigurationManager.ConnectionStrings["cloud2"].ConnectionString; protected void btnlogin2_Click(object sender, EventArgs e) {
string strCmd = "Select * From Person Where uname=#uname and upass=#upass";
SqlConnection objConn = new SqlConnection(strConn);
SqlCommand objCmd = new SqlCommand(strCmd, objConn);
objCmd.Parameters.AddWithValue("#uname", txtusername.Text);
objCmd.Parameters.AddWithValue("#upass", txtpassword.Text);
using (objConn)
{
objConn.Open();
SqlDataReader objDR = objCmd.ExecuteReader();
if (objDR.Read())
{
string fName= (string)objDR["FName"];
string lName= (string)objDR["LName"];
btnlogin2.Visible = false;
txtusername.Visible = false;
txtpassword.Visible = false;
Response.Redirect("member.aspx");
lblLogin.Text = "Logged in as: Test "+fName+" "+lName; //Display login name?
}
else
{
btnlogin2.Text = "Failed";
}
}
}
Is your question how to return just the data you want from the query, or how to access it from the datareader?
It sounds like you might want ExecuteScalar(), and you can combine the fname and lastname fields in the query so you can just pull the one result:
string strCmd = "Select Fname + ' ' + LName From Person Where uname=#uname and upass=#upass";
SqlConnection objConn = new SqlConnection(strConn);
SqlCommand objCmd = new SqlCommand(strCmd, objConn);
objCmd.Parameters.AddWithValue("#uname", txtusername.Text);
objCmd.Parameters.AddWithValue("#upass", txtpassword.Text);
using (objConn)
{
objConn.Open();
var username = objConn.ExecuteScalar() as string;
if (!string.IsNullOrEmpty())
{
btnlogin2.Visible = false;
txtusername.Visible = false;
txtpassword.Visible = false;
Response.Redirect("member.aspx");
lblLogin.Text = "Logged in as: " + username ; //Display login name?
}
Edit: Just noticed a detail... you're setting lblLogin.Text after redirecting... so not thinking anyone's going to see it anyway. Could add it to the querystring though and display it on member.aspx...
You can do something like
lblLogin.Text = "Logged in as: " + objDR.GetString(dr.GetOrdinal("FName")) + " " + objDR.GetString(dr.GetOrdinal("LName"));
If memory serves, you probably also need to first call objDR.Read(); to start iterating over the datareader.

WCF Service Issues with Java Client

This is an interesting problem, and I will do my best to explain. If you have any questions, please ask.
I have written a WCF service that is suppose to communicate with a JAVA client. This service was created via contract first from a WSDL. Now, according to the WCF test client everything works, even testing on a PHP client works as well. But when it comes to the Java client, the request messages and subsequent response messages fail to return: I get a null object SOAP fault. Here is were I think the problem lies:
According to the XSD and WSDL, I have a DateTime value that I am suppose to take in. This dateTime value from the client is of form: 2012-01-01T12:00:00.00Z. Unfortunately, this input is not valid with the built in .NET datetime. So, to get around this, I changed my code to take in a string datatype, convert that string to a Datetime to send it to the database, get a response from the database in that dateTime and convert it back to a string for the response to return a value that is like the one that was inputted.
I built a logger to check to see if the messages were being sent to and from my wcf service. From that, I have identified that messages from the client were not being received. My only guess is that it is because of the datetime issue.
Is there a way to take in a dateTime datatype in the format: 2012-01-01T12:00:00.000Z? If i can, then that will mean that the request will match my datatype and maybe it will work.
Here is some code:
public partial class findSeatsRequest
{
[MessageBodyMemberAttribute(Namespace="http://soa.cs.uwf.edu/airlineData", Order=0, Name="departAirport")]
public string DepartAirport;
[MessageBodyMemberAttribute(Namespace="http://soa.cs.uwf.edu/airlineData", Order=1, Name="arriveAirport")]
public string ArriveAirport;
[MessageBodyMemberAttribute(Namespace="http://soa.cs.uwf.edu/airlineMessage", Order=2, Name="earliestDepartTime")]
public string EarliestDepartTime;
[MessageBodyMemberAttribute(Namespace="http://soa.cs.uwf.edu/airlineMessage", Order=3, Name="latestDepartTime")]
public string LatestDepartTime;
[MessageBodyMemberAttribute(Namespace="http://soa.cs.uwf.edu/airlineMessage", Order=4, Name="minimumSeatsAvailable")]
public int MinimumSeatsAvailable;
[MessageBodyMemberAttribute(Namespace="http://soa.cs.uwf.edu/airlineMessage", Order=5, Name="maximumFlightsToReturn")]
public int MaximumFlightsToReturn;
public findSeatsRequest()
{
}
public findSeatsRequest(string departAirport, string arriveAirport, string earliestDepartTime, string latestDepartTime, int minimumSeatsAvailable, int maximumFlightsToReturn)
{
this.DepartAirport = departAirport;
this.ArriveAirport = arriveAirport;
this.EarliestDepartTime = earliestDepartTime;
this.LatestDepartTime = latestDepartTime;
this.MinimumSeatsAvailable = minimumSeatsAvailable;
this.MaximumFlightsToReturn = maximumFlightsToReturn;
}
}
public partial class findSeatsResponse
{
[MessageBodyMemberAttribute(Namespace="http://soa.cs.uwf.edu/airlineData", Order=0, Name="flight")]
[XmlElementAttribute("flight")]
public System.Collections.Generic.List<flightType> Flight;
public findSeatsResponse()
{
}
public findSeatsResponse(System.Collections.Generic.List<flightType> flight)
{
this.Flight = flight;
}
}
public virtual findSeatsResponse findSeats(findSeatsRequest request)
{
string departAirport = request.DepartAirport;
string arriveAirport = request.ArriveAirport;
string earliestDepartTime = request.EarliestDepartTime;
string latestDepartTime = request.LatestDepartTime;
int minimumSeatsAvailable = request.MinimumSeatsAvailable;
int maximumFlightsToReturn = request.MaximumFlightsToReturn;
SqlCommand cmd = null;
DataSet ds = new DataSet();
List<flightType> flight = new List<flightType>();
EventLogger log = new EventLogger();
findSeatsRequest inValue = new findSeatsRequest();
inValue.DepartAirport = departAirport;
inValue.ArriveAirport = arriveAirport;
inValue.EarliestDepartTime = earliestDepartTime;
inValue.LatestDepartTime = latestDepartTime;
inValue.MinimumSeatsAvailable = minimumSeatsAvailable;
inValue.MaximumFlightsToReturn = maximumFlightsToReturn;
string latestT = inValue.LatestDepartTime.Replace("T", " ");
string latestZ = latestT.Replace("Z", "");
DateTime _latestDepartTime = DateTime.ParseExact(latestZ, "yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture);
string earliestT = inValue.EarliestDepartTime.Replace("T", " ");
string earliestZ = earliestT.Replace("Z", "");
DateTime _earliestDepartTime = DateTime.ParseExact(earliestZ, "yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture);
log.WriteToDataBase(DateTime.Now, "FindSeats", 1, "This is the request: " + inValue);
//Check Maximum Flights
if (inValue.MaximumFlightsToReturn > 100 | inValue.MaximumFlightsToReturn < 0)
{
throw new FaultException(
"You cannot select more than 100 flights to return, or the maximum flights to return is negative.",
new FaultCode("OutOfRange"));
}
// Check Minimum Seats Available.
if (inValue.MinimumSeatsAvailable < 0)
{
throw new FaultException(
"You minimum seats available cannot be negative.",
new FaultCode("OutOfRange"));
}
// Check for valid Departure Airport
if (departAirport != null && departAirport != "ANY")
{
try
{
string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection conn = new SqlConnection(strConn);
conn.Open();
string check = "SELECT DepartAirport FROM Flight WHERE DepartAirport='" + departAirport + "'";
cmd = new SqlCommand(check, conn);
cmd.CommandText = check;
SqlDataReader depAirport;
depAirport = cmd.ExecuteReader();
if (depAirport.HasRows == false)
{
throw new FaultException(
"Invalid Airport code used.",
new FaultCode("Invalid Text Entry"));
}
}
finally
{
if (cmd != null)
cmd.Dispose();
}
}
// Check for valid Arrival Airport
if (arriveAirport != null && arriveAirport != "ANY")
{
try
{
string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection conn = new SqlConnection(strConn);
conn.Open();
string check = "SELECT ArriveAirport FROM Flight WHERE ArriveAirport='" + arriveAirport + "'";
cmd = new SqlCommand(check, conn);
cmd.CommandText = check;
SqlDataReader arrAirport;
arrAirport = cmd.ExecuteReader();
if (arrAirport.HasRows == false)
{
throw new FaultException(
"Invalid Airport code used.",
new FaultCode("Invalid Text Entry"));
}
}
finally
{
if (cmd != null)
cmd.Dispose();
}
}
try
{
string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection conn = new SqlConnection(strConn);
conn.Open();
cmd = new SqlCommand("usp_NewFindSeats", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#DepartureAirport", inValue.DepartAirport));
cmd.Parameters.Add(new SqlParameter("#ArrivalAirport", inValue.ArriveAirport));
cmd.Parameters.Add(new SqlParameter("#EarliestDepTime", _earliestDepartTime));
cmd.Parameters.Add(new SqlParameter("#LatestDepTime", _latestDepartTime));
cmd.Parameters.Add(new SqlParameter("#minSeatsAvailable", inValue.MinimumSeatsAvailable));
cmd.Parameters.Add(new SqlParameter("#maxFlightsRequested", inValue.MaximumFlightsToReturn));
using (SqlDataReader sqlReader = cmd.ExecuteReader())
{
while (sqlReader.Read())
{
flightType Flight = new flightType();
Flight.FlightId = sqlReader.GetString(0);
Flight.DepartAirport = sqlReader.GetString(1);
Flight.ArriveAirport = sqlReader.GetString(2);
Flight.DepartTime = sqlReader.GetDateTime(3).ToString("yyyy-MM-ddTHH:mm:ss.fffZ");
Flight.ArriveTime = sqlReader.GetDateTime(4).ToString("yyyy-MM-ddTHH:mm:ss.fffZ");
Flight.FlightSeatsAvailable = sqlReader.GetInt32(5);
Flight.FlightSeatPriceUSD = sqlReader.GetDouble(6);
flight.Add(Flight);
}
}
For this particular problem, the issue wasn't anything I thought it was in the beginning. Firstly, had to use WrapperNames in my C# code's request operations and the names I used were incorrect.
Secondly, I needed to specify SOAP Body encoding which I had to do within my Interface layer.
[XmlSerializerFormatAttribute(SupportFaults=true, Style=OperationFormatStyle.Document ,Use=OperationFormatUse.Literal)]