.客户端代码
public static void FileMoveInVirtualMachineForCompressor()
{
var obj = new object();
string ip = "127.0.0.1";
int port = ;
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, , bs.Length);
writer.Flush();
writer.Close(); Net.SendFile(ip, port, toFile, , );
}
.服务端监听
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 = ;
Net.ListenerAcceptFile(ip, port, @"d:\ReciveFoder");
MessageBox.Show("监听程序已启动!!");
Console.ReadKey();
}
}
} .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 == )
{
throw new ArgumentException("参数buffer 为null ,或者长度为 0");
} int flag = ;
try
{
int totalLen = buffer.Length;
int sndLen = ; while (true)
{
if ((socket.Poll(outTime * , SelectMode.SelectWrite) == true))
{ // 收集了足够多的传出数据后开始发送
sndLen = socket.Send(buffer, sndLen, totalLen, SocketFlags.None);
totalLen -= sndLen;
if (totalLen == )
{ // 数据已经全部发送
flag = ;
break;
}
else
{
if (sndLen > )
{ // 数据部分已经被发送continue;
}
else
{ // 发送数据发生错误
flag = -;
break;
}
}
}
else
{ // 超时退出
flag = -;
break;
}
}
}
catch (SocketException e)
{ flag = -;
}
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();
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(endpoint);
if (socket.Connected)
{
Console.WriteLine(socket.RemoteEndPoint + "连接成功");
}
if (fileName == null || maxBufferLength <= )
{
throw new ArgumentException("待发送的文件名称为空或发送缓冲区的大小设置不正确.");
}
int flag = ;
try
{
var fileBytes = Encoding.UTF8.GetBytes(fileName);
var fbs = new byte[];
for (int i = ; 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 = ; // 已读取部分
byte[] buffer = null; if (fileLen <= maxBufferLength)
{ /* 文件可以一次读取*/
buffer = new byte[fileLen];
readLen = fs.Read(buffer, , (int)fileLen);
flag = SendData(socket, buffer, outTime);
}
else
{
/* 循环读取文件,并发送 */
while (totalLen != )
{
if (totalLen < maxBufferLength)
{
buffer = new byte[totalLen];
readLen = fs.Read(buffer, , Convert.ToInt32(totalLen));
}
else
{
buffer = new byte[maxBufferLength];
readLen = fs.Read(buffer, , maxBufferLength);
}
if ((flag = SendData(socket, buffer, outTime)) < )
{
break;
}
totalLen -= readLen;
}
}
fs.Flush();
fs.Close();
File.Delete(fileName);
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
catch (IOException e)
{ flag = -;
}
if (flag == )
{
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[];
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[];
int size = ;
//统计实际文件大小
long len = ;
//创建文件流,然后让文件流来根据路径创建一个文件
fs = new FileStream(fileName, FileMode.Append);
DateTime oTimeBegin = DateTime.Now;
//从终端不停的接受数据,然后写入文件里面,只到接受到的数据为0为止,则中断连接
while ((size = socketClient.Receive(buffer, , buffer.Length, SocketFlags.None)) > )
{
fs.Write(buffer, , 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, , item.Value.Length);
fw.Flush();
fw.Dispose();
}
File.Delete(fileName);
Console.WriteLine("文件保存成功:" + fileName);
Console.WriteLine("接收文件用时:" + oTime.ToString() + ",文件大小:" + len / + "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();
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, , );
Console.WriteLine("文件从" + fromPath + "到" + toPath + "移动成功!!!!");
} }
} .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=,
//非web应用的配置文件
App=,
}
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 - ];//我实际的标记是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 = ;
//实例化流对象
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 = ;
HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(url);
if (SPosition > )
myRequest.AddRange((int)SPosition); //设置Range值
Stream myStream = myRequest.GetResponse().GetResponseStream();
//定义一个字节数据
byte[] btContent = new byte[];
int intSize = ;
intSize = myStream.Read(btContent, , );
while (intSize > )
{
FStream.Write(btContent, , intSize);
intSize = myStream.Read(btContent, , );
}
//关闭流
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 ;
}
/// <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 = ;
foreach (DataRow row in tblSchema.Rows)
{
tableName = row["TABLE_NAME"].ToString();
mySheetName[i] = tableName;
i++;
}
return mySheetName;
}
catch (OleDbException err)
{
if (err.ErrorCode == -)
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 = ; i < s.Count(); i++)
{
s[i] = s[i].Substring(, ).ToUpper() + s[i].Substring().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 = ; 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 = ; i < c.Length; i++)
{
if (c[i] == )
{
c[i] = (char);
continue;
}
if (c[i] > && c[i] < )
c[i] = (char)(c[i] - );
}
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[].Value.ToUpper() + match.Groups[].Value.ToUpper() + "_";
}
private static string MatchEval(Match match)
{
return match.Groups[].Value.ToUpper() + match.Groups[].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[].ToString(), objs[].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, , 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(, 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, , 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, , (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 = ;
lock (lockSequence)
{ if (NeedId)
{
#region 1.获取当前序列之
QueryInfo searchInfo = new QueryInfo();
searchInfo.CustomSQL = $"select {v_seq}.NEXTVAL from dual";
table = Dao.ExecuteDataSet(searchInfo).Tables[];
increId = Convert.ToInt64(table.Rows[][].ToString());
#endregion #region 2.改变步长
info.NamedQuery = "PRO_SEQUENCE";
info.Parameters.Add("v_simulation_number", dt.Rows.Count-);
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[];
#endregion #region 4.步长改为1
info = new QueryInfo();
info.NamedQuery = "PRO_SEQUENCE";
info.Parameters.Add("v_simulation_number", -);
info.Parameters.Add("v_seq", v_seq);
Dao.ExecuteNonQuery(info);
#endregion increId = Convert.ToInt64(table.Rows[][].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 = * ;
bulkCopy.DestinationTableName = targetTable; //服务器上目标表的名称
bulkCopy.BatchSize = ; //每一批次中的行数
try
{
IDataReader rd = new DataTableReader(dt);
//conn.Open();
if (dt != null && dt.Rows.Count != ) bulkCopy.WriteToServer(rd); //将提供的数据源中的所有行复制到目标表中
}
catch (Exception ex)
{
throw ex;
}
finally
{
info = new QueryInfo();
info.NamedQuery = "PRO_SEQUENCE";
info.Parameters.Add("v_simulation_number", -);
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() <= )
{
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[];
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 = ; 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 = ; 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 = ;
SearchTable(ref currRowIndex, arr, arr, ref table); return table; }
//多维数组处理
else
{ int rank = arr.Rank;
int cols = arr.GetLength(rank - ); for (int i = ; i < cols; i++)
{
DataColumn col = new DataColumn(Guid.NewGuid().ToString());
tmpT.Columns.Add(col);
} Dictionary<int, int> dims = new Dictionary<int, int>();
int currRowIndex = -;
Dictionary<int, DataRow> dicRow = new Dictionary<int, DataRow>();
var iterator = arr.GetEnumerator();
int count = ;
while (iterator.MoveNext())
{
var curr = iterator.Current;
if (count % cols == )
{
currRowIndex++;
DataRow dr = tmpT.NewRow();
tmpT.Rows.Add(dr);
dicRow.Add(currRowIndex, dr);
dr[] = curr.ToString();
if (count == cols)
{
count = ;
} }
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 = ; 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 + )
{
DataRow newRow = table.NewRow();
table.Rows.Add(newRow);
} try
{
table.Rows[currRowIndex][i] = (curr as Array).GetValue(i);
}
catch (Exception)
{ ;
}
if (i == curr.Length - )
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[].Rows.Count <= )
{
return new List<EasyUiTree>();
} info = new QueryInfo();
info.CustomSQL = string.Format("select * from {0} t", entity); var entityList = Dao.ExecuteDataSet(info);
if (entityList.Tables[].Rows.Count <= )
{
return new List<EasyUiTree>();
} //int parentKeyIndex = 0;
//int valueFieldKeyIndex = 0;
//int textFieldKeyIndex = 0; //valueFieldKeyIndex = 0;
//textFieldKeyIndex = 1;
//parentKeyIndex = 2;
for (var i = ; i < tempList.Tables[].Rows.Count; i++)
{ DataRow objs = tempList.Tables[].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 = ; i < entityList.Tables[].Rows.Count; i++)
{
DataRow _child = entityList.Tables[].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 = ; i < allList.Tables[].Rows.Count; i++)
{
DataRow childObj = allList.Tables[].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; }
} }

socket多文件发送(压缩,解压)的更多相关文章

  1. Linux 压缩解压

    压缩解压 ------------------------------------------ linux 下所有的压缩格式,WinRAR 都支持 gzip .gz 格式 压缩文件: gzip 文件名 ...

  2. SAPCAR 压缩解压软件的使用方法

    SAPCAR 是 SAP 公司使用的压缩解压软件,从 SAP 网站下载的补丁包和小型软件基本都是扩展名为 car 或 sar 的,它们都可以用 SAPCAR 来解压.下面是它的使用说明: 用法: 创建 ...

  3. 对称加密之AES、压缩解压以及压缩加密解密解压综合实战

    AES 压缩解压 压缩加密解密解压 对称加密: 就是采用这种加密方法的双方使用方式用同样的密钥进行加密和解密.密钥是控制加密及解密过程的指令.算法是一组规则,规定如何进行加密和解密.   因此加密的安 ...

  4. linux笔记:linux常用命令-压缩解压命令

    压缩解压命令:gzip(压缩文件,不保留原文件.这个命令不能压缩目录) 压缩解压命令:gunzip(解压.gz的压缩文件) 压缩解压命令:tar(打包压缩目录或者解压压缩文件.打包的意思是把目录打包成 ...

  5. .NET使用ICSharpCode.SharpZipLib压缩/解压文件

    SharpZipLib是国外开源加压解压库,可以方便的对文件进行加压/解压 1.下载ICSharpCode.SharpZipLib.dll,并复制到bin目录下 http://www.icsharpc ...

  6. linux驱动系列之文件压缩解压小节(转)

    转至网页:http://www.jb51.net/LINUXjishu/43356.html Linux下最常用的打包程序就是tar了,使用tar程序打出来的包我们常称为tar包,tar包文件的命令通 ...

  7. Linux的压缩解压命令快速上手——解压篇

    在Linux系统中,压缩文件通常是先将若干文件(包括目录)打包成一个tar文件,然后再调用压缩程序将tar文件压缩成相应的压缩包,这也就是为什么Linux系的压缩包的后缀通常都是像tar.gz,tar ...

  8. RAR压缩解压命令

    RAR压缩解压命令 这几天一直没空更新博客,现在补上: 先介绍一下rar的命令格式及相关参数含义(摘自rar): 用法:   rar <命令> -<开关 1> -<开关 ...

  9. 使用SevenZipSharp压缩/解压7z格式

    7z格式采用的LZMA算法,号称具有现今最高压缩率.笔者在nuget上搜索7z,在搜索结果中最终选择了SevenZipSharp来进行压缩/解压.不得不说,SevenZipSharp的API设计得非常 ...

  10. huffman压缩解压文件【代码】

    距离上次写完哈夫曼编码已经过去一周了,这一周都在写huffman压缩解压,哎,在很多小错误上浪费了很多时间调bug.其实这个程序的最关键部分不是我自己想的,而是借鉴了某位园友的代码,但是,无论如何,自 ...

随机推荐

  1. oracle10偶然性卡住登陆

    连接数据库异常:登陆数据库后以"conn /as sysdba"方式登陆正常,数据库轻载,无压力:于是检查数据库的监听器,输入"lsntctl services" ...

  2. Some facts about topological sort

    Definition: a topological sort of a DAG G is a sort such that for all edge (i,j) in G, i precedes j. ...

  3. HTML5 Canvas ( 图形变换, 升级版的星空 ) translate, rotate, scale

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  4. Celery ---- 分布式队列神器 ---- 入门

    原文:http://python.jobbole.com/87238/ 参考:https://zhuanlan.zhihu.com/p/22304455 Celery 是什么? Celery 是一个由 ...

  5. Yii常用变量

    调用YII框架中 jquery:Yii::app()->clientScript->registerCoreScript('jquery'); 调用YII框架中 jquery:Yii::a ...

  6. Spring MVC 确定目标方法POJO 类型参数

    1:确定一个Key 2. 在implicitMode 中存在Key 对应的对象, 若存在则作为参数传入 3. 在implicitMode 中不存在Key 对应的对象, 则检查当前@SessionAtr ...

  7. Mysql 主键常用修改

    修改表的定增长初始值: ALTER TABLE 表名 AUTO_INCREMENT=值;

  8. as3 程序域

    问题我要在应用程序中载入其他域的swf文件,并且允许它访问程序中的 ActionScript 解决办法使用flash.system.Security.allowDomain( ), flash.sys ...

  9. C# 获取文件名、目录、后缀、无后缀文件名、扩展名、根目录等

    [csharp] view plain copy class Program { static void Main(string[] args) { //获取当前运行程序的目录 string file ...

  10. event bManualResult

    MSDN: bManualReset [in] If this parameter is TRUE, the function creates a manual-reset event object, ...