I am currently creating a list in the class ExpandWindow using a method in the class JobComponent. How would I access the JobDateTime in JobList from jobDetail and assign the value to DateTimeTextBlock?
Code below:
ExpandWindow.cs
public ExpandWindow(int jobId)
{
InitializeComponent();
List<JobComponent.JobList> jobDetail = JobComponent.SelectJobBooking(jobId);
}
JobComponent.cs
public static List<JobList> SelectJobBooking(int jobId)
{
const string query = "SELECT t1.datetime FROM booking t1 " +
"WHERE t1.id=#id";
var jobList = new List<JobList>();
using (var cmd = new MySqlCommand(query, DbObject.Connection))
{
if (DbObject.Connection.State != ConnectionState.Open)
{
DbObject.OpenConnection();
}
cmd.Parameters.AddWithValue(("#id"), jobId);
try
{
using (MySqlDataReader dataReader = cmd.ExecuteReader())
{
while (dataReader.Read())
{
var item = new JobList
{
JobDateTime = dataReader["datetime"] + ""
};
jobList.Add(item);
}
dataReader.Close();
DbObject.CloseConnection();
return jobList;
}
}
catch (Exception ex)
{
ErrorHandlingComponent.LogError(ex.ToString());
throw;
}
}
}
Not exactly sure what you trying here, but think you will get idea how to get the JobDateTime.
public ExpandWindow(int jobId)
{
InitializeComponent();
List<JobComponent.JobList> jobDetail = JobComponent.SelectJobBooking(jobId);
if(jobDetail == null) return;
var item = jobDetail.FirstOrDefault();
if(item == null) return;
yourDatetimeControl.Value = item.JobDateTime;
}
Related
My program can load in the listbox headers, but not the actually data from the whole table.
(how I am connecting to the database):
const string connectionString = "Data Source=test;Initial Catalog=dbi391731;User ID=test;Password=test";
SqlConnection conn = new SqlConnection(connectionString);
I'm using a class to load in the data:
public List<ScoreMdw> GetScoreMdwList()
{
List<ScoreMdw> scoremdwList = new List<ScoreMdw>();
conn.Open();
string query = ("Select employeeid, questionid, score from contentment");
SqlCommand cmd = new SqlCommand(query, conn);
try
{
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
ScoreMdw sm = new ScoreMdw((int)dr["employeeid"], (int)dr["questionid"], (char)dr["score"]);
scoremdwList.Add(sm);
}
}
}
catch (Exception ex)
{
Exception error = new Exception("error", ex);
throw error;
}
finally
{
conn.Close();
}
return scoremdwList;
}
In the while loop I'm using an other class:
class ScoreMdw
{
private int employeeid;
private int questionid;
private char score;
public ScoreMdw(int nr, int id, char s)
{
this.employeeid= nr;
this.questionid= id;
this.score = s;
}
public int EmployeeId
{
get { return employeeid; }
}
public int QuestionId
{
get { return questionid; }
}
public char Score
{
get { return score; }
}
public override string ToString()
{
string s = string.Format("{0} \t{1} \t{2}", this.employeeid, this.questionid, this.score);
return s;
}
}
In my main window I'm doing this:
private void btnLoadScores_Click(object sender, RoutedEventArgs e)
{
scoremdwList = new List<ScoreMdw>();
try
{
conn.Open();
List<string> headers = so.GetContentmentHeaders();
foreach (string header in headers)
txtHeader.Text += header + "\t";
scoremdwList = so.GetScoreMdwList();
lbScores.ItemsSource = scoremdwList;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
I get the error that I made in the class ("error"). I don't know what I'm doing wrong? Maybe something with the connection? Am I opening and closing it the wrong way?
May i ask you, to show us the ex.Message? So we know what the possible error could be.
try
{
using(SqlDataReader dr = cmd.ExecuteReader())
{
while(dr.read())
{
ScoreMdw sm = new ScoreMdw((int)dr["employeeid"], (int)dr["questionid"], (char)dr["score"]);
scoremdwList.Add(sm);
}
}
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message); // <= here you will get you errormessage that is important to fix your error.
Exception error = new Exception("error", ex);
throw error;
}
I have around 8-9 functions for filling tables from SQL to Sqlite and I am trying to make a dynamic function on which I will just pass some params and it will create the sqlite table (if it doesn't exist), create multiple instances in a loop of the type I want to insert in the specific table, set the properties for it and then insert it. Here are example functions:
private bool ReloadItemsFromServer()
{
try
{
using (GS.cnn)
{
SqlCommand command = new SqlCommand("rsp_FillItem_MobileDevice;", GS.cnn);
command.CommandType = System.Data.CommandType.StoredProcedure;
GS.cnn.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
string dbPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "DataBase.PremierAndroid");
using (var sqliteConn = new SQLiteConnection(dbPath))
{
sqliteConn.CreateTable<Item>();
while (reader.Read())
{
{
var newItem = new Item();
newItem.ItemID = reader.GetInt32(0);
newItem.ItemBaseID = reader.GetInt32(1);
newItem.BrandID = reader.GetInt32(2);
newItem.Issue = reader.GetInt32(3);
sqliteConn.Insert(newItem);
}
}
}
}
else
{
_dlgAlert = new AlertDialog.Builder(this).Create();
_dlgAlert.SetMessage(Resources.GetString(Resource.String.NoRowsForItemFound));
_dlgAlert.SetTitle(Resources.GetString(Resource.String.Error));
_dlgAlert.SetButton("OK", delegate { });
_dlgAlert.Show();
return false;
}
reader.Close();
}
return true;
}
catch (Exception ex)
{
_dlgAlert = new AlertDialog.Builder(this).Create();
_dlgAlert.SetMessage(ex.Message);
_dlgAlert.SetTitle(Resources.GetString(Resource.String.Error));
_dlgAlert.SetButton("OK", delegate { });
_dlgAlert.Show();
return false;
}
finally
{
if (GS.cnn.State != ConnectionState.Closed)
{
GS.cnn.Close();
}
}
}
and here's another one:
private bool ReloadContragentsFromServer()
{
try
{
using (GS.cnn)
{
SqlCommand command = new SqlCommand("rsp_FillContragent_MobileDevice;", GS.cnn);
command.CommandType = System.Data.CommandType.StoredProcedure;
GS.cnn.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
string dbPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "DataBase.PremierAndroid");
using (var sqliteConn = new SQLiteConnection(dbPath))
{
sqliteConn.CreateTable<Contragent>();
while (reader.Read())
{
{
var newContragent = new Contragent();
newContragent.ContragentID = reader.GetInt32(0);
newContragent.ContragentTypeID = reader.GetInt32(1);
newContragent.ContragentGroupID = reader.GetInt32(2);
newContragent.FullName = reader.GetString(3);
newContragent.BULSTAT = reader.GetString(4);
newContragent.ItemPriceGroupID = reader.GetInt32(5);
newContragent.ItemDiscountGroupID = reader.GetInt32(6);
sqliteConn.Insert(newContragent);
}
}
}
}
else
{
_dlgAlert = new AlertDialog.Builder(this).Create();
_dlgAlert.SetMessage(Resources.GetString(Resource.String.NoRowsForContragentFound));
_dlgAlert.SetTitle(Resources.GetString(Resource.String.Error));
_dlgAlert.SetButton("OK", delegate { });
_dlgAlert.Show();
return false;
}
reader.Close();
}
return true;
}
catch (Exception ex)
{
_dlgAlert = new AlertDialog.Builder(this).Create();
_dlgAlert.SetMessage(ex.Message);
_dlgAlert.SetTitle(Resources.GetString(Resource.String.Error));
_dlgAlert.SetButton("OK", delegate { });
_dlgAlert.Show();
return false;
}
finally
{
if (GS.cnn.State != ConnectionState.Closed)
{
GS.cnn.Close();
}
}
}
You can see what's different. How can I make it so I just call one method and give it some params so i dont have 8-9 blocks of code which are somewhat repeating?
I currently have this as a dynamic function (unfinished):
private bool LoadDataFromServer(string procedure, Type passedType)
{
try
{
using (GS.cnn)
{
SqlCommand command = new SqlCommand(procedure, GS.cnn);
command.CommandType = System.Data.CommandType.StoredProcedure;
GS.cnn.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
string dbPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "DataBase.PremierAndroid");
using (var sqliteConn = new SQLiteConnection(dbPath))
{
sqliteConn.CreateTable(passedType);
while (reader.Read()) //to do > i++ bla bla
{
{
var newItem = Activator.CreateInstance(passedType);
//newItem - loop through properties and set = reader.get(int/string)(i)
sqliteConn.Insert(newItem);
}
}
}
}
else
{
_dlgAlert = new AlertDialog.Builder(this).Create();
_dlgAlert.SetMessage(Resources.GetString(Resource.String.NoRowsForItemFound));
_dlgAlert.SetTitle(Resources.GetString(Resource.String.Error));
_dlgAlert.SetButton("OK", delegate { });
_dlgAlert.Show();
return false;
}
reader.Close();
}
return true;
}
catch (Exception ex)
{
_dlgAlert = new AlertDialog.Builder(this).Create();
_dlgAlert.SetMessage(ex.Message);
_dlgAlert.SetTitle(Resources.GetString(Resource.String.Error));
_dlgAlert.SetButton("OK", delegate { });
_dlgAlert.Show();
return false;
}
finally
{
if (GS.cnn.State != ConnectionState.Closed)
{
GS.cnn.Close();
}
}
}
Thank you
let reflection and inherit help like this:
class Caller{
// see how it sends objects to method 'processAllClasses' with different classes
void main(){
ItemClass1 i1 = new ItemClass1();
i1.setItemsB(1,2);
processAllClasses(i1);
ItemClass2 i2 = new ItemClass2();
i2.setItemsB(10, 20);
processAllClasses(i2);
}
//using reflection and inherit to process different classes, obj is what need to be processed on.
//alternative way:
//get members from the type, then assign values to them one by one
void processAllClasses(ParentClass myobjvalue)
{
Type realtype = myobjvalue.GetType();
ParentClass myobj = new ParentClass();
MethodInfo mi = realtype.GetMethod("setItemsA");
object obj = Activator.CreateInstance(realtype);
Object[] parameter = new Object[] { myobjvalue };
mi.Invoke(obj, parameter);
}
}
class ParentClass {
}
class ItemClass1: ParentClass
{
int ItemID;
int ItemBaseID;
public void setItemsA(ItemClass1 itemclass1)
{
this.ItemID = itemclass1.ItemID;
this.ItemBaseID = itemclass1.ItemBaseID;
}
public void setItemsB(int ItemID, int ItemBaseID)
{
this.ItemID = ItemID;
this.ItemBaseID = ItemBaseID;
}
}
class ItemClass2 : ParentClass
{
int ContragentID;
int ContragentTypeID;
public void setItemsA(ItemClass2 itemclass2)
{
this.ContragentID = itemclass2.ContragentID;
this.ContragentTypeID = itemclass2.ContragentTypeID;
}
public void setItemsB(int ContragentID, int ContragentTypeID)
{
this.ContragentID = ContragentID;
this.ContragentTypeID = ContragentTypeID;
}
}
/*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.
Assume I have a model:
public class Person
{
public int ID {get;set;}
public string Name {get;set;}
}
And have a table in database:
person(integer ID, char Name)
How can I return IEnumerable (or List) from database when in compiler time model (Person) is unknown. For instance, I think, select method must has the following structure:
public List<object> Select(string query, Dictionary<string, object> parameters)
{
List<object> listValue = new List<object>();
using (var command = new MySqlCommand(query, connection))
{
#region fill command.Parameters.AddWithValue
if (parameters != null)
{
foreach (var param in parameters)
{
if (param.Value == null)
{
command.Parameters.AddWithValue("#" + param.Key, DBNull.Value);
continue;
}
DateTime _date = new DateTime();
if (DateTime.TryParse(param.Value.ToString(), out _date))
{
command.Parameters.AddWithValue("#" + param.Key, _date.ToString("yyyy-MM-dd"));
continue;
}
command.Parameters.AddWithValue("#" + param.Key, param.Value);
}
}
#endregion
if (connection.State == System.Data.ConnectionState.Closed) connection.Open();
try
{
using (MySqlDataReader reader = command.ExecuteReader(System.Data.CommandBehavior.CloseConnection))
{
while (reader.Read())
{
object newObject = new object();
// What must I do there?
listValue.Add(new { });
}
}
}
catch (Exception ex) { }
finally
{
if (connection.State == System.Data.ConnectionState.Open)
connection.Close();
}
}
return listValue;
}
I think u need a new argument like 'Func" to let invoker decide how to convert a datarow from database to the entity
How would one go about using Dapper with Oracle stored procedures which return cursors?
var p = new DynamicParameters();
p.Add("foo", "bar");
p.Add("baz_cursor", dbType: DbType.? , direction: ParameterDirection.Output);
Here, the DbType is System.Data.DbType which does not have a Cursor member. I've tried using DbType.Object but that does not work with both OracleClient and OracleDataAcess.
What would be a possible way to use OracleType or OracleDbType instead?
Thanks for the solution here. I achieved the same thing with a little less code using a simple DynamicParameter decorator:
public class OracleDynamicParameters : SqlMapper.IDynamicParameters
{
private readonly DynamicParameters dynamicParameters = new DynamicParameters();
private readonly List<OracleParameter> oracleParameters = new List<OracleParameter>();
public void Add(string name, object value = null, DbType? dbType = null, ParameterDirection? direction = null, int? size = null)
{
dynamicParameters.Add(name, value, dbType, direction, size);
}
public void Add(string name, OracleDbType oracleDbType, ParameterDirection direction)
{
var oracleParameter = new OracleParameter(name, oracleDbType, direction);
oracleParameters.Add(oracleParameter);
}
public void AddParameters(IDbCommand command, SqlMapper.Identity identity)
{
((SqlMapper.IDynamicParameters)dynamicParameters).AddParameters(command, identity);
var oracleCommand = command as OracleCommand;
if (oracleCommand != null)
{
oracleCommand.Parameters.AddRange(oracleParameters.ToArray());
}
}
}
You would have to implement:
public interface IDynamicParameters
{
void AddParameters(IDbCommand command, Identity identity);
}
Then in the AddParameters callback you would cast the IDbCommand to an OracleCommand and add the DB specific params.
Add this class to your project
and your code should like below :-
var p = new OracleDynamicParameters();
p.Add("param1", pAuditType);
p.Add("param2", pCommnId);
p.Add("outCursor", dbType: OracleDbType.RefCursor, direction: ParameterDirection.Output);
using (var multi = cnn.QueryMultiple("procedure_name", param: p, commandType: CommandType.StoredProcedure))
{
var data = multi.Read();
return data;
}
Just to elaborate on Sams suggestion here's what I came up with. Note that this code is brittle and is now just for Oracle.
Modified Dapper 1.7
void SqlMapper.IDynamicParameters.AddParameters(IDbCommand command, SqlMapper.Identity identity)
{
if (templates != null)
{
foreach (var template in templates)
{
var newIdent = identity.ForDynamicParameters(template.GetType());
Action<IDbCommand, object> appender;
lock (paramReaderCache)
{
if (!paramReaderCache.TryGetValue(newIdent, out appender))
{
appender = SqlMapper.CreateParamInfoGenerator(newIdent);
paramReaderCache[newIdent] = appender;
}
}
appender(command, template);
}
}
foreach (var param in parameters.Values)
{
string name = Clean(param.Name);
bool add = !((Oracle.DataAccess.Client.OracleCommand)command).Parameters.Contains(name);
Oracle.DataAccess.Client.OracleParameter p;
if(add)
{
p = ((Oracle.DataAccess.Client.OracleCommand)command).CreateParameter();
p.ParameterName = name;
} else
{
p = ((Oracle.DataAccess.Client.OracleCommand)command).Parameters[name];
}
var val = param.Value;
p.Value = val ?? DBNull.Value;
p.Direction = param.ParameterDirection;
var s = val as string;
if (s != null)
{
if (s.Length <= 4000)
{
p.Size = 4000;
}
}
if (param.Size != null)
{
p.Size = param.Size.Value;
}
if (param.DbType != null)
{
p.DbType = param.DbType.Value;
}
if (add)
{
if (param.DbType != null && param.DbType == DbType.Object)
{
p.OracleDbType = Oracle.DataAccess.Client.OracleDbType.RefCursor;
((Oracle.DataAccess.Client.OracleCommand)command).Parameters.Add(p);
}
else
{
((Oracle.DataAccess.Client.OracleCommand)command).Parameters.Add(p);
}
}
param.AttachedParam = p;
}
}
Test code
class Program
{
static void Main(string[] args)
{
OracleConnection conn = null;
try
{
const string connString = "DATA SOURCE=XE;PERSIST SECURITY INFO=True;USER ID=HR;PASSWORD=Adv41722";
conn = new OracleConnection(connString);
conn.Open();
var p = new DynamicParameters();
p.Add(":dep_id", 60);
p.Add(":employees_c", dbType: DbType.Object, direction: ParameterDirection.Output);
p.Add(":departments_c", dbType: DbType.Object, direction: ParameterDirection.Output);
// This will return an IEnumerable<Employee> // How do I return both result?
var results = conn.Query<Employee>("HR_DATA.GETCURSORS", p, commandType: CommandType.StoredProcedure);
}
catch (Exception exception)
{
Console.WriteLine(exception);
throw;
}
finally
{
if (conn != null && conn.State == ConnectionState.Open)
{
conn.Close();
}
}
Console.WriteLine("Fininhed!");
Console.ReadLine();
}
}
class Employee
{
public int Employee_ID { get; set; }
public string FIRST_NAME { get; set; }
public string LAST_NAME { get; set; }
public string EMAIL { get; set; }
public string PHONE_NUMBER { get; set; }
}