1.客戶端代碼 public static void FileMoveInVirtualMachineForCompressor() { var obj = new object(); string ip = "127.0.0.1"; int port = 11000; List<string> files = Directory.GetFiles(@"C:\Users\admin\Desktop\sendFile").ToList(); Dictionary<string, byte[]> infoList = new Dictionary<string, byte[]>(); foreach (var file in files) { byte[] buffer = File.ReadAllBytes(file); infoList.Add(Path.GetFileName(file), buffer); } byte[] bs = Holworth.Utility.HraUtility.CompressionObject(infoList); string toPath = @"C:\Users\admin\Desktop\sendFile"; string toFile = Path.Combine(toPath, DateTime.Now.ToString("yyyyMMdd")+ ".shape"); //將數組寫入文件 Stream writer = new FileStream(toFile, FileMode.Create, FileAccess.Write, FileShare.Write); writer.Write(bs, 0, bs.Length); writer.Flush(); writer.Close(); Net.SendFile(ip, port, toFile, 512, 900000); } 2.服務端監聽 using SocketIM; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace FileListener { class Program { static void Main(string[] args) { string ip = "127.0.0.1"; int port = 11000; Net.ListenerAcceptFile(ip, port, @"d:\ReciveFoder"); MessageBox.Show("監聽程序已啟動!!"); Console.ReadKey(); } } } 3.Net.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; namespace SocketIM { ////// Net : 提供靜態方法,對常用的網絡操作進行封裝 public class Net { public class ObjectState { public string fileName { get; set; } public Socket workSocket { get; set; } public Thread workThread { get; set; } } private Net() { } ////// 向遠程主機發送數據 //////要發送數據且已經連接到遠程主機的 Socket///待發送的數據///發送數據的超時時間,以秒為單位,可以精確到微秒///0:發送數據成功;-1:超時;-2:發送數據出現錯誤;-3:發送數據時出現異常////// 當 outTime 指定為-1時,將一直等待直到有數據需要發送 public static int SendData(Socket socket, byte[] buffer, int outTime) { if (socket == null || socket.Connected == false) { throw new ArgumentException("參數socket 為null,或者未連接到遠程計算機"); } if (buffer == null || buffer.Length == 0) { throw new ArgumentException("參數buffer 為null ,或者長度為 0"); } int flag = 0; try { int totalLen = buffer.Length; int sndLen = 0; while (true) { if ((socket.Poll(outTime * 100, SelectMode.SelectWrite) == true)) { // 收集了足夠多的傳出數據后開始發送 sndLen = socket.Send(buffer, sndLen, totalLen, SocketFlags.None); totalLen -= sndLen; if (totalLen == 0) { // 數據已經全部發送 flag = 0; break; } else { if (sndLen > 0) { // 數據部分已經被發送continue; } else { // 發送數據發生錯誤 flag = -2; break; } } } else { // 超時退出 flag = -1; break; } } } catch (SocketException e) { flag = -3; } return flag; } ////// 向遠程主機發送文件 //////要發送數據且已經連接到遠程主機的 socket///待發送的文件名稱///文件發送時的緩沖區大小///發送緩沖區中的數據的超時時間///0:發送文件成功;-1:超時;-2:發送文件出現錯誤;-3:發送文件出現異常;-4:讀取待發送文件發生錯誤////// 當 outTime 指定為-1時,將一直等待直到有數據需要發送 public static int SendFile(string ip, int port, string fileName, int maxBufferLength, int outTime) { IPAddress address = IPAddress.Parse(ip); IPEndPoint endpoint = new IPEndPoint(address, port); //創建服務端負責監聽的套接字,參數(使用IPV4協議,使用流式連接,使用TCO協議傳輸數據) Thread.Sleep(1500); Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Connect(endpoint); if (socket.Connected) { Console.WriteLine(socket.RemoteEndPoint + "連接成功"); } if (fileName == null || maxBufferLength <= 0) { throw new ArgumentException("待發送的文件名稱為空或發送緩沖區的大小設置不正確."); } int flag = 0; try { var fileBytes = Encoding.UTF8.GetBytes(fileName); var fbs = new byte[100]; for (int i = 0; i < fileBytes.Length; i++) { fbs[i] = fileBytes[i]; } socket.Send(fbs); FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); long fileLen = fs.Length; // 文件長度 long totalLen = fileLen; // 未讀取部分 int readLen = 0; // 已讀取部分 byte[] buffer = null; if (fileLen <= maxBufferLength) { /* 文件可以一次讀取*/ buffer = new byte[fileLen]; readLen = fs.Read(buffer, 0, (int)fileLen); flag = SendData(socket, buffer, outTime); } else { /* 循環讀取文件,並發送 */ while (totalLen != 0) { if (totalLen < maxBufferLength) { buffer = new byte[totalLen]; readLen = fs.Read(buffer, 0, Convert.ToInt32(totalLen)); } else { buffer = new byte[maxBufferLength]; readLen = fs.Read(buffer, 0, maxBufferLength); } if ((flag = SendData(socket, buffer, outTime)) < 0) { break; } totalLen -= readLen; } } fs.Flush(); fs.Close(); File.Delete(fileName); socket.Shutdown(SocketShutdown.Both); socket.Close(); } catch (IOException e) { flag = -4; } if (flag == 0) { Console.WriteLine(fileName + "文件發送成功"); socket.Close(); Console.WriteLine("連接關閉"); } else { Console.WriteLine(fileName + "文件發送失敗,i=" + flag); } return flag; } private static void WatchConnecting(object info) { ObjectState state = (ObjectState)info; Socket socketWatch = state.workSocket; while (true)//持續不斷的監聽客戶端的請求 { //開始監聽 客戶端連接請求,注意:Accept方法,會阻斷當前的線程 Socket connection = socketWatch.Accept(); if (connection.Connected) { //創建通信線程 Thread thradRecMsg = new Thread(RecMsg); state.workSocket = connection; state.workThread = thradRecMsg; thradRecMsg.IsBackground = true; thradRecMsg.Start(state); } } } ////// 接收消息 private static void RecMsg(object socketClientPara) { string ext = string.Empty; string fileSourcePath = string.Empty; ObjectState state = (ObjectState)socketClientPara; string fileName = state.fileName;//獲得用戶保存文件的路徑 Socket socketClient = state.workSocket; FileStream fs = null; while (true) { //定義一個接受用的緩存區(100M字節數組) //將接收到的數據存入arrMsgRec數組,並返回真正接受到的數據的長度 if (socketClient.Connected) { try { byte[] fileBuffer = new byte[100]; int size1= socketClient.Receive(fileBuffer); fileSourcePath = Encoding.UTF8.GetString(fileBuffer).Trim(); var chs = fileSourcePath.ToCharArray(); var chList = new List<char>(); foreach (var item in chs) { if (item != '\0') { chList.Add(item); } } fileSourcePath = string.Join("", chList); fileName = Path.Combine(state.fileName, Path.GetFileName(fileSourcePath)); ext = Path.GetExtension(fileName); //因為終端每次發送文件的最大緩沖區是512字節,所以每次接收也是定義為512字節 byte[] buffer = new byte[512]; int size = 0; //統計實際文件大小 long len = 0; //創建文件流,然后讓文件流來根據路徑創建一個文件 fs = new FileStream(fileName, FileMode.Append); DateTime oTimeBegin = DateTime.Now; //從終端不停的接受數據,然后寫入文件里面,只到接受到的數據為0為止,則中斷連接 while ((size = socketClient.Receive(buffer, 0, buffer.Length, SocketFlags.None)) > 0) { fs.Write(buffer, 0, size); len += size; } DateTime oTimeEnd = DateTime.Now; TimeSpan oTime = oTimeEnd.Subtract(oTimeBegin); fs.Flush(); fs.Dispose(); //解壓文件.DEFP; var obj=(Dictionary<string,byte[]>) Holworth.Utility.HraUtility.DeSerializerFileToObj(fileName); foreach (var item in obj) { string path = Path.Combine(state.fileName, item.Key); FileStream fw= new FileStream(path, FileMode.Append); fw.Write(item.Value, 0, item.Value.Length); fw.Flush(); fw.Dispose(); } File.Delete(fileName); Console.WriteLine("文件保存成功:" + fileName); Console.WriteLine("接收文件用時:" + oTime.ToString() + ",文件大小:" + len / 1024 + "kb"); } catch (Exception ex) { if (fs != null) { fs.Dispose(); } Console.WriteLine(socketClient.RemoteEndPoint + "下線了"); break; } finally { socketClient.Shutdown(SocketShutdown.Both); socketClient.Close(); } } else { } } } /// <summary> /// 監聽並接收文件 /// </summary> /// <param name="ip"></param> /// <param name="port"></param> /// <param name="fileName"></param> public static void ListenerAcceptFile(string ip, int port, string fileName) { //創建服務端負責監聽的套接字,參數(使用IPV4協議,使用流式連接,使用Tcp協議傳輸數據) Socket socketListen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socketListen.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); //獲取Ip地址對象 IPAddress address = IPAddress.Parse(ip); //創建包含Ip和port的網絡節點對象 IPEndPoint endpoint = new IPEndPoint(address, port); //將負責監聽的套接字綁定到唯一的Ip和端口上 socketListen.Bind(endpoint); //設置監聽隊列的長度 socketListen.Listen(10); connectDone.Set(); ObjectState state = new ObjectState(); //創建負責監聽的線程,並傳入監聽方法 Thread threadWatch = new Thread(WatchConnecting); state.fileName = fileName; state.workSocket = socketListen; state.workThread = threadWatch; threadWatch.IsBackground = true;//設置為后台線程 threadWatch.Start(state);//開始線程 } public static void CloseTcpSocket(Thread threadWatch, Socket socketWatch) { threadWatch.Abort(); socketWatch.Close(); Console.WriteLine("服務器關閉監聽"); } public static ManualResetEvent connectDone = new ManualResetEvent(false); public static void FileMove(string ip, int port, string fromPath, string toPath) { int i = SendFile(ip, port, fromPath, 512, 90000); Console.WriteLine("文件從" + fromPath + "到" + toPath + "移動成功!!!!"); } } } 3.Utility工具類,慢看吧,里面有這次的壓縮代碼 using System; using System.Collections.Generic; using System.Linq; using System.Text; using a = Utility; using System.Net; using System.IO; using System.Data; using System.Data.OleDb; using ut = Utility; using System.Collections; using System.Text.RegularExpressions; using System.Runtime.Serialization.Formatters.Binary; using System.IO.Compression; using Framework; using Oracle.DataAccess.Client; using System.Runtime.Remoting.Messaging; using Contract.Domain; using System.Reflection; using System.Collections.Concurrent; using Framework.Domain; namespace Holworth.Utility { public class DataBaseInfo { public string datasource { get; set; } public string user { get; set; } public string datasource2 { get; set; } public string password { get; set; } public string database { get; set; } public string port { get; set; } public string dbSwitch { get; set; } } public class HraUtility { public enum AppEnum { //web應用的配置文件 Web=0, //非web應用的配置文件 App=1, } private static object lockDataBaseInfo = new object(); private static DataBaseInfo _dbWebInfo = null; private static DataBaseInfo _dbAppInfo = null; public static DataBaseInfo GetDataBaseInfo(AppEnum app) { DataBaseInfo info = null; if (app == AppEnum.Web) { info = _dbWebInfo; } else if (app ==AppEnum.App) { info = _dbAppInfo; } if (info == null) { lock (lockDataBaseInfo) { if (info == null) { if (app == AppEnum.Web) { info = _dbWebInfo=new DataBaseInfo(); } else if (app == AppEnum.App) { info = _dbAppInfo=new DataBaseInfo(); } System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument(); xmlDoc.Load(AppDomain.CurrentDomain.BaseDirectory +app.ToString()+".config"); System.Xml.XmlNodeList nodes = xmlDoc.SelectNodes("/configuration/databaseSettings/add"); var ps = info.GetType().GetProperties().ToList().ToDictionary(x => x.Name); foreach (System.Xml.XmlNode node in nodes) { string key = node.Attributes["key"].InnerText; string value = node.Attributes["value"].Value; string realKey = key.Split('.')[key.Split('.').Length - 1];//我實際的標記是db.key如db.database ,db.user,db.password if (realKey == "user") { value = value.ToUpper(); } ps[realKey].SetValue(info, value); } } } } return info; } /// <summary> /// xml Sql操作接口 /// </summary> public static EntityRowMapper EntityRowMapper = new EntityRowMapper(); public static CSVHelper csvHelper = new CSVHelper(); public static IList<T> ListToT<T>(System.Collections.IList list) { System.Collections.Generic.IList<T> returnList = new System.Collections.Generic.List<T>(); foreach (T a in list) { returnList.Add(a); } return returnList; } public static void DownLoad(string url, string fileName) { bool flag = false; //打開上次下載的文件 long SPosition = 0; //實例化流對象 FileStream FStream; string strFileName = fileName; //判斷要下載的文件夾是否存在 if (File.Exists(strFileName)) { File.Delete(strFileName); ////打開要下載的文件 //FStream = File.OpenWrite(strFileName); ////獲取已經下載的長度 //SPosition = FStream.Length; //FStream.Seek(SPosition, SeekOrigin.Current); } FStream = new FileStream(strFileName, FileMode.Create); SPosition = 0; HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(url); if (SPosition > 0) myRequest.AddRange((int)SPosition); //設置Range值 Stream myStream = myRequest.GetResponse().GetResponseStream(); //定義一個字節數據 byte[] btContent = new byte[512]; int intSize = 0; intSize = myStream.Read(btContent, 0, 512); while (intSize > 0) { FStream.Write(btContent, 0, intSize); intSize = myStream.Read(btContent, 0, 512); } //關閉流 FStream.Close(); myStream.Close(); } public static decimal ChangeCross(string from, string to, int twice) { string url = a.ConfigManager.GetConfig("CrossUrl"); url += string.Format("?s={0}=X&f=l1", from.ToUpper(), to.ToUpper()); System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url); //從URL地址得到一個WEB請求 System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse(); //從WEB請求得到 if (myrp.StatusCode == HttpStatusCode.OK) { long totalBytes = myrp.ContentLength; //從WEB響應得到總字節數 System.IO.Stream st = myrp.GetResponseStream(); //從WEB請求創建流(讀 StreamReader responseReader = new StreamReader(st); string s = responseReader.ReadToEnd(); if (!string.IsNullOrEmpty(s)) { return decimal.Parse(s); } else { throw new Exception("無法獲取相應匯率"); } } return 0; } /// <summary> /// 獲取Excel 數據 /// </summary> /// <param name="strPath"></param> /// <param name="sheetName"></param> /// <returns></returns> public static DataTable GetExcelSheetContent(string strPath, string sheetName) { string mystring = ""; DataTable dt = new DataTable(); mystring = "Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = '" + strPath + "';Extended Properties='Excel 8.0;HDR=NO;IMEX=1;'"; if (System.IO.Path.GetExtension(strPath).ToLower().EndsWith("xlsx")) { mystring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strPath + ";Extended Properties='Excel 12.0;HDR=YES'"; } OleDbConnection connection = new OleDbConnection(mystring); OleDbDataAdapter da = null; try { da = new OleDbDataAdapter("select * from [" + sheetName + "]", connection); da.Fill(dt); return dt; } catch (OleDbException err) { throw new Exception("執行查詢語句時出錯:" + err.Message); } finally { connection.Close(); da.Dispose(); } } /// <summary> /// 獲取Excel 表格名 /// </summary> /// <param name="strPath"></param> /// <returns></returns> public static string[] GetExcelTableName(string strPath) { string mystring = ""; mystring = "Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = '" + strPath + "';Extended Properties='Excel 8.0;HDR=YES;IMEX=1;'"; if (System.IO.Path.GetExtension(strPath).ToLower().EndsWith("xlsx")) { mystring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strPath + ";Extended Properties='Excel 12.0;HDR=YES'"; } //IList<string> tblNames = null; DataTable tblSchema = null; string tableName = ""; OleDbConnection connection = new OleDbConnection(mystring); try { if (connection.State != ConnectionState.Open) connection.Open(); //Prepare the command tblSchema = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); string[] mySheetName = new string[tblSchema.Rows.Count]; int i = 0; foreach (DataRow row in tblSchema.Rows) { tableName = row["TABLE_NAME"].ToString(); mySheetName[i] = tableName; i++; } return mySheetName; } catch (OleDbException err) { if (err.ErrorCode == -2147467259) throw new Exception("您選擇的Excel文件不是預期的格式!"); else throw new Exception("執行查詢語句時出錯:" + err.Message); } finally { connection.Close(); } } /// <summary> /// 將“abc_d_ef”類型的字符串轉換成首字母大寫的"AbcDEf" /// </summary> /// <param name="name"></param> /// <returns></returns> public static string NameFormatter(string name) { string[] s = name.Split('_'); for (int i = 0; i < s.Count(); i++) { s[i] = s[i].Substring(0, 1).ToUpper() + s[i].Substring(1).ToLower(); } name = string.Concat(s); return name; } /// <summary> /// 將AbcDef轉成ABC_DEF /// </summary> /// <param name="name"></param> /// <returns></returns> public static string NameConverter(string name) { List<char> c = name.ToList(); int count = c.Count; for (int i = 1; i < count; i++) { if (c[i] >= 'A' && c[i] <= 'Z') { c.Insert(i, '_'); i++; } } string result = string.Concat(c); return result; } /// <summary> /// 全角轉半角 /// </summary> /// <param name="input"></param> /// <returns></returns> public static string ToDBC(String input) { char[] c = input.ToCharArray(); for (int i = 0; i < c.Length; i++) { if (c[i] == 12288) { c[i] = (char)32; continue; } if (c[i] > 65280 && c[i] < 65375) c[i] = (char)(c[i] - 65248); } return new string(c); } private static Framework.IService.ICommonService GetDao() { Spring.Context.IApplicationContext ctx = Spring.Context.Support.ContextRegistry.GetContext(); return (Framework.IService.ICommonService)ctx["CommonService"]; } public static string ConvertToEntityColumnName(string name) { List<string> strList = name.Split('_').ToList(); StringBuilder sb = new StringBuilder(); foreach (string s2 in strList) { sb.Append(ReplaceString(s2)); } return sb.ToString(); } public static string ReplaceString(string s) { return Regex.Replace(s, (string)@"([A-Za-z]{1})([A-Za-z]*)", (MatchEvaluator)MatchEval); } public static string ConvertToTableColumnName(string name) { name = Regex.Replace(name, @"([A-Z]{1})([a-z]*)", MatchEval2); name = name.TrimEnd('_'); return name; } private static string MatchEval2(Match match) { return match.Groups[1].Value.ToUpper() + match.Groups[2].Value.ToUpper() + "_"; } private static string MatchEval(Match match) { return match.Groups[1].Value.ToUpper() + match.Groups[2].Value.ToLower(); } public static Dictionary<string, string> ChangeType(string NodeSource, string DataValueField, string DataTextField, object cellValue) { var Dao = GetDao(); Framework.QueryInfo NodeSourceInfo = new Framework.QueryInfo(); NodeSourceInfo.CustomSQL = "select " + DataValueField + "," + DataTextField + " from " + NodeSource; Dictionary<string, string> NodeSourceDictionary = new Dictionary<string, string>(); IList NodeSourceList = Dao.FindList(NodeSourceInfo); foreach (dynamic item in NodeSourceList) { object[] objs = item as object[]; NodeSourceDictionary.Add(objs[0].ToString(), objs[1].ToString()); } return NodeSourceDictionary; } public static byte[] CompressionObject(object DataOriginal) { if (DataOriginal == null) return null; BinaryFormatter bFormatter = new BinaryFormatter(); MemoryStream mStream = new MemoryStream(); bFormatter.Serialize(mStream, DataOriginal); byte[] bytes = mStream.ToArray(); MemoryStream oStream = new MemoryStream(); DeflateStream zipStream = new DeflateStream(oStream, CompressionMode.Compress); zipStream.Write(bytes, 0, bytes.Length); zipStream.Flush(); zipStream.Close(); return oStream.ToArray(); } public static object DecompressionObject(byte[] bytes) { if (bytes == null) return null; MemoryStream mStream = new MemoryStream(bytes); mStream.Seek(0, SeekOrigin.Begin); DeflateStream unZipStream = new DeflateStream(mStream, CompressionMode.Decompress, true); object dsResult = null; BinaryFormatter bFormatter = new BinaryFormatter(); dsResult = (object)bFormatter.Deserialize(unZipStream); return dsResult; } /// <summary> /// 序列化對象,將對象寫入文件,然后還原. /// </summary> public static void SerializerObjToFile(string serializerFileName, object obj) { byte[] bs = CompressionObject(obj); string path = HraUtility.EntityRowMapper.GetFilePath("admin/InitDataBase/Sql/SerializerFile/" + serializerFileName + ".shape"); //將數組寫入文件 Stream writer = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Write); writer.Write(bs, 0, bs.Length); writer.Flush(); writer.Close(); } public static object DeSerializerFileToObj(string relativePath) { //"admin/InitDataBase/Sql/SerializerFile/" + serializerFileName + ".shape" string path = relativePath;// HraUtility.EntityRowMapper.GetFilePath(relativePath); //讀取文件,先寫入數組,再從數組轉換為對象.Easy! FileStream fs = File.Open(path, FileMode.OpenOrCreate,FileAccess.ReadWrite); byte[] bss = new byte[fs.Length]; int i = fs.Read(bss, 0, (int)fs.Length); fs.Dispose(); object o = DecompressionObject(bss); //還原,ok return o; } public static object lockListObj = new object(); public static object lockSequence = new object(); public static object lockGetSequence = new object(); public static object lockDeleteSequence = new object(); public static object lockReBuildSequence = new object(); /// <summary> /// BulkCopy /// </summary> /// <param name="dt"></param> /// <param name="targetTable"></param> /// <param name="IdField"></param> /// <param name="NeedId"></param> public static void DataTableWriteToServer(DataTable dt, string targetTable, string IdField = "ID", bool NeedId = false,string v_seq= "BULKCOPYSEQUENCE") { var Dao = GetDao(); QueryInfo info = new QueryInfo(); DataTable table = null; Int64 increId = 0; lock (lockSequence) { if (NeedId) { #region 1.獲取當前序列之 QueryInfo searchInfo = new QueryInfo(); searchInfo.CustomSQL = $"select {v_seq}.NEXTVAL from dual"; table = Dao.ExecuteDataSet(searchInfo).Tables[0]; increId = Convert.ToInt64(table.Rows[0][0].ToString()); #endregion #region 2.改變步長 info.NamedQuery = "PRO_SEQUENCE"; info.Parameters.Add("v_simulation_number", dt.Rows.Count-1); info.Parameters.Add("v_seq", v_seq); Dao.ExecuteNonQuery(info); #endregion #region 3.改變序列的新值 searchInfo = new QueryInfo(); searchInfo.CustomSQL = $"select {v_seq}.NEXTVAL from dual"; table = Dao.ExecuteDataSet(searchInfo).Tables[0]; #endregion #region 4.步長改為1 info = new QueryInfo(); info.NamedQuery = "PRO_SEQUENCE"; info.Parameters.Add("v_simulation_number", -1); info.Parameters.Add("v_seq", v_seq); Dao.ExecuteNonQuery(info); #endregion increId = Convert.ToInt64(table.Rows[0][0].ToString()); foreach (DataRow t in dt.Rows) { t[IdField] = increId++; } } //System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; OracleConnection conn =(OracleConnection) Dao.GetSession().Connection; //new OracleConnection(connOrcleString); OracleBulkCopy bulkCopy = new OracleBulkCopy(conn, OracleBulkCopyOptions.UseInternalTransaction); bulkCopy.BulkCopyTimeout = 260 * 1000; bulkCopy.DestinationTableName = targetTable; //服務器上目標表的名稱 bulkCopy.BatchSize = 5000; //每一批次中的行數 try { IDataReader rd = new DataTableReader(dt); //conn.Open(); if (dt != null && dt.Rows.Count != 0) bulkCopy.WriteToServer(rd); //將提供的數據源中的所有行復制到目標表中 } catch (Exception ex) { throw ex; } finally { info = new QueryInfo(); info.NamedQuery = "PRO_SEQUENCE"; info.Parameters.Add("v_simulation_number", -1); info.Parameters.Add("v_seq", v_seq); Dao.ExecuteNonQuery(info); conn.Close(); if (bulkCopy != null) bulkCopy.Close(); } } } /// <summary> /// 獲取Hibernate對象映射的序列 /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public static string GetSequenceName<T>() where T : Framework.Domain.Entity, new() { var ctx = Spring.Context.Support.ContextRegistry.GetContext(); var mapping = ((Spring.Data.NHibernate.LocalSessionFactoryObject)ctx.GetObject("&SessionFactory")).Configuration.GetClassMapping(typeof(T)); if (((((NHibernate.Mapping.SimpleValue)mapping.Table.IdentifierValue)).IdentifierGeneratorStrategy) != "native") { return "HIBERNATE_SEQUENCE"; } var sequece = ((NHibernate.Mapping.SimpleValue)mapping.Table.IdentifierValue).IdentifierGeneratorProperties["sequence"].ToUpper(); return sequece; } /// <summary> /// List<T>最終使用Bulkcopy的方式實現數據的高效插入,如果可以提供MapDataRow請盡量提供,盡量避免反射帶來的效率問題,雖然內部已經使用了高效反射,但任不及直接賦值 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="DataList"></param> /// <param name="MapDataRow">將對象T轉換為DataRow</param> public static void DataListWriteToServer<T>(IEnumerable<T> DataList) where T : Framework.Domain.Entity,new() { ConcurrentDictionary<DataRow, Framework.Domain.Entity> dr2obj = new ConcurrentDictionary<DataRow, Framework.Domain.Entity>(); if (DataList.Count() <= 0) { return; } bool IsMapDataRow = DataList.FirstOrDefault() is IMapRow<T>; string typeName = typeof(T).FullName; var ctx = Spring.Context.Support.ContextRegistry.GetContext(); var mapping = ((Spring.Data.NHibernate.LocalSessionFactoryObject)ctx.GetObject("&SessionFactory")).Configuration.GetClassMapping(typeof(T)); var tableName = mapping.Table.Name; DataTable targetTable = GetDao().ExecuteDataSet(new QueryInfo() { CustomSQL = $"select * from {tableName} where 1!=1" }).Tables[0]; Hashtable columnsType = new Hashtable(); foreach (DataColumn col in targetTable.Columns) { columnsType.Add(col.ColumnName, col.DataType.Name); } var pmap = mapping.PropertyIterator; //查找主鍵 string primaryKey = ((NHibernate.Mapping.Column)(mapping.Key.ColumnIterator.FirstOrDefault())).Name; //映射列和字段信息的PropertyColumnMappingInfo的集合 Hashtable pcMappinght = new Hashtable(); lock (lockListObj) { foreach (NHibernate.Mapping.Property item in pmap) { //面相對象里Bag在數據中不體現 //if (item.ColumnIterator.GetType().Name == "ISelectable[]") //{ // continue; //} NHibernate.Mapping.Column c = (NHibernate.Mapping.Column)item.ColumnIterator.FirstOrDefault(); ////等下再改 Type columnType = null; //1對多的屬性如children沒有對應的列 if (c != null) { string columnTypeName = columnsType[c.Name].ToString(); switch (columnTypeName) { case "String": columnType = typeof(string); break; case "Int16": case "Int32": case "Int64": columnType = typeof(int); break; case "Decimal": columnType = typeof(decimal); break; case "DateTime": columnType = typeof(DateTime); break; case "Boolean": case "bool": columnType = typeof(bool); break; default: break; } //targetTable.Columns.Add(c.Name, columnType); if (!pcMappinght.ContainsKey(c.Name + "," + item.Name)) { PropertyColumnMappingInfo map = new PropertyColumnMappingInfo(); map.ColumnName = c.Name; map.PropertyName = item.Name; map.ColumnType = columnType; var key = c.Name + "," + item.Name; pcMappinght.Add(key, map); } } } IMapRow<T> mapRow = null; foreach (var item in DataList) { DataRow dtRow = targetTable.NewRow(); if (IsMapDataRow) { mapRow = (IMapRow<T>)item; dtRow = mapRow.MapDataRow(dtRow); } else { foreach (NHibernate.Mapping.Property p in pmap) { object curValue = item.FastGetValue<T>(typeName, p.Name); if (p.IsEntityRelation == true) { if (curValue != null) curValue = ((Framework.Domain.Entity)curValue).Id; } //面相對象里Bag在數據中不體現 if (p.ColumnIterator.GetType().Name == "ISelectable[]") { continue; } NHibernate.Mapping.Column c = (NHibernate.Mapping.Column)p.ColumnIterator.FirstOrDefault(); var key = c.Name + "," + p.Name; var map = (PropertyColumnMappingInfo)pcMappinght[key]; if (curValue == null && c.IsNullable == false) { if (map.ColumnType == typeof(int) || map.ColumnType == typeof(Int16) || map.ColumnType == typeof(long)) { curValue = default(int); } if (map.ColumnType == typeof(DateTime)) { curValue = default(DateTime).Date; } if (map.ColumnType == typeof(decimal)) { curValue = default(decimal); } if (map.ColumnType == typeof(string)) { curValue = default(string); } if (map.ColumnType == typeof(bool)) { curValue = default(bool); } } if (curValue != null) { dtRow[c.Name] = Convert.ChangeType(curValue, map.ColumnType); } else { dtRow[c.Name] = DBNull.Value; } } } targetTable.Rows.Add(dtRow); dr2obj.TryAdd(dtRow, item); } if (((((NHibernate.Mapping.SimpleValue)mapping.Table.IdentifierValue)).IdentifierGeneratorStrategy)!="native") { var sequece = ((NHibernate.Mapping.SimpleValue)mapping.Table.IdentifierValue).IdentifierGeneratorProperties["sequence"].ToUpper(); //bulkcopy DataTableWriteToServer(targetTable, tableName.ToUpper(), primaryKey, true,sequece); } else { DataTableWriteToServer(targetTable, tableName.ToUpper(), primaryKey, true, "HIBERNATE_SEQUENCE"); } foreach (DataRow dr in targetTable.Rows) { dr2obj[dr].Id = dr[primaryKey].ToString(); } } } public static void InitColumns(Array arr, ref Dictionary<string, DataColumn> dicCols, ref DataTable table) { for (int i = 0; i < arr.Length; i++) { if ((arr as dynamic)[i] is Array) { InitColumns((arr as dynamic)[i], ref dicCols, ref table); } else { if (arr.Length >= dicCols.Keys.Count) { dicCols.Clear(); for (int ii = 0; ii < arr.Length; ii++) { string colName = Guid.NewGuid().ToString(); DataColumn col = new DataColumn(colName); if (!dicCols.ContainsKey(colName)) { dicCols.Add(colName, col); } } } } } } public static DataTable ArrayConvert2DataTable(Array arr) { DataTable tmpT = new DataTable(); Dictionary<string, DataColumn> dicCols = new Dictionary<string, DataColumn>(); Dictionary<string, DataRow> dicRows = new Dictionary<string, DataRow>(); //J=交 C=錯 bool isJC = !(arr.GetType().Name.Contains(',')); //交錯數組處理 if (isJC) { //交錯數組第一個維度的元素個 DataTable table = new DataTable(); List<int> dims = new List<int>(); InitColumns(arr, ref dicCols, ref table); foreach (var item in dicCols) { table.Columns.Add(item.Value); } int currRowIndex = 0; SearchTable(ref currRowIndex, arr, arr, ref table); return table; } //多維數組處理 else { int rank = arr.Rank; int cols = arr.GetLength(rank - 1); for (int i = 0; i < cols; i++) { DataColumn col = new DataColumn(Guid.NewGuid().ToString()); tmpT.Columns.Add(col); } Dictionary<int, int> dims = new Dictionary<int, int>(); int currRowIndex = -1; Dictionary<int, DataRow> dicRow = new Dictionary<int, DataRow>(); var iterator = arr.GetEnumerator(); int count = 0; while (iterator.MoveNext()) { var curr = iterator.Current; if (count % cols == 0) { currRowIndex++; DataRow dr = tmpT.NewRow(); tmpT.Rows.Add(dr); dicRow.Add(currRowIndex, dr); dr[0] = curr.ToString(); if (count == cols) { count = 0; } } else { tmpT.Rows[currRowIndex][count] = curr.ToString(); } count++; } } return tmpT; } private static void SearchTable(ref int currRowIndex, Array ori, Array curr, ref DataTable table) { for (int i = 0; i < curr.Length; i++) { bool isa = (curr as dynamic)[i] is Array; if (isa) { SearchTable(ref currRowIndex, ori, (curr as dynamic)[i], ref table); } else { if (table.Rows.Count < currRowIndex + 1) { DataRow newRow = table.NewRow(); table.Rows.Add(newRow); } try { table.Rows[currRowIndex][i] = (curr as Array).GetValue(i); } catch (Exception) { ; } if (i == curr.Length - 1) currRowIndex++; } } } private Spring.Caching.ICache cache; private Spring.Caching.ICache SpringCache { get { if (cache == null) cache = (Spring.Caching.ICache)ctx.GetObject("AspNetCache"); return cache; } set { cache = value; } } private static Spring.Caching.ICache getCache() { var cache = (Spring.Caching.ICache)Spring.Context.Support.ContextRegistry.GetContext().GetObject("AspNetCache"); return cache; } private Spring.Context.IApplicationContext _ctx; protected Spring.Context.IApplicationContext ctx { get { if (_ctx == null) _ctx = Spring.Context.Support.ContextRegistry.GetContext(); return _ctx; } } public static string ConvertValue2Name(string IdValue, string entity = "SysEnumDict", string idField = "EnumValue", string textField = "EnumName") { var ha = CallContext.GetData("Current") as Hashtable; if (ha == null) { ha = new Hashtable(); CallContext.SetData("Current", new Hashtable()); } Dictionary<string, string> dic = null; if (!ha.ContainsKey(entity + idField + textField)) { dic = ChangeType(entity, idField, textField, ""); ha[entity + idField + textField] = dic; } else { dic = ha[entity + idField + textField] as Dictionary<string, string>; } var value = ""; if (dic.ContainsKey(IdValue)) { value = dic[IdValue]; } return value; } /// <summary> /// 通用生成具有上下級樹的結構代碼 /// </summary> /// <param name="valueField">主鍵id</param> /// <param name="entity">表名</param> /// <param name="parentKey">parent_id</param> /// <param name="textField">文本字段</param> /// <param name="isFirst">是否第一次</param> /// <param name="where">條件</param> /// <returns></returns> public static IList<EasyUiTree> LoadEntityTree(string valueField, string entity,string nodeSourceKey, string parentKey, string textField, string where = "", string levelField="",string StrucIdKey="") { var Dao = GetDao(); IList<EasyUiTree> list = new List<EasyUiTree>(); QueryInfo info = new QueryInfo(); info.CustomSQL = "select * from " + entity; if (!string.IsNullOrEmpty(where)) { info.Where.Add("where", " and " + where); } var tempList = Dao.ExecuteDataSet(info); if (tempList.Tables[0].Rows.Count <= 0) { return new List<EasyUiTree>(); } info = new QueryInfo(); info.CustomSQL = string.Format("select * from {0} t", entity); var entityList = Dao.ExecuteDataSet(info); if (entityList.Tables[0].Rows.Count <= 0) { return new List<EasyUiTree>(); } //int parentKeyIndex = 0; //int valueFieldKeyIndex = 0; //int textFieldKeyIndex = 0; //valueFieldKeyIndex = 0; //textFieldKeyIndex = 1; //parentKeyIndex = 2; for (var i = 0; i < tempList.Tables[0].Rows.Count; i++) { DataRow objs = tempList.Tables[0].Rows[i]; string _parentValue = objs[parentKey] != null ? objs[parentKey].ToString() : null; string _valueField = objs[valueField] != null ? objs[valueField].ToString() : null; string _textField = objs[textField] != null ? objs[textField].ToString() : null; if ((string.IsNullOrEmpty(_parentValue))) { EasyUiTree c = new EasyUiTree(); c.id = _valueField; c.text = _textField; dynamic d=new System.Dynamic.ExpandoObject(); if (!string.IsNullOrEmpty(nodeSourceKey)) { d.tableRef =objs[nodeSourceKey].ToString(); } if (!string.IsNullOrEmpty(StrucIdKey)) { d.StrucId = objs[StrucIdKey].ToString(); } if (!string.IsNullOrEmpty(levelField)) { d.strucLevel = objs[levelField]; //c.attributes = new { tableRef = nodeSourceKey, isRoot = false, strucLevel = objs[levelField] }; } d.isRoot = true; c.attributes = d; if (HasEntityChildNode(objs, entityList, valueField, textField, parentKey)) { c.state = ""; } // (EasyUiTree parent, DataRow objs, DataSet allList, string valueField, string textField, string parentKey, string levelKey = "", string nodeSourceKey = "",string StrucIdKey="") addEntityChildNode(c, objs, entityList, valueField, textField, parentKey, levelField, nodeSourceKey, StrucIdKey); list.Add(c); } } return list; } private static bool HasEntityChildNode(DataRow objs, DataSet entityList, string valueField, string textField, string parentKey) { string _valueField = objs[valueField] != null ? objs[valueField].ToString() : null; for (var i = 0; i < entityList.Tables[0].Rows.Count; i++) { DataRow _child = entityList.Tables[0].Rows[i]; string _parentValue = _child[parentKey] != null ? _child[parentKey].ToString() : null; if (_valueField == _parentValue) { return true; } } return false; } private static void addEntityChildNode(EasyUiTree parent, DataRow objs, DataSet allList, string valueField, string textField, string parentKey, string levelKey = "", string nodeSourceKey = "",string StrucIdKey="") { parent.children = new List<EasyUiTree>(); for (var i = 0; i < allList.Tables[0].Rows.Count; i++) { DataRow childObj = allList.Tables[0].Rows[i]; if (childObj[parentKey] != null && !string.IsNullOrEmpty(childObj[parentKey].ToString()) && parent.id == childObj[parentKey].ToString()) { EasyUiTree c = new EasyUiTree(); c.id = childObj[valueField].ToString(); c.text = childObj[textField].ToString(); dynamic d = new System.Dynamic.ExpandoObject(); if (!string.IsNullOrEmpty(nodeSourceKey)) { d.tableRef =childObj[nodeSourceKey].ToString(); } if (!string.IsNullOrEmpty(StrucIdKey)) { d.StrucId = childObj[StrucIdKey].ToString(); } if (!string.IsNullOrEmpty(levelKey)) { d.strucLevel = childObj[levelKey]; } d.isRoot = false; c.attributes = d; //new { tableRef = childObj[nodeSourceKey], isRoot = false, strucLevel = objs[levelKey] }; if (HasEntityChildNode(childObj, allList, valueField, textField, parentKey)) { c.state = "closed"; addEntityChildNode(c, childObj, allList, valueField, textField, parentKey,levelKey,nodeSourceKey,StrucIdKey); } parent.children.Add(c); } } return; } } public class PropertyColumnMappingInfo { public string PropertyName { get; set; } public string ColumnName { get; set; } public Type ColumnType { get; set; } } }