EFLite.cs
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Data;
6 using System.ComponentModel;
7 using System.Reflection;
8 using sage.ew.db;
9 
10 namespace sage.addons.offline.Negocio.Clases
11 {
15  public static class EFLite
16  {
20 
30  public static void Insert(this Object obj)
31  {
32  obj.Insert(obj.GetPropertyByName<string>("_DataBase"), obj.GetPropertyByName<string>("_Table"));
33  }
40  public static void Insert(this Object obj, string _DataBase, string _Table)
41  {
42  Tuple<string, string> ret = obj.GetNamesValues();
43  string lcSql = string.Format("INSERT INTO " + DB.SQLDatabase(_DataBase, _Table) + " ({0})" +" VALUES ({1})",ret.Item1,ret.Item2);
44  DB.SQLExec(lcSql);
45  }
50  public static void InsertOrUpdate(this Object obj)
51  {
52  string _DataBase = obj.GetPropertyByName<string>("_DataBase");
53  string _Table = obj.GetPropertyByName<string>("_Table").ToString();
54  string where = obj.GetWhere();
55 
56  if(obj.Exists(_DataBase, _Table, where))
57  {
58  if (!string.IsNullOrEmpty(where))
59  {
60  obj.Update(_DataBase, _Table, where);
61  }
62  }
63  else
64  {
65  obj.Insert();
66  }
67  }
76  public static bool Exists(this Object obj, string _DataBase, string _Table, string where)
77  {
78  DataTable dt = new DataTable();
79  string lcSql = "SELECT count(*) as existe " + " FROM " + DB.SQLDatabase(_DataBase, _Table) +
80  " WHERE " + where;
81  DB.SQLExec(lcSql, ref dt);
82  return Convert.ToInt32(dt.Rows[0]["existe"]) > 0;
83  }
93  public static Int32 NewStrId(this Object obj, string field, Int32 inc = 1, string where = "")
94  {
95  Int32 ret = inc;
96 
97  string lcSql = "Select max(CAST(" + field + " AS INT)) as maximo from " +
98  DB.SQLDatabase(obj.GetPropertyByName<string>("_DataBase"), obj.GetPropertyByName<string>("_Table"));
99  if (!string.IsNullOrEmpty(where))
100  {
101  lcSql += " WHERE " + where;
102  }
103 
104  DataTable dt = new DataTable();
105  DB.SQLExec(lcSql, ref dt);
106  if (dt.Rows.Count > 0)
107  {
108  if (dt.Rows[0]["maximo"] == DBNull.Value)
109  {
110  ret = inc;
111  }
112  else
113  {
114  ret += Convert.ToInt32(dt.Rows[0]["maximo"]);
115  }
116  }
117 
118  return ret;
119  }
128  public static Int32 NewId(this Object obj, string field, Int32 inc=1, string where="")
129  {
130  Int32 ret = inc;
131 
132  string lcSql = "Select max(" + field + ") as maximo from " +
133  DB.SQLDatabase(obj.GetPropertyByName<string>("_DataBase"), obj.GetPropertyByName<string>("_Table"));
134  if (!string.IsNullOrEmpty(where))
135  {
136  lcSql += " WHERE " + where;
137  }
138 
139  DataTable dt = new DataTable();
140  DB.SQLExec(lcSql, ref dt);
141  if (dt.Rows.Count > 0)
142  {
143  if (dt.Rows[0]["maximo"] == DBNull.Value)
144  {
145  ret = inc;
146  }
147  else
148  {
149  ret += Convert.ToInt32(dt.Rows[0]["maximo"]);
150  }
151  }
152 
153  return ret;
154  }
160  public static bool IsNullOrEmpty(this Object obj)
161  {
162  bool ret = false;
163  string myType = obj.GetType().Name.ToLower();
164  switch (myType)
165  {
166  case "string":
167  {
168  ret = obj == null || ((string)obj) == "";
169  }
170  break;
171  case "datetime":
172  {
173  ret = obj == null || ((DateTime)obj) == DateTime.MinValue;
174  }
175  break;
176  default:
177  {
178  ret = obj == null;
179  }
180  break;
181  }
182  return ret;
183  }
184 
193  public static void Delete(this Object obj)
194  {
195  DataTable dt = new DataTable();
196  string[] keys = obj.GetPropertyByName<string[]>("_keys");
197  StringBuilder sb = new StringBuilder();
198  List<string> _flds = (List<string>)obj.GetType().GetField("_flds").GetValue(obj);
199 
200  foreach (string key in keys)
201  {
202  PropertyInfo prop = obj.GetPropertyInfoByName(key);
203  object valor = prop.GetValue(obj, null);
204  if (_flds.Contains(prop.Name))
205  {
206  sb.Append(prop.Name + " = " + FormatValue(prop.PropertyType.ToString().ToLower(), valor) + " and ");
207  }
208  }
209  sb.Remove(sb.Length - 4, 4);
210  obj.Delete(obj.GetPropertyByName<string>("_DataBase"), obj.GetPropertyByName<string>("_Table"), sb.ToString());
211  }
219  public static void Delete(this Object obj, string _DataBase, string _Table, string where)
220  {
221  string lcSql = "DELETE FROM " + DB.SQLDatabase(_DataBase, _Table);
222 
223  if (!string.IsNullOrEmpty(where))
224  {
225  lcSql += " WHERE " + where;
226  DB.SQLExec(lcSql);
227  }
228  }
234  public static void Delete(this Object obj, string where)
235  {
236  obj.Delete(obj.GetPropertyByName<string>("_DataBase"), obj.GetPropertyByName<string>("_Table"), where);
237  }
245  public static void Update(this Object obj, string _DataBase, string _Table, string where)
246  {
247  string lcSql = " UPDATE " + DB.SQLDatabase(_DataBase, _Table) +
248  " SET " + "%%CAMPOSVALORES%%" +
249  " WHERE " + where;
250 
251  StringBuilder sbCamposValores = new StringBuilder();
252  Type myType = obj.GetType();
253  IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties().Where(r => r.Name.Substring(0, 1) != "_"));
254  List<string> _flds = (List<string>)obj.GetType().GetField("_flds").GetValue(obj);
255 
256  foreach (PropertyInfo prop in props)
257  {
258  AttributeCollection attributes = TypeDescriptor.GetProperties(obj)[prop.Name].Attributes;
259  //DefaultValueAttribute myAttribute = (DefaultValueAttribute)attributes[typeof(DefaultValueAttribute)];
260  object valor = prop.GetValue(obj, null);
261 
262  //if (myAttribute != null && System.Collections.Comparer.DefaultInvariant.Compare(myAttribute.Value,valor)!=0)
263  if (_flds.Contains(prop.Name))
264  {
265  sbCamposValores.Append(prop.Name + " = " + FormatValue(prop.PropertyType.ToString().ToLower(), valor) + " , ");
266  }
267  /*else
268  {
269  switch (prop.PropertyType.Name)
270  {
271  case "DateTime":
272  {
273  DateTime dateTime = new DateTime(1, 1, 1, 0, 0, 0);
274  if (prop.PropertyType.Name == "DateTime" && dateTime.CompareTo(Convert.ToDateTime(valor)) != 0)
275  {
276  sbCamposValores.Append(prop.Name + " = " + FormatValue(prop.PropertyType.ToString().ToLower(), valor) + " , ");
277  }
278  }
279  break;
280  }
281  }*/
282  }
283  sbCamposValores.Remove(sbCamposValores.Length - 2, 2);
284  lcSql = lcSql.Replace("%%CAMPOSVALORES%%", sbCamposValores.ToString());
285 
286  DB.SQLExec(lcSql);
287  _flds.Clear();
288  }
293  public static void Update(this Object obj)
294  {
295  string _DataBase = obj.GetPropertyByName<string>("_DataBase");
296  string _Table = obj.GetPropertyByName<string>("_Table").ToString();
297  string lcSql = " UPDATE " + DB.SQLDatabase(_DataBase, _Table) +
298  " SET " + "%%CAMPOSVALORES%%" +
299  " WHERE %%WHERE%%";
300 
301  StringBuilder sbKeys = new StringBuilder();
302  string[] keys = GetPropertyByName<string[]>(obj, "_keys");
303  if (keys.Length == 0)
304  return;
305  List<string> _flds = (List<string>)obj.GetType().GetField("_flds").GetValue(obj);
306  //GetPropertyByName<List<string>>(obj, "_flds");
307 
308  // Localizamos el registro por los valores de las _keys
309  StringBuilder sb = new StringBuilder();
310  foreach (string key in keys)
311  {
312  PropertyInfo prop = obj.GetPropertyInfoByName(key);
313  object valor = prop.GetValue(obj, null);
314  //if (!valor.IsNullOrEmpty())
315  if(_flds.Contains(prop.Name))
316  {
317  sb.Append(prop.Name + " = " + FormatValue(prop.PropertyType.ToString().ToLower(), valor) + " and ");
318  }
319  }
320  sb.Remove(sb.Length - 4, 4);
321  obj.Update(_DataBase, _Table, sb.ToString());
322  }
328  public static void Load(this Object obj, DataRow row)
329  {
330  foreach (DataColumn column in row.Table.Columns)
331  {
332  Type _type = Type.GetType(obj.GetType().Namespace + "." + obj.GetType().Name);
333  PropertyInfo _propertyInfo = _type.GetProperty(column.ColumnName.ToUpper());
334 
335  if (_propertyInfo != null && row[column.ColumnName] != DBNull.Value)
336  {
337  object propertyValue = System.Convert.ChangeType(row[column.ColumnName], _propertyInfo.PropertyType);
338  _propertyInfo.SetValue(obj, propertyValue, null);
339  }
340  }
341  }
342 
349  public static bool Find(this Object obj, string where = "")
350  {
351  DataTable dt = new DataTable();
352  string lcSql = " SELECT Count(*) as num FROM " + DB.SQLDatabase(obj.GetPropertyByName<string>("_DataBase"), obj.GetPropertyByName<string>("_Table")) + " WHERE ";
353  if (string.IsNullOrEmpty(where))
354  {
355  string[] keys = obj.GetPropertyByName<string[]>("_keys");
356  StringBuilder sb = new StringBuilder();
357  foreach (string key in keys)
358  {
359  PropertyInfo prop = obj.GetPropertyInfoByName(key);
360  object valor = prop.GetValue(obj, null);
361  if (!valor.IsNullOrEmpty())
362  {
363  sb.Append(prop.Name + " = " + FormatValue(prop.PropertyType.ToString().ToLower(), valor) + " and ");
364  }
365  }
366  sb.Remove(sb.Length - 4, 4);
367  lcSql += sb.ToString();
368  }
369  else
370  {
371  lcSql += where;
372  }
373  DB.SQLExec(lcSql, ref dt);
374 
375  return dt.Rows.Count > 0 && Convert.ToInt32(dt.Rows[0]["num"]) > 0;
376  }
389  public static DataTable GetDataTable(this Object obj, string[] columns = null, string where = "", string joins="", string orderby = "")
390  {
391  string _DataBase = obj.GetPropertyByName<string>("_DataBase");
392  string _Table = obj.GetPropertyByName<string>("_Table").ToString();
393  DataTable ret = new DataTable();
394  StringBuilder sb = new StringBuilder();
395  if (columns == null)
396  {
397  Type myType = obj.GetType();
398  IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties().Where(r => r.Name.Substring(0, 1) != "_"));
399 
400  foreach (PropertyInfo prop in props)
401  {
402  sb.Append(prop.Name + ", ");
403  }
404  }
405  else
406  {
407  foreach (string column in columns)
408  {
409  sb.Append(column + ", ");
410  }
411  }
412  sb.Remove(sb.Length - 2, 2);
413 
414  string lcSql = "SELECT " + sb.ToString() + " FROM " + DB.SQLDatabase(_DataBase, _Table) + " A ";
415  if (!string.IsNullOrEmpty(joins))
416  {
417  lcSql += joins;
418  }
419  if (!string.IsNullOrEmpty(where))
420  {
421  lcSql += " where " + where;
422  }
423  if (!string.IsNullOrEmpty(orderby))
424  {
425  lcSql += " ORDER BY " + orderby;
426  }
427  DB.SQLExec(lcSql, ref ret);
428  return ret;
429  }
439  public static BindingList<T> ToBindingList<T>(this Object obj, string[] columns = null, string where = "", string join = "")
440  {
441  BindingList<T> ret = new BindingList<T>();
442  DataTable dt = obj.GetDataTable(columns, where, join );
443  List<T> s = dt.ToLista<T>();
444  return new BindingList<T>(s);
445  }
455  public static List<T> ToLista<T>(this Object obj, string[] columns = null, string where = "", string join = "")
456  {
457  BindingList<T> ret = new BindingList<T>();
458  DataTable dt = obj.GetDataTable(columns, where, join);
459 
460  return dt.ToLista<T>();
461  }
468  public static List<T> ToLista<T>(this DataTable dt)
469  {
470  List<T> data = new List<T>();
471  foreach (DataRow row in dt.Rows)
472  {
473  T item = GetItem<T>(row);
474  data.Add(item);
475  }
476  return data;
477  }
484  public static T GetItem<T>(DataRow dr)
485  {
486  Type temp = typeof(T);
487  T obj = Activator.CreateInstance<T>();
488 
489  foreach (DataColumn column in dr.Table.Columns)
490  {
491  foreach (PropertyInfo pro in temp.GetProperties())
492  {
493  if (pro.Name == column.ColumnName)
494  {
495  pro.SetValue(obj, (dr[column.ColumnName] == DBNull.Value?null: dr[column.ColumnName]), null);
496  break;
497  }
498  else
499  continue;
500  }
501  }
502  return obj;
503  }
504  private static string FormatValue(string propertyType, object propValue)
505  {
506  string ret = "";
507  propertyType = propertyType.Replace("system.", "");
508  if (propertyType == "int" ||
509  propertyType == "int32" ||
510  propertyType == "decimal" ||
511  propertyType == "numeric")
512  {
513  ret = propValue.ToString().Replace(",", ".");
514  }
515  else
516  if (propertyType == "string" ||
517  propertyType == "datetime" ||
518  propertyType == "char" ||
519  propertyType == "smalldatetime" ||
520  propertyType == "text" ||
521  propertyType == "ntext")
522  {
523  ret = DB.SQLString(propValue);
524  }
525  else
526  if (propertyType == "bool" ||
527  propertyType == "boolean" ||
528  propertyType == "bit")
529  {
530  ret = Convert.ToBoolean(propValue) ? "1" : "0";
531  }
532  return ret;
533  }
547  public static T GetPropertyByName<T>(this object input, string name)
548  {
549  return (T)input
550  .GetType()
551  .GetProperty(name)?
552  .GetValue(input, null);
553  }
554 
561  public static PropertyInfo GetPropertyInfoByName(this object input, string name)
562  {
563  PropertyInfo info;
564 
565  IList<PropertyInfo> props = new List<PropertyInfo>(input.GetType().GetProperties());
566 
567  info = (PropertyInfo)props.Single(x => x.Name == name.Trim());
568 
569  return info;
570  }
576  public static string GetWhere(this Object obj)
577  {
578  string[] keys = GetPropertyByName<string[]>(obj, "_keys");
579  if (keys.Length == 0)
580  return "";
581 
582  // Localizamos el registro por los valores de las _keys
583  StringBuilder sb = new StringBuilder();
584  foreach (string key in keys)
585  {
586  PropertyInfo prop = obj.GetPropertyInfoByName(key);
587  object valor = prop.GetValue(obj, null);
588  if (!valor.IsNullOrEmpty())
589  {
590  sb.Append(prop.Name + " = " + FormatValue(prop.PropertyType.ToString().ToLower(), valor) + " and ");
591  }
592  }
593  sb.Remove(sb.Length - 4, 4);
594  return sb.ToString();
595  }
601  public static string GetWhereExt(this Object obj)
602  {
603  //Tuple<string, string> ret = obj.GetNamesValues();
604 
606  //StringBuilder sb = new StringBuilder();
607  //string[] names = ret.Item1.Split(',');
608  //string[] values = ret.Item2.Split(',');
609  //for (int i=0; i<names.Length; i++)
610  //{
611  // string name = names[i].Trim();
612  // string valor = values[i].Trim();
613  // PropertyInfo prop = obj.GetPropertyInfoByName(name);
614  // sb.Append(name + " = " + FormatValue(prop.PropertyType.ToString().ToLower(), valor) + " and ");
615  //}
616  //sb.Remove(sb.Length - 4, 4);
617  //return sb.ToString();
618  return "";
619  }
625  public static Tuple<string, string> GetNamesValues(this Object obj)
626  {
627  StringBuilder sbNames = new StringBuilder();
628  StringBuilder sbValues = new StringBuilder();
629  Type myType = obj.GetType();
630  IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties().Where(r => r.Name.Substring(0, 1) != "_"));
631  List<string> _flds = (List<string>)obj.GetType().GetField("_flds").GetValue(obj);
632 
633  foreach (PropertyInfo prop in props)
634  {
635  object valor = prop.GetValue(obj, null);
636  //AttributeCollection attributes = TypeDescriptor.GetProperties(obj)[prop.Name].Attributes;
637  //DefaultValueAttribute myAttribute = (DefaultValueAttribute)attributes[typeof(DefaultValueAttribute)];
638 
639  //if (myAttribute != null && System.Collections.Comparer.DefaultInvariant.Compare(myAttribute.Value, valor) != 0)
640  if (_flds.Contains(prop.Name))
641  {
642  sbNames.Append(prop.Name + ", ");
643  sbValues.Append(FormatValue(prop.PropertyType.ToString().ToLower(), valor) + ", ");
644  //sbCamposValores.Append(prop.Name + " = " + FormatValue(prop.PropertyType.ToString().ToLower(), valor) + " , ");
645  }
646  else
647  {
648  switch (prop.PropertyType.Name)
649  {
650  case "DateTime":
651  {
652  DateTime dateTime = new DateTime(1, 1, 1, 0, 0, 0);
653  if (prop.PropertyType.Name == "DateTime" && dateTime.CompareTo(Convert.ToDateTime(valor)) != 0)
654  {
655  sbNames.Append(prop.Name + ", ");
656  sbValues.Append(FormatValue(prop.PropertyType.ToString().ToLower(), valor) + ", ");
657  }
658  }
659  break;
660  }
661  }
662  }
663 
664  sbNames.Remove(sbNames.Length - 2, 2); // quitar las últimas comas
665  sbValues.Remove(sbValues.Length - 2, 2);
666 
667  // _flds.Clear();
668  return new Tuple<string,string>(sbNames.ToString(), sbValues.ToString());
669  }
683 
684  public static string InnerJoin(this Object obj, string asobj, string rel1, Object obj2, string asobj2, string rel2)
685  {
686  // Pendiente de desarrollar
687  string lcSql = "";
688 
689 
690  return lcSql;
691  }
700  public static T GetFieldValue<T>(this Object obj, string fieldName, string where)
701  {
702  T ret = default(T);
703 
704  DataTable dt = obj.GetDataTable(new string[] { fieldName }, where);
705 
706  if (dt != null && dt.Rows.Count == 1)
707  {
708  ret = (T)Convert.ChangeType(dt.Rows[0][fieldName], typeof(T) );
709  }
710  return ret;
711  }
719  public static void AddExt<T>(this List<T> lista, T dato)
720  {
721  if (!lista.Contains(dato))
722  {
723  lista.Add(dato);
724  }
725  }
726  }
727 }
Es como el tipo de entrada asientos pero por negocio, sin formulario, pq quiero que me haga las propu...
Consulta de una declaración existente