主要记录工作当中遇到的一些问题和总结的一些经验

客户端请求-->web服务接口-->sql 语句执行(存储在数据库中)-->web服务(客户端通过调用web服务接口)-->返回DataTable或Dataset(sql server)--> 统一的DataTable或Dataset转换成对象-->提交给客户端(xml、json等等其他的)

1、首先通过sql语句返回结果,返回的结果一般都以Dataset的形式和DataTable的形式返回。

2、统一的DataTable或Dataset转换成对象

 #region 写对象信息

         /// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="tableName"></param>
/// <returns></returns>
public T WriteTObjectInfo<T>(string tableName, DataRow dr, string[] exceptArray)
{
try
{
if (this.Status == )
{
throw new Exception(this.Msg);
} T item = Activator.CreateInstance<T>(); List<Parameter> listParameter = GetProperties<T>(item, exceptArray); foreach (Parameter p in listParameter)
{
foreach (DataColumn dc in this.dsResult.Tables[tableName].Columns)
{
if (dc.ColumnName == p.Name)
{
Type type = item.GetType(); MethodInfo method = type.GetMethod("SetAttributeValue"); method.Invoke(item, new object[] { p.Name, dr[p.Name].ToString().Trim() });
}
}
} return item;
}
catch (Exception ex)
{
throw new Exception("写" + Activator.CreateInstance<T>().ToString() + "信息发生错误,错误原因:" + ex.Message);
}
} /// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="tableName"></param>
/// <returns></returns>
public T WriteTObjectInfo<T>(string tableName)
{
try
{
if (this.Status == )
{
throw new Exception(this.Msg);
} T item = Activator.CreateInstance<T>(); if (this.dsResult.Tables.Contains(tableName))
{
DataRow dr = this.dsResult.Tables[tableName].Rows[]; List<Parameter> listParameter = GetProperties<T>(item); foreach (Parameter p in listParameter)
{
foreach (DataColumn dc in this.dsResult.Tables[tableName].Columns)
{
if (dc.ColumnName == p.Name)
{
Type type = item.GetType(); MethodInfo method = type.GetMethod("SetAttributeValue"); method.Invoke(item, new object[] { p.Name, dr[p.Name].ToString().Trim() });
}
}
}
} return item;
}
catch (Exception ex)
{
throw new Exception("写" + Activator.CreateInstance<T>() + "信息发生错误,错误原因:" + ex.Message);
}
} /// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="tableName"></param>
/// <returns></returns>
public T WriteTObjectInfo<T>(string tableName, string[] exceptArray)
{
try
{
if (this.Status == )
{
throw new Exception(this.Msg);
} T item = Activator.CreateInstance<T>(); if (this.dsResult.Tables.Contains(tableName))
{
DataRow dr = this.dsResult.Tables[tableName].Rows[]; List<Parameter> listParameter = GetProperties<T>(item, exceptArray); foreach (Parameter p in listParameter)
{
foreach (DataColumn dc in this.dsResult.Tables[tableName].Columns)
{
if (dc.ColumnName == p.Name)
{
Type type = item.GetType(); MethodInfo method = type.GetMethod("SetAttributeValue"); method.Invoke(item, new object[] { p.Name, dr[p.Name].ToString().Trim() });
}
}
}
} return item;
}
catch (Exception ex)
{
throw new Exception("写" + Activator.CreateInstance<T>() + "信息发生错误,错误原因:" + ex.Message);
}
} /// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="tableName"></param>
/// <returns></returns>
public List<T> WriteTObjectInfoList<T>(string tableName, string[] exceptArray)
{
try
{
if (this.Status == )
{
throw new Exception(this.Msg);
} List<T> list = new List<T>(); if (this.dsResult.Tables.Contains(tableName))
{
foreach (DataRow dr in this.dsResult.Tables[tableName].Rows)
{
T item = WriteTObjectInfo<T>(tableName, dr, exceptArray); list.Add(item);
}
} return list;
}
catch (Exception ex)
{
throw new Exception("写" + Activator.CreateInstance<T>().ToString() + "信息发生错误,错误原因:" + ex.Message);
}
} /// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="tableName"></param>
/// <returns></returns>
public List<T> WriteTObjectInfoList<T>(string tableName)
{
return WriteTObjectInfoList<T>(tableName, new string[] { });
} #endregion

  以上代码统一用泛型实现

比较实用的获取属性的代码

 /// <summary>
/// 获取对象的属性名称、值和描述
/// </summary>
/// <typeparam name="T">对象的类型</typeparam>
/// <param name="t">对象</param>
/// <returns>对象列表</returns>
public List<Parameter> GetProperties<T>(T t)
{
List<Parameter> list = new List<Parameter>(); if (t == null)
{
return list;
}
PropertyInfo[] properties = t.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); if (properties.Length <= )
{
return list;
}
foreach (PropertyInfo item in properties)
{
string name = item.Name; //名称
object value = item.GetValue(t, null); //值 string des = string.Empty; try
{
des = ((DescriptionAttribute)Attribute.GetCustomAttribute(item, typeof(DescriptionAttribute))).Description;// 属性值
}
catch { } if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))
{
Parameter parameter = new Parameter(); parameter.Name = name;
parameter.Value = value == null ? "" : value.ToString();
parameter.Object = des; list.Add(parameter);
}
else
{
GetProperties(value);
}
}
return list;
} /// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <param name="exceptArray"></param>
/// <returns></returns>
public List<Parameter> GetProperties<T>(T t, string[] exceptArray)
{
List<Parameter> list = new List<Parameter>(); if (t == null)
{
return list;
}
PropertyInfo[] properties = t.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); if (properties.Length <= )
{
return list;
}
foreach (PropertyInfo item in properties)
{
string name = item.Name; //名称
object value = item.GetValue(t, null); //值
string des = string.Empty; try
{
des = ((DescriptionAttribute)Attribute.GetCustomAttribute(item, typeof(DescriptionAttribute))).Description;// 属性值
}
catch (Exception ex)
{
des = string.Empty;
} if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))
{
if (!((IList)exceptArray).Contains(name))
{
Parameter parameter = new Parameter(); parameter.Name = name;
parameter.Value = value == null ? "" : value.ToString();
parameter.Object = des; list.Add(parameter);
}
}
else
{
GetProperties(value);
}
}
return list;
}

基础的Parameter类

 public class Parameter
{
/// <summary>
/// 名称
/// </summary>
private string _name = string.Empty; /// <summary>
/// 获取或设置名称
/// </summary>
public string Name
{
get { return this._name; }
set { this._name = value; }
} /// <summary>
/// 值
/// </summary>
private string _value = string.Empty; /// <summary>
/// 获取或设置值
/// </summary>
public string Value
{
get { return this._value; }
set { this._value = value; }
} private object _object = null; public object Object
{
get { return this._object; }
set { this._object = value; }
} /// <summary>
/// 构造函数
/// </summary>
/// <param name="name">名称</param>
/// <param name="value">值</param>
public Parameter(string name, string value)
{
this.Name = name;
this.Value = value;
} public Parameter(string name, object obj)
{
this.Name = name;
this.Object = obj;
} /// <summary>
/// 构造函数
/// </summary>
public Parameter()
{ } /// <summary>
///
/// </summary>
/// <returns></returns>
public override string ToString()
{
return string.Format(@"名称(Name):{0},值(Value):{1},对象(Object):{2}", this.Name, this.Value, this.Object);
}
}

对象例子(这个对象例子的类,这个类其实和上面的DataTable和Dataset是对应的,通过以上的操作可以把DataTable或Dataset转换成具体的对象),因为这个类是比较统一的可以用代码生成工具可以直接生成

 public class Log
{
#region 属性 [Description("数据日志编号")]
public string LogID { get; set; } [Description("设备编号")]
public string DeviceID { get; set; } [Description("设备名称")]
public string DeviceName { get; set; } [Description("质控项目编号")]
public string QCItemDicID { get; set; } [Description("质控项目中文名称")]
public string CNName { get; set; } [Description("质控项目英文名称")]
public string ENName { get; set; } [Description("质控项目名称简拼码")]
public string JPM { get; set; } [Description("质控项目名称简拼码")]
public string NameAB { get; set; } [Description("质控项目单位")]
public string Unit { get; set; } [Description("设备质控编号")]
public string Dev_QC_No { get; set; } [Description("设备质控序号")]
public string Dev_QC_SequenceNo { get; set; } [Description("设备质控名称")]
public string Dev_QC_Name { get; set; } [Description("质控时间")]
public string QCTime { get; set; } [Description("值类型")]
public string TextType { get; set; } [Description("数值")]
public string ItemValue { get; set; } [Description("创建时间")]
public string CreateTime { get; set; } [Description("创建人")]
public string CreateUser { get; set; } [Description("序号(通道号)")]
public string Serial { get; set; } #endregion /// <summary>
/// 设置属性值
/// </summary>
/// <param name="name">名称</param>
/// <param name="value">值</param>
public void SetAttributeValue(string name, string value)
{
switch (name)
{
case "LogID"://数据日志编号
this.LogID = value;
break;
case "DeviceID"://设备编号
this.DeviceID = value;
break;
case "DeviceName"://设备名称
this.DeviceName = value;
break;
case "QCItemDicID"://质控项目编号
this.QCItemDicID = value;
break;
case "CNName"://质控项目中文名称
this.CNName = value;
break;
case "ENName"://质控项目英文名称
this.ENName = value;
break;
case "JPM"://质控项目名称简拼码
this.JPM = value;
break;
case "NameAB"://质控项目名称简拼码
this.NameAB = value;
break;
case "Unit"://质控项目单位
this.Unit = value;
break;
case "Dev_QC_No"://设备质控编号
this.Dev_QC_No = value;
break;
case "Dev_QC_SequenceNo"://设备质控序号
this.Dev_QC_SequenceNo = value;
break;
case "Dev_QC_Name"://设备质控名称
this.Dev_QC_Name = value;
break;
case "QCTime"://质控时间
this.QCTime = value;
break;
case "TextType"://值类型
this.TextType = value;
break;
case "ItemValue"://数值
this.ItemValue = value;
break;
case "CreateTime"://创建时间
this.CreateTime = value;
break;
case "CreateUser"://创建人
this.CreateUser = value;
break;
case "Serial"://序号(通道号)
this.Serial = value;
break;
default:
break;
}
}
}

另外也可以把对象转换成DataTable或Dataset 根据具体使用的情况进行具体的转换

 #region 获取对象和对象转换成DataTable

         /// <summary>
/// 返回数据列
/// </summary>
/// <param name="columnName"></param>
/// <param name="caption"></param>
/// <returns></returns>
public static DataColumn AddDataColumn(string columnName, string caption)
{
DataColumn dc = new DataColumn(); dc.ColumnName = columnName;
dc.Caption = caption; return dc;
} /// <summary>
/// 获取表格的数据列
/// </summary>
/// <param name="name"></param>
/// <param name="caption"></param>
/// <returns></returns>
public static DataColumn GetColumn(string name, string caption)
{
DataColumn dc = new DataColumn(); dc.ColumnName = name;
dc.Caption = caption; return dc;
} /// <summary>
/// 获取对象的属性名称、值和描述
/// </summary>
/// <typeparam name="T">对象的类型</typeparam>
/// <param name="t">对象</param>
/// <returns>对象列表</returns>
public static List<Parameter> GetProperties<T>(T t)
{
List<Parameter> list = new List<Parameter>(); if (t == null)
{
return list;
}
System.Reflection.PropertyInfo[] properties = t.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); if (properties.Length <= )
{
return list;
}
foreach (System.Reflection.PropertyInfo item in properties)
{
string name = item.Name; //名称
object value = item.GetValue(t, null); //值
string des = string.Empty; try
{
des = ((DescriptionAttribute)Attribute.GetCustomAttribute(item, typeof(DescriptionAttribute))).Description;// 属性值
}
catch { } if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))
{
Parameter parameter = new Parameter(); parameter.Name = name;
parameter.Value = value == null ? string.Empty : value.ToString();
parameter.Object = des; list.Add(parameter);
}
else
{
GetProperties(value);
}
}
return list;
} /// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <param name="exceptArray"></param>
/// <returns></returns>
public static List<Parameter> GetProperties<T>(T t, string[] exceptArray)
{
List<Parameter> list = new List<Parameter>(); if (t == null)
{
return list;
}
PropertyInfo[] properties = t.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); if (properties.Length <= )
{
return list;
}
foreach (PropertyInfo item in properties)
{
string name = item.Name; //名称
object value = item.GetValue(t, null); //值
string des = string.Empty; try
{
des = ((DescriptionAttribute)Attribute.GetCustomAttribute(item, typeof(DescriptionAttribute))).Description;// 属性值
}
catch (Exception ex)
{
des = string.Empty;
} if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))
{
if (!((IList)exceptArray).Contains(name))
{
Parameter parameter = new Parameter(); parameter.Name = name;
parameter.Value = value == null ? "" : value.ToString();
parameter.Object = des; list.Add(parameter);
}
}
else
{
GetProperties(value);
}
}
return list;
} /// <summary>
/// 类型对象生成DataTable
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <returns></returns>
public static DataTable TToDataTable<T>(T obj, List<T> listT)
{
DataTable dt = new DataTable(); int flag = ; if (listT != null)
{
foreach (T t in listT)
{
List<Parameter> listProperty = GetProperties<T>(t); if (flag <= )
{
foreach (Parameter parameter in listProperty)
{
flag++; dt.Columns.Add(GetColumn(parameter.Name, parameter.Object.ToString()));
}
} DataRow dr = dt.NewRow(); foreach (Parameter parameter in listProperty)
{
dr[parameter.Name] = parameter.Value;
} dt.Rows.Add(dr);
}
}
else
{
List<Parameter> listProperty = GetProperties<T>(obj); foreach (Parameter parameter in listProperty)
{
dt.Columns.Add(GetColumn(parameter.Name, parameter.Object.ToString()));
} DataRow dr = dt.NewRow(); foreach (Parameter parameter in listProperty)
{
dr[parameter.Name] = parameter.Value;
} dt.Rows.Add(dr);
} return dt;
} /// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static DataTable TToDataTable<T>(T obj)
{
return TToDataTable<T>(obj, null);
} /// <summary>
/// 类型对象生成DataTable
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="listT"></param>
/// <returns></returns>
public static DataTable TToDataTable<T>(List<T> listT)
{
return TToDataTable<T>(default(T), listT);
} /// <summary>
/// 生成参数
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
/// <returns></returns>
public static Parameter GetParameter(string name, string value)
{
Parameter parameter = new Parameter(); parameter.Name = name;
parameter.Value = value; return parameter;
}

要是客户端为bs架构,用一下代码进行发送

 /// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
public void SendDataObject<T>(T t)
{
string json = Newtonsoft.Json.JsonConvert.SerializeObject(t); SendDataByJson(json);
}

具体的后端向前端发送的代码可以参考如下:

 #region 公共方法
/// <summary>
/// 向客户端发送数据
/// </summary>
/// <param name="contentEncoding">字符编码</param>
/// <param name="contentType">输出流的MIME类型</param>
/// <param name="content">输出的内容</param>
public void SendData(Encoding contentEncoding, string contentType, string content)
{
Response.Clear();
Response.ContentEncoding = contentEncoding;
Response.ContentType = contentType;
Response.Write(content);
Response.Flush();
Response.End();
}
/// <summary>
/// 向客户端发送数据
/// </summary>
/// <param name="content">输出的内容</param>
public void SendData(string content)
{
SendData(Encoding.UTF8, "application/json", content);
} public void SendDataFile(string filePath, string fileName)
{
System.IO.FileStream fs = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read); byte[] b = new Byte[fs.Length];
fs.Read(b, , b.Length);
fs.Flush();
fs.Close(); Response.Clear();
Response.ClearHeaders();
Response.Clear();
Response.ClearHeaders();
Response.Buffer = false;
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
Response.AppendHeader("Content-Length", b.Length.ToString());
fs.Close();
fs.Close();
if (b.Length > )
{
Response.OutputStream.Write(b, , b.Length);
}
Response.Flush();
Response.End();
}
/// <summary>
/// 通过json的形式发送文本
/// </summary>
/// <param name="content">要发送的内容</param>
public void SendDataByJson(string content)
{
SendData(Encoding.UTF8, "application/json", content);
}
/// <summary>
/// 向客户端发送数据
/// </summary>
/// <param name="content">输出的内容</param>
public void SendData(string contentType, string content)
{
SendData(Encoding.UTF8, contentType, content);
}
/// <summary>
/// 通过文本的形式发送文件
/// </summary>
/// <param name="content">要发送的内容</param>
public void SendDataByText(string content)
{
SendData(Encoding.UTF8, "text/plain", content);
}
/// <summary>
/// 处理错误消息
/// </summary>
/// <param name="message">要处理的消息</param>
/// <returns>处理之后的消息</returns>
public string DealErrorMsg(string message)
{
return message.Replace((char), (char)).Replace((char), (char)).Replace("\"", "'").Replace("\0", "");
} #endregion

简单的sql server->bs或cs数据交互模式的更多相关文章

  1. 最简单删除SQL Server中所有数据的方法

     最简单删除SQL Server中所有数据的方法 编写人:CC阿爸 2014-3-14 其实删除数据库中数据的方法并不复杂,为什么我还要多此一举呢,一是我这里介绍的是删除数据库的所有数据,因为数据之间 ...

  2. 恢复SQL Server被误删除的数据(再扩展)

    恢复SQL Server被误删除的数据(再扩展) 大家对本人之前的文章<恢复SQL Server被误删除的数据> 反应非常热烈,但是文章里的存储过程不能实现对备份出来的日志备份里所删数据的 ...

  3. 恢复SQL Server被误删除的数据

    恢复SQL Server被误删除的数据 <恢复SQL Server被误删除的数据(再扩展)> 地址:http://www.cnblogs.com/lyhabc/p/4620764.html ...

  4. 转:Sql Server中清空所有数据表中的记录

    如果要删除数据表中所有数据只要遍历一下数据库再删除就可以了,清除所有数据我们可以使用搜索出所有表名,构造为一条SQL语句进行清除了,这里我一一给各位同学介绍.   使用sql删除数据库中所有表是不难的 ...

  5. Sql Server中清空所有数据表中的记录

    Sql Server中清空所有数据表中的记录 清空所有数据表中的记录: 代码如下:exec sp_msforeachtable  @Command1 ='truncate table ?'删除所有数据 ...

  6. SQL SERVER 和ACCESS的数据导入导出

            //批量导入Access         string filepath = Server.MapPath("student.mdb");         stri ...

  7. .SQL Server中 image类型数据的比较

    原文:.SQL Server中 image类型数据的比较 在SQL Server中如果你对text.ntext或者image数据类型的数据进行比较.将会提示:不能比较或排序 text.ntext 和 ...

  8. [转]实战 SQL Server 2008 数据库误删除数据的恢复

    实战 SQL Server 2008 数据库误删除数据的恢复 关键字:SQL Server 2008, recover deleted records 今天有个朋友很着急地打电话给我,他用delete ...

  9. SQL Server 2008 数据库误删除数据的恢复

    原文:SQL Server 2008 数据库误删除数据的恢复 原文:http://www.cnblogs.com/dudu/archive/2011/10/15/sql_server_recover_ ...

随机推荐

  1. <转>牛顿法与拟牛顿法

    转自:http://blog.csdn.net/itplus/article/details/21896619 机器学习算法中经常碰到非线性优化问题,如 Sparse Filtering 算法,其主要 ...

  2. Spring的Log4J配置器Log4jWebConfigurer介绍

    1. Logj4简介 Log4j是Apache大旗下的一个子项目,它可以用来重定向应用日志文件的输出流,无论我们想将日志文件输出到控制台还是网络还是其他地方,都可以通过logj4来配置,如果我们的应用 ...

  3. Let's Encrypt泛域名SSL证书申请

    操作系统:CentOS 7 github:https://github.com/Neilpang/acme.sh 有中文说明: https://github.com/Neilpang/acme.sh ...

  4. Ubuntu 安装mono

    Ubuntu 安装mono 我的系统:Ubuntu 16   Mono参考: http://www.mono-project.com/docs/getting-started/install/linu ...

  5. 关于BigDecimal.ROUND_HALF_UP与ROUND_HALF_DOWN

    ROUND_HALF_UP: 遇到.5的情况时往上近似,例: 1.5 ->;2ROUND_HALF_DOWN : 遇到.5的情况时往下近似,例: 1.5 ->;1 BigDecimal a ...

  6. iOS - Harpy版本更新工具兼容版本第三方库

    Harpy(兼容版) git地址:https://github.com/yangchao0033/Harpy ###(iOS5-9适配版本,基于ArtSabintsev/Harpy v3.4.5) 提 ...

  7. markdown 基本语法(转载)

    最近感觉一直使用富文本编辑器写东西,感觉有点烦,所以就试着学习了一下简单的markdown编辑器的使用 原文地址:http://www.jianshu.com/p/815788f4b01d markd ...

  8. python GIL :全局解释器

    cpython 解释器中存在一个GIL(全局解释器锁),无论多少个线程.多少颗cpu 他的作用就是保证同一时刻只有一个线程可以执行代码,因此造成了我们使用多线程的时候无法实现并行. 因为有GIL的存在 ...

  9. linux中的cd

    cd命令 实例 hling@hling:~$ cd /home/hling/桌面/huanghling@hling:~/桌面/huang$ cd ..hling@hling:~/桌面$ cd ..hl ...

  10. 基于 ASP.NET Core 2.1 的 Razor Class Library 实现自定义错误页面的公用类库

    注意:文中使用的是 razor pages ,建议使用 razor views ,使用 razor pages 有一个小坑,razor pages 会用到 {page} 路由参数,如果应用中也用到了这 ...