You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
DS7/HcDBUtility/Core/ModelObjectBill.cs

821 lines
28 KiB
C#

3 years ago
using System;
using System.ComponentModel;
using System.Reflection;
using HcUtility.Comm;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data.Common;
using System.Data;
using System.Text;
using System.Collections.Generic;
using Newtonsoft.Json.Converters;
namespace HcUtility.Core
{
/// <summary>
/// 功能: 业务单据的基类
/// 创建: 吴伟 2009-05-07
/// 说明:
/// </summary>
///
public abstract class ModelObjectBill : ModelObjectBase
{
virtual public string GetBillNoFieldName()
{
return "BillNo";
}
virtual public string GetStateFieldName()
{
return "STATE";
}
virtual public string GetOrgCode()
{
return "OrgCode";
}
virtual public string GetYwTypeFieldName()
{
return "YwType";
}
virtual public string GetTimeMarkFieldName()
{
return "TimeMark";
}
virtual public string GetCompanyFieldName()
{
return "CORPID";
}
virtual public string GetDeptFieldName()
{
return "SALEDEPT";
}
/// <summary>
/// 用于某些实体类保存后更新一次timemark 以便连续进行保存
/// </summary>
virtual public void TimeMarkNext()
{
var _TimeMarkField = GetTimeMarkFieldName();
if (!string.IsNullOrEmpty(_TimeMarkField))
{
var TimeMarkValue = Convert.ToInt32(GetValue(_TimeMarkField));
TimeMarkValue++;
SetValue(_TimeMarkField, TimeMarkValue.ToString());
}
}
virtual public object GetBillNoValue()
{
return GetPropertyValue(GetBillNoFieldName());
}
virtual public object GetStateValue()
{
return GetPropertyValue(GetStateFieldName());
}
//virtual public List<Fieldmb> GetFieldList()
//{
// //从数据库获取字段信息表
// var headList = new List<Fieldmb>();
// Database db = DatabaseFactory.CreateDatabase();
// string sql = "select * from tSYS_FieldInfo where TABLENAME='" + TableName + "' ";
// using (IDataReader reader = db.ExecuteReader(CommandType.Text, sql))
// {
// while (reader.Read())
// {
// Fieldmb data = new Fieldmb();
// #region Set DB data to Object
// data.GID = Convert.ToString(reader["GID"]);
// data.TABLENAME = Convert.ToString(reader["TABLENAME"]);
// data.FIELDNAME = Convert.ToString(reader["FIELDNAME"]);
// data.FIELDTYPE = Convert.ToString(reader["FIELDTYPE"]);
// data.DEFAULTVALUE = Convert.ToString(reader["DEFAULTVALUE"]);
// data.NOTFLANK = Convert.ToString(reader["NOTFLANK"]);
// data.DECIMALLIMIT = Convert.ToString(reader["DECIMALLIMIT"]);
// data.SORT = Convert.ToString(reader["SORT"]);
// data.VIEWTYPE = Convert.ToString(reader["VIEWTYPE"]);
// data.WIDTH = Convert.ToString(reader["WIDTH"]);
// data.HEIGHT = Convert.ToString(reader["HEIGHT"]);
// #endregion
// headList.Add(data);
// }
// reader.Close();
// }
// return headList;
// //return FieldList;
//}
//取得新的单据号
//获取新的业务编号
public static List<Dictionary<string, string>> getDicList(List<ModelObjectBase> ExtendObjectList)
{
var list = new List<Dictionary<string, string>>();
if (ExtendObjectList.Count > 0)
{
foreach (var data in ExtendObjectList)
{
list.Add(data.ExtendDic);
}
}
return list;
}
virtual public string GetNewBillNo(Database db)
{
string billNo = String.Empty;
using (DbCommand cmd = db.GetStoredProcCommand("sSysGetBillNo"))
{
db.AddInParameter(cmd, "ps_BillType", DbType.String, GetPropertyValue(GetYwTypeFieldName()).ToString());
db.AddOutParameter(cmd, "ps_BillNo", DbType.String, 20);
db.ExecuteNonQuery(cmd);
billNo = Convert.ToString(db.GetParameterValue(cmd, "ps_BillNo"));
}
return billNo;
}
//检查时间戳
virtual public DBResult CheckTimeMark(Database db, IDbConnection idbConn, IDbTransaction idbTran, ref List<DbCommand> listCmd)
{
DBResult result = new DBResult();
result.Success = true;
result.Message = "";
string timeMarkFieldName = this.GetTimeMarkFieldName();
if (!string.IsNullOrEmpty(timeMarkFieldName))
{
ModelDBAttribute attribute;
if ((base.DbOperationType != DbOperationType.DbotUpd) && (base.DbOperationType != DbOperationType.DbotDel))
{
return result;
}
DbCommand sqlStringCommand = null;
string str2 = string.Empty;
string str3 = string.Empty;
StringBuilder builder = new StringBuilder();
StringBuilder builder2 = new StringBuilder();
builder.Append("select convert(bigint ," + timeMarkFieldName + ") from " + base.TableName);
builder.Append(" where ");
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(this);
foreach (PropertyDescriptor descriptor in properties)
{
foreach (Attribute attribute2 in descriptor.Attributes)
{
if (attribute2 is ModelDBAttribute)
{
attribute = (ModelDBAttribute)attribute2;
if (ModelDBOprationType.Edit == (ModelDBOprationType.Edit & attribute.MDBType))
{
str2 = (attribute.UpdFieldName == string.Empty) ? descriptor.Name : attribute.UpdFieldName;
str3 = (attribute.UpdParamName == string.Empty) ? descriptor.Name : attribute.UpdParamName;
if (attribute.IsPrimary)
{
if (builder2.Length != 0)
{
builder2.Append(" and ");
}
builder2.Append(str2 + "=@" + str3);
}
}
}
}
}
if (Extended())
{
foreach (var d in ExtendDataList)
{
if (d.MDB.IsPrimary)
{
if (builder2.Length != 0)
{
builder2.Append(" and ");
}
builder2.Append("[" + d.Name + "]" + "=@" + d.Name);
}
}
}
builder.Append(builder2.ToString());
sqlStringCommand = db.GetSqlStringCommand(builder.ToString());
sqlStringCommand.Connection = (DbConnection)idbConn;
sqlStringCommand.Transaction = (DbTransaction)idbTran;
foreach (PropertyDescriptor descriptor in properties)
{
foreach (Attribute attribute2 in descriptor.Attributes)
{
if (attribute2 is ModelDBAttribute)
{
attribute = (ModelDBAttribute)attribute2;
if (ModelDBOprationType.Edit == (ModelDBOprationType.Edit & attribute.MDBType))
{
str2 = (attribute.UpdFieldName == string.Empty) ? descriptor.Name : attribute.UpdFieldName;
str3 = (attribute.UpdParamName == string.Empty) ? descriptor.Name : attribute.UpdParamName;
if (attribute.IsPrimary)
{
str3 = (attribute.UpdParamName == string.Empty) ? descriptor.Name : attribute.UpdParamName;
DbType dbType = TypeConvertUtil.ConverTypeToDbType(descriptor.PropertyType);
object obj2 = descriptor.GetValue(this);
db.AddInParameter(sqlStringCommand, "@" + str3, dbType, descriptor.GetValue(this));
}
}
}
}
}
if (Extended())
{
foreach (var d in ExtendDataList)
{
if (d.MDB.IsPrimary)
{
db.AddInParameter(sqlStringCommand, "@" + d.Name, DbType.String, d.Value);
}
}
}
if (listCmd != null)
{
listCmd.Add(sqlStringCommand);
}
object obj3 = sqlStringCommand.ExecuteScalar();
object propertyValue = this.GetPropertyValue(this.GetTimeMarkFieldName());
if (!(Convert.ToDecimal(obj3) == Convert.ToDecimal(propertyValue)))
{
result.Success = false;
result.Message = "数据已被其他人修改!请刷新后重试!";
}
}
return result;
}
//删除前处理
public virtual DBResult BeforeDeleteHandler(Database db, IDbConnection idbConn, IDbTransaction idbTran)
{
string prcName = "sMsSysBeforeDelete";
return this.ProcedureHandlerComm(db, idbConn, idbTran, prcName);
}
//删除后处理
public virtual DBResult AfterDeleteHandler(Database db, IDbConnection idbConn, IDbTransaction idbTran)
{
string prcName = "sMsSysAfterDelete";
return this.ProcedureHandlerComm(db, idbConn, idbTran, prcName);
}
//保存后处理
virtual public DBResult AfterSaveHandler(Database db, IDbConnection idbConn, IDbTransaction idbTran, ref List<DbCommand> listCmd)
{
string prcName = "sMsSysAfterSave";
return this.ProcedureHandlerComm(db, idbConn, idbTran, prcName);
}
private DBResult ProcedureHandlerComm(Database db, IDbConnection idbConn, IDbTransaction idbTran, string prcName)
{
DBResult result = new DBResult();
result.Success = true;
string ywTypeFieldName = this.GetYwTypeFieldName();
string str2 = Convert.ToString(this.GetPropertyValue(ywTypeFieldName));
if (string.IsNullOrEmpty(str2))
{
result.Success = true;
result.Message = "不需要处理";
return result;
}
try
{
DbCommand storedProcCommand = db.GetStoredProcCommand(prcName);
storedProcCommand.Connection = (DbConnection)idbConn;
storedProcCommand.Transaction = (DbTransaction)idbTran;
storedProcCommand.Parameters.Clear();
db.AddInParameter(storedProcCommand, "ps_BillNo", DbType.String, this.GetPropertyValue(this.GetBillNoFieldName()).ToString());
db.AddInParameter(storedProcCommand, "ps_YwType", DbType.String, str2);
decimal loginUserID = 0M;
string loginUserCode = string.Empty;
string loginUserName = string.Empty;
if (this is ModelObjectBillHead)
{
ModelObjectBillHead head = (ModelObjectBillHead)this;
loginUserID = head.LoginUserID;
loginUserCode = head.LoginUserCode;
loginUserName = head.LoginUserName;
}
db.AddInParameter(storedProcCommand, "ps_UserCode", DbType.String, loginUserCode);
db.AddInParameter(storedProcCommand, "ps_UserName", DbType.String, loginUserName);
db.AddOutParameter(storedProcCommand, "pi_Result", DbType.Int32, 0x20);
db.AddOutParameter(storedProcCommand, "ps_Message", DbType.String, 0x7d0);
storedProcCommand.ExecuteNonQuery();
result.Success = Convert.ToInt32(db.GetParameterValue(storedProcCommand, "pi_Result")) == 1;
result.Message = Convert.ToString(db.GetParameterValue(storedProcCommand, "ps_Message"));
if (!result.Success)
{
throw new ModelDbException(result.Message);
}
}
catch (Exception exception)
{
result.Success = false;
if (!(exception is ModelDbException))
{
result.Message = exception.ToString();
}
}
return result;
}
//取得属性的值
public object GetPropertyValue(string propertyname)
{
Type type = null;
try
{
type = this.GetType();
PropertyInfo myPropInfo = type.GetProperty(propertyname);
if (myPropInfo != null)
{
object value = myPropInfo.GetValue(this, null);
if (string.IsNullOrEmpty(value.ToString()))
{
return GetExtendValue(propertyname);
}
else
return value;
}
else
{
return GetExtendValue(propertyname);
}
}
catch
{
return String.Empty;
}
}
public string GetValue(string propertyname)
{
return GetPropertyValue(propertyname).ToString();
}
public bool isnew() {
var result = false;
if (GetValue(GetBillNoFieldName()) == "*" || string.IsNullOrWhiteSpace(GetValue(GetBillNoFieldName())))
{
result = true;
}
return result;
}
public int GetInt32(string propertyname)
{
string _r = GetPropertyValue(propertyname).ToString();
var result = 0;
var _r2 = isNumberic(_r,out result);
return result;
}
public Decimal GetDecimal(string propertyname)
{
string _r = GetPropertyValue(propertyname).ToString();
Decimal result = 0;
var _r2 = isDecimal(_r, out result);
return result;
}
protected bool isNumberic(string message, out int result)
{
//判断是否为整数字符串
//是的话则将其转换为数字并将其设为out类型的输出值、返回true, 否则为false
result = 0; //result 定义为out 用来输出值
try
{
//当数字字符串的为是少于4时以下三种都可以转换任选一种
//如果位数超过4的话请选用Convert.ToInt32() 和int.Parse()
//result = int.Parse(message);
//result = Convert.ToInt16(message);
result = Convert.ToInt32(message);
return true;
}
catch
{
return false;
}
}
protected bool isDecimal(string message, out Decimal result)
{
//判断是否为整数字符串
//是的话则将其转换为数字并将其设为out类型的输出值、返回true, 否则为false
result = 0; //result 定义为out 用来输出值
try
{
//当数字字符串的为是少于4时以下三种都可以转换任选一种
//如果位数超过4的话请选用Convert.ToInt32() 和int.Parse()
//result = int.Parse(message);
//result = Convert.ToInt16(message);
result = Convert.ToDecimal(message);
return true;
}
catch
{
return false;
}
}
public bool GetBoolen(string propertyname)
{
var _r = GetPropertyValue(propertyname).ToString();
bool result = (_r.Trim() == ""|| _r=="false"|| _r == "False" || _r == "0") ? false : true;
return result;
}
public Decimal GetMoney(string propertyname)
{
try
{
var result = Convert.ToDecimal(GetValue(propertyname));
return result;
}
catch
{
return -1;
}
}
//public class ModelObjectConvert<T> where T:ModelObjectBase
//{
// private static ModelObjectBase Converter(T inputObject)
// {
// return inputObject;
// }
// public static List<ModelObjectBase> ToModelObjectList(List<T> objList)
// {
// if (objList == null)
// return null;
// return objList.ConvertAll<ModelObjectBase>(new Converter<T, ModelObjectBase>(Converter));
// }
// public static List<Dictionary<string,string>> ToExtendList(List<T> objList)
// {
// if (objList == null)
// return null;
// else{
// var result = new List<Dictionary<string,string>>();
// foreach(var obj in objList){
// result.Add(obj.ExtendDic);
// }
// return result;
// }
// }
//}
/////////////
//设置属性的值
/// <summary>
/// ///////////
/// </summary>
/// <param name="propertyname"></param>
/// <param name="value"></param>
/// <returns></returns>
public bool SetPropertyValue(string propertyname, object value)
{
Type type = null;
try
{
type = this.GetType();
PropertyInfo myPropInfo = type.GetProperty(propertyname);
if (myPropInfo != null)
{
myPropInfo.SetValue(this, value, null);
return true;
}
else
{
return SetExtendValue(propertyname, value.ToString());
}
}
catch (NullReferenceException e)
{
throw new Exception(type.ToString() + "中没有(" + propertyname + ")属性!错误信息:" + e.ToString());
}
}
public bool SetPropertyValue(IDataReader reader)
{
for (int i = 0; i < reader.FieldCount; i++)
{
var _name = reader.GetName(i);
var _value = Convert.ToString(reader.GetValue(i));
try
{
SetPropertyValue(reader.GetName(i), Convert.ToString(reader.GetValue(i)));
}
catch (NullReferenceException e)
{
throw e;
}
}
return true;
}
public bool AddDBParam(string propertyName, object propertyValue)
{
//动态添加一个name=propertyName value=propertyValue的属性
//令其Attribut为ModelDBAttribute
//try
//{
// var newproperty = new System.Collections.Generic.KeyValuePair<string, object>(propertyName, propertyValue);
// (this as System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<string, object>>).Add(newproperty);
//}
//catch (Exception e) {
// throw e;
//}
return false;
//var ca = TypeDescriptor.GetAttributes(this).OfType<ModelDBAttribute>();
//TypeDescriptor.AddAttributes(typeof(this), new CategoryAttribute("naughty"));
//ca = TypeDescriptor.GetAttributes(typeof(ModelDBAttribute)).OfType<CategoryAttribute>().FirstOrDefault();
}
/// <summary>
/// 获取扩展的属性值
/// </summary>
/// <param name="propertyname"></param>
/// <returns></returns>
public object GetExtendValue(string propertyname)
{
if (Extended())
{
foreach (var d in ExtendDataList)
{
if (d.Name == propertyname) return d.Value;
}
}
return String.Empty;
}
//设置属性的值
public bool SetExtendValue(string propertyname, string value)
{
if (Extended())
{
if (Have(propertyname))
{
foreach (var d in ExtendDataList)
{
if (d.Name == propertyname)
{
d.Value = value;
return true;
}
}
}
else
{
AddExtendDate(propertyname, value);
return true;
}
}
else
{
AddExtendDate(propertyname, value);
return true;
}
return false;
}
//private void AddEData(string propertyname, string value)
//{
// var _dt = GetPKey();
// if ((_dt[propertyname] & ModelDBOprationType.All) > 0)
// {
// AddExtendDate(propertyname, value, true, _dt[propertyname]);
// }
// else
// {
// AddExtendDate(propertyname, value);
// }
//}
public bool SetExtendValue(IDataReader reader, bool upper = false)
{
for (int i = 0; i < reader.FieldCount; i++)
{
var _name = reader.GetName(i);
var _value = Convert.ToString(reader.GetValue(i));
if (upper) _value = _value.ToUpper();
try
{
SetExtendValue(_name, _value);
}
catch (NullReferenceException e)
{
throw e;
}
}
return true;
}
public bool SetExtendValue(DataTable table,DataRow row) {
var namelist = GetColumnsByDataTable(table);
int a = table.Rows.Count;
var _i = 0;
foreach (var fieldname in namelist) {
var value = row[_i].ToString();
SetValue(fieldname, value);
_i++;
}
return true;
}
public static string[] GetColumnsByDataTable(DataTable dt)
{
string[] strColumns = null;
if (dt.Columns.Count > 0)
{
int columnNum = 0;
columnNum = dt.Columns.Count;
strColumns = new string[columnNum];
for (int i = 0; i < dt.Columns.Count; i++)
{
strColumns[i] = dt.Columns[i].ColumnName;
}
}
return strColumns;
}
public void SetExtendValue_Save(Dictionary<string, string> SaveDicList)
{
foreach (var d in SaveDicList)
{
try
{
if (d.Value == null)
{
SetExtendValue(d.Key, "");
}else
SetExtendValue(d.Key, d.Value.ToString());
}
catch (NullReferenceException e)
{
throw e;
}
}
}
public void SetExtendValue_Null(Dictionary<string, string> SaveDicList)
{
foreach (var d in SaveDicList)
{
try
{
SetExtendValue(d.Key, "");
}
catch (NullReferenceException e)
{
throw e;
}
}
}
//获取表的字段值
public void GetTableField(Database db)
{
this.SaveDic.Clear();
using (DbCommand cmd = db.GetSqlStringCommand("select sc.name Name, case when st.name='timestamp' then 0 when st.name='image' then 0 else 1 end CanSave from syscolumns sc,systypes st where sc.xtype=st.xtype and sc.id in(select id from sysobjects where xtype='U' and name='" + TableName + "')"))
{
var reader = db.ExecuteReader(cmd);
while (reader.Read())
{
var Name = Convert.ToString(reader["Name"]);
if (!this.SaveDic.ContainsKey(Name))
this.SaveDic.Add(Name, Convert.ToString(reader["CanSave"]));
}
}
}
public static T Deserialize<T>(string json)
{//只为了解析成Dictionary<string, string>
T obj = Activator.CreateInstance<T>();
var jsonObj = json;
if (json == null)
jsonObj = string.Empty;
obj = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(jsonObj);
return obj;
}
public void SetValue(Database db, string JsonStr)
{
this.GetTableField(db);
var _Dic = Deserialize<Dictionary<string, string>>(JsonStr);
this.SetExtendValue_Save(_Dic);
}
public void SetValue(Database db, Dictionary<string, string> Dic)
{
//this.GetTableField(db);
//var _Dic = Deserialize<Dictionary<string, string>>(JsonStr);
this.SetExtendValue_Save(Dic);
}
public void SetValue(Dictionary<string, string> Dic)
{
//this.GetTableField(db);
//var _Dic = Deserialize<Dictionary<string, string>>(JsonStr);
this.SetExtendValue_Save(Dic);
}
public void SetValue(string Name, string Value)
{
//this.GetTableField(db);
//var _Dic = Deserialize<Dictionary<string, string>>(JsonStr);
this.SetExtendValue(Name, Value);
}
public bool isNull(string Name) {
if (string.IsNullOrWhiteSpace(GetValue(Name)))
{
return true;
}
else
return false;
}
/// <summary>
/// 如果被写入的值为空 则将值写入
/// 用于填充默认值(有值的就不填默认进去了)
/// </summary>
/// <param name="Name"></param>
/// <param name="DefValue"></param>
public void setNoNullDef(string Name,string DefValue="0")
{
if (isNull(Name))
{
SetValue(Name, DefValue);
}
}
/// <summary>
/// 如果值不为空 则将值写入
/// 用于批量修改(未设置值的数据将不会被更新成空)
/// </summary>
/// <param name="Name"></param>
/// <param name="Value"></param>
public void setValue_NoNull(string Name, string Value)
{
if (!string.IsNullOrWhiteSpace(Value))
{
SetValue(Name, Value);
}
}
public void SetBoolToTinyint(string Name)
{
var v = this.GetExtendValue(Name).ToString();
if (v == "true")
{
this.SetExtendValue(Name, "1");
}
else
{
this.SetExtendValue(Name, "0");
}
}
}
}