silverlight C# code - silverlight-4.0

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)

Related

Passing DropDownList value into SQL command in ASP.net

I have a DropDownList which gets it values from SQL table
I want to get the Average of the selected item (course in this case) from the dropDownList and to show it in a label :
This section works -
SqlConnection sqlConnection1;
sqlConnection1 = new SqlConnection(#"Data Source=HA\SQLEXPRESS; Initial Catalog=Grades1; Integrated Security=True");
SqlCommand Command = null;
Command = new SqlCommand("SELECT Course FROM GradesTable1", sqlConnection1);
Command.Connection.Open();
SqlDataAdapter dataAdapter = new SqlDataAdapter(Command);
DataTable dataTble1 = new DataTable();
dataAdapter.Fill(dataTble1);
if (dataTble1.Rows.Count > 0)
{
foreach (DataRow row in dataTble1.Rows)
{
ListItem course1 = new ListItem(row["Course"].ToString());
if (!DropDownList1.Items.Contains(course1))
{
DropDownList1.Items.Add(course1); // showing the 2 courses
}
}
}
Command.Connection.Close();
}
}
Here is the problem - (I get nothing, no data )
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection sqlConnection1;
sqlConnection1 = new SqlConnection(#"Data Source=HA\SQLEXPRESS; Initial Catalog=Grades1; Integrated Security=True");
SqlCommand Command = null;
Command = new SqlCommand($"SELECT AVG(Grade) FROM GradesTable1 WHERE Course = #course", sqlConnection1);
Command.Parameters.AddWithValue("#course", DropDownList1.SelectedItem);
Command.Connection.Open();
SqlDataReader sqlDataReader1 = Command.ExecuteReader();
if (sqlDataReader1.Read())
{
LabelAverage.Text = sqlDataReader1[0].ToString();
}
else
{
LabelAverage.Text = "No Data"; // doesn't get into here anyhow
}
}
EDIT
I tried several variations as $"SELECT AVG(Grade) AS "ClassAVG" FROM GradesTable1 WHERE Course = #course" and Command.Parameters.AddWithValue("#course", DropDownList1.SelectedItem.Text), or DropDownList1.SelectedValue
I believe the problem is with the DropDownlist values which being received from the SQL and are not hard coded.
Is there a correct way to this? is it possible without knowing what are the "Courses" in advanced?
Thanks for the answers, feel free to give your opinion.
I found out what was missing in the DropDownList in aspx page (not the aspx.cs page) -the AutoPostBack="true"
Adding that to DropDownList solved the problem.
// query = Sql query
query.Select(s => new MusteriNoktaComboItemDTO
{
Label = s.Adi,
Value = s.ID.ToString()
}).ToList();

MVC 5 Convert SQL Query to EF Linq

I have this result:
The problem is that I am not using the power of EF.
I followed this EF tutorial but i'm now able to do it.
ActivityLogController.cs
using System;
...
namespace AccountSystem.Controllers
{
public class ActivityLogController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET: ActivityLog
public ActionResult Index()
{
/* var id = User.Identity.GetUserId();
var Emaill = (from x in db.Users
where x.Id == id
select x.Email).Single(); */
//string Access = AccessQ.ToString();
IEnumerable<ActivityLogViewData> model = null;
List<ActivityLogViewData> verify = new List<ActivityLogViewData>();
SqlConnection connection = new SqlConnection("xxx");
connection.Open();
SqlCommand command = new SqlCommand("", connection);
command.CommandText = "select dbo.AspNetUsers.Email,dbo.AspNetUsers.UserName,dbo.ActivityLogModels.ID,dbo.ActivityLogModels.Acess,dbo.AspNetUsers.Id from dbo.ActivityLogModels inner join dbo.AspNetUsers on dbo.ActivityLogModels.userID=dbo.AspNetUsers.Id";
SqlDataReader dr = command.ExecuteReader();
while (dr.Read())
{
verify.Add(new ActivityLogViewData { Email = dr[0].ToString(), UserName = dr[1].ToString(), accessID = Convert.ToInt32(dr[2].ToString()), Acess = Convert.ToDateTime(dr[3].ToString()), userID = dr[4].ToString()});
}
connection.Close();
//verify.Add(new ActivityLogViewData {Email = Emaill });
//return View(db.ActivityLog.ToList());
return View(verify);
}
The commented lines are my unsuccessful tries.
Can someone convert this to use EF?
TiA!

ASP.NET 5 - DataSet, DataTable and friends

I'm creating a new webservice in ASP.NET 5 using the new .NET Core library, so far I've only hit an issue with using DataSet and DataTable.
According to this site they are not included at this moment in time, which is fine, but I don't know what alternatives I have at this time, so I'm just looking for some guidance.
I have the following code:
public string Get(string p_sUserId, string p_sUserPassword, int p_iCustId)
{
Select qrySelect = new Select();
using (SqlConnection conn = new SqlConnection(Startup.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(qrySelect.getData(), conn))
{
cmd.Parameters.AddWithValue("#Id", sTestId);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
using (DataSet ds = new DataSet())
{
// foo
// bar
}
}
}
}
return "value";
}
How should I handle the data that is being return from the query? I need to build and return a string using the above data fetched from the query. Any help and guidance would be appreciated.
I believe SqlDataReader should work.
string sql = "SELECT * FROM Table";
using (SqlConnection con = new SqlConnection(Startup.ConnectionString)) {
con.Open();
using (SqlCommand command = new SqlCommand(sql, con)) {
using (IDataReader dr = command.ExecuteReader()) {
while (dr.Read()) {
//process data
}
}
}
}
DataTable and SqlDBAdapter are now supported using .NET Standard 2.0. Upgrade to VS2017 Preview, add System.Data.Common and System.Data.SqlClient nugets, and the code below should work. More detail at the blog post here -> https://blogs.msdn.microsoft.com/devfish/2017/05/15/exploring-datatable-and-sqldbadapter-in-asp-net-core-2-0/ . GitHub repo here -> https://github.com/jhealy/aspdotnetcore/tree/master/SqlClientPlay20 .
public static DataTable ExecuteDataTableSqlDA(SqlConnection conn, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
{
System.Data.DataTable dt = new DataTable();
System.Data.SqlClient.SqlDataAdapter da = new SqlDataAdapter(cmdText, conn);
da.Fill(dt);
return dt;
}

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;

Return nested complex types from WCF WebGet

I've created a wcf data service to return a List of complex type patient. I used the model browser to create a complex type for "Patient" and a complex type for "Contact". I'd like to add a "Contacts" property to "Patient", which would be a List.
How do I add a nested complex type list as a property and return it?
[WebGet]
public List<Patient> GetPatientByID(int tolid)
{
List<Patient> list = new List<Patient>();
// create pds user session record
SqlConnection conn = new SqlConnection("Data Source=server;Initial Catalog=db;User ID=<ID>;Password=<pwd>");
SqlCommand cmd = new SqlCommand();
try
{
// open the connection
conn.Open();
// configure the command
cmd.Connection = conn;
cmd.CommandText = "sp_tol_patient_select";
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("tolid", tolid));
// execute the command and convert the decimal value
// returned by ExecuteScalar to an int to get new identity value
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Patient itm = new Patient();
itm.MRN = reader["UNITNUMBER"].ToString();
itm.AccountNum = reader["ACCTNUM"].ToString();
itm.FullName = reader["PATNAME"].ToString();
itm.BirthDate = reader["BIRTHDATE"].ToString();
itm.Gender = reader["SEX"].ToString();
list.Add(itm);
}
return list;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
cmd.Dispose();
conn.Close();
}
}