WCF Service Issues with Java Client - wcf

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)]

Related

SQL Data Reader into Label - Value doesn't display

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

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.

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.

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)