Returning list of items - c#

I am retrieving multiple records from database and storing it in list. I have created properties class and then i assign data being retrieved to variables in properties and then trying to return all collection of values to client who made function call but it doesn't work. Why ? please make it correct.
Code:
public Properties FetchCoordinates(String FetchParam)
{
String[] parts = FetchParam.Split(',');
sqlCom.CommandText = "FetchCoordinates";
sqlCom.CommandType = CommandType.StoredProcedure;
sqlCom.Parameters.Add("#IMEI", SqlDbType.VarChar).Value = parts[0].ToString();
sqlCom.Parameters.Add("#DateTimeFrom", SqlDbType.VarChar).Value = Convert.ToDateTime(parts[1].ToString());
sqlCom.Parameters.Add("#DateTimeTo", SqlDbType.VarChar).Value = Convert.ToDateTime(parts[2].ToString());
SqlParameter sqlParam = new SqlParameter("#result", SqlDbType.Int);
sqlCom.Parameters.Add(sqlParam);
sqlCom.Parameters["#result"].Direction = ParameterDirection.Output;
List<Properties> props = new List<Properties>();
Properties p;
try
{
sqlCon.Open();
using (SqlDataReader reader = sqlCom.ExecuteReader())
{
while (reader.Read())
{
p = new Properties()
{
Longitude = reader["Longitude"].ToString(),
Latitude = reader["Latitude"].ToString()
};
props.Add(p);
return p;
}
}
}
catch (Exception ex)
{
}
finally
{
sqlCon.Close();
}
}
}
Properties.cs
public class Properties
{
public Properties()
{
}
public string Longitude { get; set; }
public string Latitude { get; set; }
}

Change the method signature;
public List<Properties> FetchCoordinates(String FetchParam)
and rather than returning p which is only a single instance, return the List props;
while (reader.Read())
{
p = new Properties()
{
Longitude = reader["Longitude"].ToString(),
Latitude = reader["Latitude"].ToString()
};
props.Add(p);
}
return props;

Related

How can I get var output data when my return type is IEnumerable

I need to get data from var result = new not from IEnumerable. Please help me if is their any alternate solution, please let me know.
public IEnumerable<Employee_Join> GetEmployees(int paginate)
{
int FilterdCount = 0;
using (SqlConnection con = Db.Dbcontect)
{
var employee = new List<Employee_Join>();
con.Open();
SqlCommand cmd = new SqlCommand("SP_GetEmployees_By_Pagination", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Pagination", paginate);
cmd.Parameters.AddWithValue("#Total", 5);
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows == true)
{
while (rdr.Read())
{
Employee_Join emp = new Employee_Join();
if (!Convert.IsDBNull(rdr["EmployeeId"]))
{
emp.Emp_Id = Convert.ToInt32(rdr["EmployeeId"]);
}
emp.EmpName = rdr["EmpName"].ToString();
emp.Email = rdr["Email"].ToString();
emp.Cnt_Name = rdr["CountryName"].ToString();
employee.Add(emp);
}
}
var result = new
{
iTotalRecords = GetTotalEmployeeCount(),
iTotalDisplayRecords = FilterdCount,
aaData = employee
};
return employee;
}
}
I need var result = new output not employee
If you want to return result, you need to create a ViewModel / DTO class from it, since C# does not let your return anonymous objects from methods (technically you can, but this creates a lot of additional work down the road, so just don't, please).
public class MyCustomDTO
{
public Type iTotalRecords { get; set; }
public Type iTotalDisplayRecords { get; set; }
public Type employee { get; set; }
}
The change your code so it does not create an anonyomous type, but your new class:
var result = new MyCustomDTO
{
iTotalRecords = GetTotalEmployeeCount(),
iTotalDisplayRecords = FilterdCount,
aaData = employee
};
return employee;
Finally change to return type of your function to reflect the correct type
public MyCustomDTO GetEmployees(int paginate) { /* ... */}

Binding dropdownlist with generic list in 3-tier architecture

/*data access layer */
public DataSet getdata(string procedurename, SqlParameter[] param)
{
try
{
SqlCommand command;
command = new SqlCommand(procedurename, connection);
command.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataSet set = new DataSet();
if (param != null)
{
for (int i = 0; i < param.Length; i++)
{
command.Parameters.Add(param[i]);
}
}
adapter.Fill(set);
return set;
}
catch (Exception ex)
{
throw ex;
}
finally
{
closeConnection();
}
}
Middle Tier:
public class dropdownbind
{
private string _itemName;
private int _itemvalue;
public int Itemvalue
{
get { return _itemvalue; }
set { _itemvalue = value; }
}
public string ItemName
{
get { return _itemName; }
set { _itemName = value; }
}
public List<dropdownbind> getDepartment()
{
DBlist obj = new DBlist();
DataSet ds = obj.getdata("str_getdepartment",null);
List<dropdownbind> departments = new List<dropdownbind>();
foreach (DataRow orow in ds.Tables[0].Rows)
{
dropdownbind dlist = new dropdownbind();
dlist.ItemName = orow["deparment_name"].ToString();
dlist.Itemvalue = int.Parse(orow["id"].ToString());
departments.Add(dlist);
}
return departments;
}
}
UI:-
protected void BindDdlList()
{
dropdownbind dlist = new dropdownbind();
List<dropdownbind> departments = dlist.getDepartment();
ddlEmpDepatment.DataSource = departments;
ddlEmpDepatment.DataTextField = dlist.ItemName;
ddlEmpDepatment.DataValueField = dlist.Itemvalue.ToString();
ddlEmpDepatment.DataBind();
}
i am trying to bind departments to dropdownlist using 3-tier architecture.
but this code is not working, it shows middletier.dropdownbind in text field.
You need to correct the DataTextField & DataValueField properties like this:-
ddlEmpDepatment.DataValueField = "Itemvalue";
ddlEmpDepatment.DataTextField = "ItemName";
You are specifying the property name rather you need to specify the property name as string.

Using ADO.Net Core With Models, I want to Display Data From Different Relational Tables But It Gives Me Some Errors

I have an error in the code below. When I use it for one table it works fine, But it doesn't work for relational tables.
Method for displaying all records:
public List<AdminUserRegisterModel> GetAll()
{
List<AdminUserRegisterModel> List = new List<AdminUserRegisterModel>();
try
{
SqlCommand cmd = new SqlCommand("sp_admin_user_search_all", connection);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader dr;
connection.Open();
dr = cmd.ExecuteReader();
// while(dr.HasRows)
//{
while(dr.Read())
{
AdminUserRegisterModel obj = new AdminUserRegisterModel();
obj.adminUsers.adminId = Convert.ToInt32(dr["adminId"]);
obj.adminUsers.adminName = Convert.ToString(dr["adminName"]);
obj.adminUsers.adminEmail = Convert.ToString(dr["adminEmail"]);
obj.adminUsers.adminPassword = Convert.ToString(dr["adminPassword"]);
obj.adminUsers.adminStatus = Convert.ToInt32(dr["adminStatus"]);
obj.adminUsers.joinDate = Convert.ToDateTime(dr["adminJoinDate"]);
// AdminUserProfile table
obj.adminProfiles.adminProfileId = Convert.ToInt32(dr["profileId"]);
obj.adminProfiles.firstName = Convert.ToString(dr["firstName"]);
obj.adminProfiles.lastName = Convert.ToString(dr["lastName"]);
obj.adminProfiles.cnic = Convert.ToString(dr["cnic"]);
obj.adminProfiles.profileImg = Convert.ToString(dr["profileImg"]);
obj.adminProfiles.adminId = Convert.ToInt32(dr["adminId"]);
List.Add(obj);
}
//}
if (!dr.IsClosed)
{
dr.Close();
}
connection.Close();
return List;
}
catch
{
connection.Close();
return null;
}
finally
{
connection.Close();
}
}
Controller method:
// Display All Records
public ActionResult Display()
{
repObj = new AdminUserRegisterRepository();
return View(repObj.GetAll());
}
Model class:
public class AdminUserRegisterModel
{
public adminUser adminUsers { get; set; }
public admin_profile adminProfiles { get; set; }
}
It gives me the following error:

Generic List linked with Database using Reflection

I have a class
public class UserInfo
{
public int ID { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
And I need to make a link between the database, with this code:
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.HasRows)
{
}
}
Using Reflection on all the lines of the database.
And store them into a generic List:
List<UserInfo> users = new List<UserInfo>();
I GOT IT !!
I GOT IT !!
This is the result, maybe someone needs it !!
public List<UserInfo> GetAllUsers()
{
List<UserInfo> users = new List<UserInfo>();
try
{
using (SqlConnection sqlConnection = connectionString)
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "dbo.GetAllUsers";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConnection;
sqlConnection.Open();
using (SqlDataReader dataReader = cmd.ExecuteReader())
{
if (dataReader.HasRows)
{
while (dataReader.Read())
{
UserInfo user = new UserInfo();
PropertyInfo[] pList = typeof(UserInfo).GetProperties();
foreach (PropertyInfo pi in pList)
{
object value = dataReader[pi.Name];
if (!value.GetType().Equals(typeof(DBNull)))
{
users.GetType().GetProperty(pi.Name, BindingFlags.Public | BindingFlags.Instance).SetValue(user, value, null);
}
}
users.Add(user);
}
}
else
{
users = null;
}
}
}
sqlConnection.Close();
}
}
catch (Exception)
{
return null;
}
return users;
}

Object Data Source function returning only 1 value

I am using ObjectDataSource for my Gridview.
The function I am using to return values is just returning a single value that is the last one from the table.
What changes do I make to return all the values.
public class Employees
{
public int e_number;
public string e_name;
public string e_designation;
private SqlConnection conn = null;
private SqlCommand cmd = null;
private string constring = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
public Employees()
{
conn = new SqlConnection(constring);
cmd = new SqlCommand();
}
public int Employee
{
get
{
return e_number;
}
set
{
e_number = value;
}
}
public string Name
{
get
{
return e_name;
}
set
{
e_name = value;
}
}
public string Designation
{
get
{
return e_designation;
}
set
{
e_designation = value;
}
}
public Employees GetEmployee()
{
string strquery = "select [Number],[Name],[Designation] from [Users]";
conn.Open();
cmd.Connection = conn;
cmd.CommandText = strquery;
SqlDataReader objSqlDataReader = cmd.ExecuteReader();
int counter = 0;
// ArrayList myObj = new ArrayList();
// Employees objEmployees = new Employees();
Employees emp = null;
//if (objSqlDataReader.Read())
while(objSqlDataReader.Read())
{
emp = new Employees();
// myObj[counter] = new Employees();
// Employees employee = new Employees();
emp.Employee = (int)objSqlDataReader["Number"];
emp.Name=(string)objSqlDataReader["Name"];
emp.Designation = (string)objSqlDataReader["Designation"];
// objEmployees.e_number = (int)objSqlDataReader["Number"];
// objEmployees.e_name = (string)objSqlDataReader["Name"];
//objEmployees.e_designation = (string)objSqlDataReader["Designation"];
}
conn.Close();
return emp;
//return objEmployees;
}
}
}
I have tried all approaches like making array of objects but I am not able to .
Please could you tell me what to add in my code.
You need to return a list of employees. You are only returning a single one, the last instance after you exit the loop:
public List<Employees> GetEmployees()
{
..
List<Employees> emps = new List<Employees>();
Employees emp = null;
while (..)
{
emp = new Employees();
..
emps.Add(emp);
}
return emps;
}

Categories