Generic List linked with Database using Reflection - c#

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

Related

Is there a way i can reuse this code in C#

Is there a way i can reuse this codes in executing SQL transaction, i want to make it a method so i can put parameters to execute other stored procedures,
can you guys help me to design a good coding structure?
try {
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("InsertUser2Sp", con) {
CommandType = CommandType.StoredProcedure
}) {
cmd.Parameters.AddWithValue("#UserID", useridStr);
cmd.Parameters.AddWithValue("#Firstname", firstnStr);
cmd.Parameters.AddWithValue("#Middlename", middleNstr);
cmd.Parameters.AddWithValue("#Lastname", lastnStr);
cmd.Parameters.AddWithValue("#UserAge", ageInt);
cmd.Parameters.AddWithValue("#HomeAddress", homeaddStr);
con.Open();
cmd.ExecuteNonQuery();
}
}
} catch (Exception ex) {
MessageBox.Show("Could not connect to database. Check settings. " + ex.Message, "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show(ex.Message);
}
}
I will share a generic method here . All you need to do is to build an object with the same property names (including cases) same with the parameters in your SP.
protected internal string GetSingleValue_String(String spname, Object entity)
{
Object res = new Object();
String conString = String.Empty;
using (SqlConnection con = new SqlConnection(ConnectionString))
{
con.Open();
SqlCommand cmd = new SqlCommand(spname, con);
cmd.CommandType = CommandType.StoredProcedure;
if (entity != null)
{
SqlCommandBuilder.DeriveParameters(cmd);
PropertyInfo entitymember = default(PropertyInfo);
foreach (SqlParameter _param in cmd.Parameters)
{
if (_param.Direction == ParameterDirection.Input)
{
entitymember = entity.GetType().GetProperty(_param.ParameterName.Replace("#", ""));
var entityValue = entitymember.GetValue(entity, null);
String _paramvalue = entityValue != null ? entityValue.ToString() : null;
_param.Value = (string.IsNullOrEmpty(_paramvalue) || _paramvalue == string.Empty ? null : _paramvalue);
}
}
}
res = cmd.ExecuteScalar();
cmd.Connection.Close();
entity = null;
cmd = null;
if(res==null)
res = "";
else if (String.IsNullOrEmpty(res.ToString()))
res = "";
return res.ToString();
}
}
So in your example, create a new class that have the same definition as your SP parameters.
class NewClass()
{
public string UserID { get; set; }
public string Firstname { get; set; }
public string Middlename { get; set; }
public string Lastname { get; set; }
public string UserAge { get; set; }
public string HomeAddress { get; set; }
}
And will call the method like this.
var newClass = new NewClass
{
UserID = "UserId",
Firstname = "Firstname",
Middlename = "Middlename",
Lastname = "Lastname",
UserAge = "UserAge",
HomeAddress = "HomeAddress"
}
var res = GetSingleValue_String("InsertUser2Sp", newClass);
Don'd mind the return type.

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:

Insert null datetime from sql table into datagridview silverlight

I have problem with null values, I want to insert from sql table nulls ( from datetime column) into datagridview, and datagridview return error.
Communication Exception was unhandled by user code
Code:
public class Pismo
{
public int Id { get; set; }
public string PW { get; set; }
public DateTime? Data_Wysylki { get; set; }
}
public ObservableCollection<Pismo> ReadPisma(int id_pismo)
{
ObservableCollection<Pismo> result = new ObservableCollection<Pismo>();
string nwConn = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
SqlDataReader dr;
SqlConnection conn = new SqlConnection(nwConn);
try
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = conn;
cmd.CommandText = "INSERT";
cmd.Parameters.AddWithValue("#id", id);
conn.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
Pismo wiersz = new Pismo();
wi.Id = dr.GetInt32(0);
wi.PW = dr.GetString(1);
wi.Data_Wysylki = dr.GetDateTime(2);
result.Add(wi);
}
dr.Close();
return result;
}
catch (SqlException e)
{
Pismo wi = new Pismo();
wi.Id = e.Message;
result.Add(wi);
return result;
}
finally
{
conn.Close();
};
}
<sdk:DataGridTextColumn Header="Data WysyƂki" Binding="{Binding Data_Wysylki, StringFormat='yyyy/MM/dd'}"/>
I try to add this below
if (wi.Data_Wysylki.HasValue) wi.Data_Wysylki = dr.GetDateTime(16);
after that error didnt show but in datagridview all column (even with some dates) was null

Returning list of items

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;

I get the error 'not all code paths return a value' in a try catch block

Please see the code below, it is MVC, I'm trying to create a IEnumerable view. The error I'm getting is'not all code path return a value' how can I correct the error?
public class CustomerSummary
{
public string ContactName { get; set; } // Customer table
public string City { get; set; } // Customer table
public string PostalCode { get; set; } // Order table
public string ShipName { get; set; } // Order table
public string ProductName { get; set; } // Product table
public bool Discontinued { get; set; } // product table
}
Controller
public class CustomerSummaryController : Controller
{
//
// GET: /CustomerSummary/
private CustomerSummaries _customerSummaries = new CustomerSummaries();
public ViewResult Index()
{
IEnumerable<CustomerSummary> summaries = _customerSummaries.GetAll();
return View(summaries);
}
}
Data layer
public IEnumerable<CustomerSummaries> GetAll(/* to do put connection string here */)
{
try
{
SqlCommand cmd = new SqlCommand("GetAll", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlDataReader sdr;
conn.Open();
sdr = cmd.ExecuteReader();
while (sdr.Read())
{
if (sdr.IsDBNull(sdr.GetOrdinal("ContactName")) != true)
{
sdr["ContactName"].ToString();
}
}
}
catch (Exception)
{
throw;
}
finally
{
conn.Close();
}
}
I'm making a fair amount of assumptions here, but I think this is what you want:
public IEnumerable<CustomerSummary> GetAll(SqlConnection conn)
{
var result = new List<CustomerSummary>();
try
{
SqlCommand cmd = new SqlCommand("GetAll", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlDataReader sdr;
conn.Open();
sdr = cmd.ExecuteReader();
while (sdr.Read())
{
var cs = new CustomerSummary();
if (sdr.IsDBNull(sdr.GetOrdinal("ContactName")) != true)
{
cs.ContactName = sdr["ContactName"].ToString();
}
// repeat the above if-block to add more info if needed...
// add the CustomerSummary to the result
result.Add(cs);
}
}
catch (Exception)
{
throw;
}
finally
{
conn.Close();
}
return result;
}

Categories