大量数据写入数据库方法:SqlServer优化之批量插入(SqlBulkCopy、表值参数)
#region 获取 本周、本月、本季度、本年 的开始时间或结束时间 /// <summary> /// 获取开始时间 /// </summary> /// <param name="TimeType">Week、Month、Season、Year</param> /// <param name="now"></param> /// <returns>2017-01-01 00:00:00</returns> public static DateTime? GetTimeStartByType(string TimeType, DateTime now) { switch (TimeType) { case "Week": return now.AddDays(-(now.DayOfWeek == 0 ? 7 : (int)now.DayOfWeek) + 1).Date; case "Month": return now.AddDays(-now.Day + 1).Date; case "Season": var time = now.AddMonths(0 - ((now.Month - 1) % 3)); return time.AddDays(-time.Day + 1).Date; case "Year": return now.AddDays(-now.DayOfYear + 1).Date; default: return null; } } /// <summary> /// 获取结束时间 /// </summary> /// <param name="TimeType">Week、Month、Season、Year</param> /// <param name="now"></param> /// <returns>2017-12-31 23:59:59</returns> public static DateTime? GetTimeEndByType(string TimeType, DateTime now) { DateTime dt = new DateTime(); switch (TimeType) { case "Week": dt = now.AddDays(7 - (now.DayOfWeek == 0 ? 7 : (int)now.DayOfWeek)).Date; break; case "Month": dt = now.AddMonths(1).AddDays(-now.AddMonths(1).Day + 1).AddDays(-1).Date; break; case "Season": var time = now.AddMonths((3 - ((now.Month - 1) % 3) - 1)); dt = time.AddMonths(1).AddDays(-time.AddMonths(1).Day + 1).AddDays(-1).Date; break; case "Year": var time2 = now.AddYears(1); dt = time2.AddDays(-time2.DayOfYear).Date; break; default: return null; } return dt.AddDays(1).AddSeconds(-1); } #endregion
//ashx页面下调用多种方法 public void ProcessRequest(HttpContext context) { var dataType = context.Request["DataType"]; var keyid = context.Request["Keyid"]; var cMethod = string.Format("Get{0}", dataType); var tp = typeof(DataFetch); var mi = tp.GetMethod(cMethod); if (mi != null) { mi.Invoke(Activator.CreateInstance(tp), new object[] { context, keyid }); } } /// <summary> /// 获取用户信息 /// </summary> /// <param name="keyid"></param> public void GetUser(HttpContext context, string keyid) { var context = HttpContext.Current; //var param = context.Request["Param"]; context.WriteJson(json); }
/*泛型转换*/ /// <summary> /// 获取视图状态的属性值 /// </summary> /// <typeparam name="T">类型</typeparam> /// <param name="stateName">视图状态名称</param> /// <param name="defauleValue">默认值</param> public T GetState<T>(string stateName, T defauleValue) { T m_Value = defauleValue; if (ViewState[stateName] != null) { m_Value = (T)ViewState[stateName]; } return m_Value; } /// <summary> /// 获取视图状态的属性值 /// </summary> /// <typeparam name="T">类型</typeparam> /// <param name="stateName">视图状态名称</param> public T GetState<T>(string stateName) { return GetState<T>(stateName, default(T)); } private List<T_AberRedSetInfo> listAberRedSet { get { return this.GetState<List<T_AberRedSetInfo>>("T_AberRedSet"); } set { this.SetState("T_AberRedSet", value); } }
强制对所有代进行即时垃圾回收 GC.Collect();
深度拷贝与浅复制
///复制List--当然前题是List中的对象要实现ICloneable接口 public static IList<T> Clone<T>(this IList<T> listToClone) where T: ICloneable { return listToClone.Select(item => (T)item.Clone()).ToList(); }
#region Object拓展,深复制,对象转换 /// <summary> /// 深复制,就是完全复制Clone,代替ICloneable接口 /// </summary> /// <param name="oSource"></param> /// <returns></returns> public static T DeepCopy<T>(this T oSource) { T oClone; DataContractSerializer dcs = new DataContractSerializer(typeof(T)); using (MemoryStream ms = new MemoryStream()) { dcs.WriteObject(ms, oSource); ms.Position = 0; oClone = (T)dcs.ReadObject(ms); } return oClone; } /// <summary> /// 将Object对象转换为目标对象,一般用于匿名对象转换。 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <param name="t"></param> /// <returns></returns> public static T ChangeObjectType<T>(this object obj, T t) { return (T)obj; } #endregion
[Serializable] public class InvoiceDetailResponse : IDeepCopy, IShallowCopy { public Guid merchant_id { get; set; } /// <summary> /// 名称 /// </summary> public string uname { get; set; } /// <summary> /// 浅拷贝 /// </summary> /// <returns></returns> public object ShallowCopy() { return this.MemberwiseClone(); } /// <summary> /// 深拷贝 【不建议使用二进制流方法,此方法即使在类前面加了可序列化标志,调用该方法时也会报未序列化错误】,推荐使用反射方式 /// </summary> /// <returns></returns> public object DeepCopy() { using (MemoryStream stream = new MemoryStream()) { BinaryFormatter bFormatter = new BinaryFormatter(); bFormatter.Serialize(stream, this); stream.Seek(0, SeekOrigin.Begin); return (InvoiceDetailResponse)bFormatter.Deserialize(stream); } } } /// <summary> /// 深拷贝接口 /// </summary> interface IDeepCopy { object DeepCopy(); } /// <summary> /// 浅拷贝接口 /// </summary> interface IShallowCopy { object ShallowCopy(); }
///利用反射实现 public static T DeepCopyByReflection<T>(T obj) { if (obj is string || obj.GetType().IsValueType) return obj; object retval = Activator.CreateInstance(obj.GetType()); FieldInfo[] fields = obj.GetType().GetFields(BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Static|BindingFlags.Instance); foreach(var field in fields) { try { field.SetValue(retval, DeepCopyByReflection(field.GetValue(obj))); } catch { } } return (T)retval; }
public static T Clone<T>(T RealObject) { using (Stream objectStream = new MemoryStream()) { //利用 System.Runtime.Serialization序列化与反序列化完成引用对象的复制 IFormatter formatter = new BinaryFormatter(); formatter.Serialize(objectStream, RealObject); objectStream.Seek(0, SeekOrigin.Begin); return (T)formatter.Deserialize(objectStream); } }
#region Object拓展,深复制,对象转换 /// <summary> /// 深复制,就是完全复制Clone,代替ICloneable接口 /// </summary> /// <param name="oSource"></param> /// <returns></returns> public static T DeepCopy<T>(this T oSource) { T oClone; DataContractSerializer dcs = new DataContractSerializer(typeof(T)); using (MemoryStream ms = new MemoryStream()) { dcs.WriteObject(ms, oSource); ms.Position = 0; oClone = (T)dcs.ReadObject(ms); } return oClone; } /// <summary> ///将Object对象转换为目标对象,一般用于匿名对象转换。 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <param name="t"></param> /// <returns></returns> public static T ChangeObjectType<T>(this object obj, T t) { return (T)obj; } #endregion
Cpu、内存和IO监控
#region 监控服务器状况 if (intSecond == 0) //while (true) { //Thread.Sleep(1000); var obj = new ManagementObjectSearcher("select * from Win32_PhysicalMemory"); ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_PerfFormattedData_PerfOS_Processor"); var cpuTimes = searcher.Get().Cast<ManagementObject>().Select(mo => new { Name = mo["Name"], Usage = mo["PercentProcessorTime"] }).ToList(); var query = cpuTimes.Where(x => x.Name.ToString() == "_Total").Select(x => x.Usage); Log.LogNoteInfo(string.Format("{0}:cpu使用率:{1}%,内存使用率:{2}%", DateTime.Now.ToString(), query.SingleOrDefault().ToString(), GetNCZYL())); } #endregion 监控服务器状况 public string GetNCZYL() { double zyl = (GetNC() - GetKYNC()) / GetNC() * 100; return Math.Round(zyl, 2).ToString(); } public double GetKYNC() { double totalCapacity = 0; ObjectQuery objectQuery = new ObjectQuery("select * from Win32_PerfRawData_PerfOS_Memory"); ManagementObjectSearcher searcher = new ManagementObjectSearcher(objectQuery); ManagementObjectCollection vals = searcher.Get(); foreach (ManagementObject val in vals) { totalCapacity += System.Convert.ToDouble(val.GetPropertyValue("Availablebytes")); } double ramCapacity = totalCapacity / 1048576; return ramCapacity; } public double GetNC() { double totalCapacity = 0; ObjectQuery objectQuery = new ObjectQuery("select * from Win32_PhysicalMemory"); ManagementObjectSearcher searcher = new ManagementObjectSearcher(objectQuery); ManagementObjectCollection vals = searcher.Get(); foreach (ManagementObject val in vals) { totalCapacity += System.Convert.ToDouble(val.GetPropertyValue("Capacity")); } double ramCapacity = totalCapacity / 1048576; return ramCapacity; }
#region 监控进程状况 var processName = Process.GetCurrentProcess().ProcessName; try { // 创建对 CPU 占用百分比的性能计数器。 //var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total"); // 创建内存占用字节数的性能计数器 //var ramCounter = new PerformanceCounter("Memory", "Available MBytes"); var cpuCounter = new PerformanceCounter("Process", "% Processor Time", processName); var ramCounter = new PerformanceCounter("Process", "Working Set", processName); float cpu = cpuCounter.NextValue(); float ram = ramCounter.NextValue(); strLog = string.Format("处理结束Cpu:{0},Ram:{1}", cpu, ram); AddLogsInfo1(strLog, 0); LogHelper.WriteLog(strLog); } catch (Exception ex) { strLog = "【Error】处理结束CpuCpu+Ram" + ex.Message; LogHelper.WriteLog(strLog); } try { string categoryName = "Process"; PerformanceCounter ioReadcounter = new PerformanceCounter(categoryName, "IO Read Bytes/sec", processName); PerformanceCounter ioWritecounter = new PerformanceCounter(categoryName, "IO Write Bytes/sec", processName); strLog = string.Format("处理结束IO Read:{0},IO Write:{1}", ioReadcounter.NextValue(), ioWritecounter.NextValue()); LogHelper.WriteLog(strLog); } catch (Exception ex) { strLog = "【Error】处理结束IO" + ex.Message; LogHelper.WriteLog(strLog); } #endregion 监控进程状况