添加项目文件。

master
王剑峰 2 years ago
parent 31de771504
commit d3520976e9

@ -0,0 +1,377 @@
namespace MenuTool
{
partial class Form1
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要修改
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.txtSortNo = new System.Windows.Forms.NumericUpDown();
this.label5 = new System.Windows.Forms.Label();
this.cmdMenuSort = new System.Windows.Forms.Button();
this.cmdCopySql = new System.Windows.Forms.Button();
this.txtsql = new System.Windows.Forms.RichTextBox();
this.cmdSql = new System.Windows.Forms.Button();
this.cmdDelete2 = new System.Windows.Forms.Button();
this.chk_PopedomType = new System.Windows.Forms.CheckBox();
this.txtModuleUrl = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.cmdNext = new System.Windows.Forms.Button();
this.cmdPrev = new System.Windows.Forms.Button();
this.cmdDel = new System.Windows.Forms.Button();
this.cmdSave = new System.Windows.Forms.Button();
this.cmdAdd = new System.Windows.Forms.Button();
this.txtMenuName = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.txtMenuNo = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.txtParentMenuNo = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.treeView1 = new System.Windows.Forms.TreeView();
this.label6 = new System.Windows.Forms.Label();
this.comboBox1 = new System.Windows.Forms.ComboBox();
this.label7 = new System.Windows.Forms.Label();
this.comboBox2 = new System.Windows.Forms.ComboBox();
((System.ComponentModel.ISupportInitialize)(this.txtSortNo)).BeginInit();
this.SuspendLayout();
//
// txtSortNo
//
this.txtSortNo.Location = new System.Drawing.Point(376, 203);
this.txtSortNo.Margin = new System.Windows.Forms.Padding(2);
this.txtSortNo.Maximum = new decimal(new int[] {
999,
0,
0,
0});
this.txtSortNo.Name = "txtSortNo";
this.txtSortNo.Size = new System.Drawing.Size(250, 21);
this.txtSortNo.TabIndex = 59;
this.txtSortNo.Value = new decimal(new int[] {
101,
0,
0,
0});
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(294, 204);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(47, 12);
this.label5.TabIndex = 58;
this.label5.Text = "排序号:";
//
// cmdMenuSort
//
this.cmdMenuSort.Location = new System.Drawing.Point(346, 391);
this.cmdMenuSort.Name = "cmdMenuSort";
this.cmdMenuSort.Size = new System.Drawing.Size(75, 44);
this.cmdMenuSort.TabIndex = 57;
this.cmdMenuSort.Text = "排序子菜单";
this.cmdMenuSort.UseVisualStyleBackColor = true;
//
// cmdCopySql
//
this.cmdCopySql.Font = new System.Drawing.Font("宋体", 18F);
this.cmdCopySql.Location = new System.Drawing.Point(681, 452);
this.cmdCopySql.Name = "cmdCopySql";
this.cmdCopySql.Size = new System.Drawing.Size(53, 96);
this.cmdCopySql.TabIndex = 56;
this.cmdCopySql.Text = "复制";
this.cmdCopySql.UseVisualStyleBackColor = true;
//
// txtsql
//
this.txtsql.Location = new System.Drawing.Point(295, 443);
this.txtsql.Name = "txtsql";
this.txtsql.Size = new System.Drawing.Size(373, 117);
this.txtsql.TabIndex = 55;
this.txtsql.Text = "";
//
// cmdSql
//
this.cmdSql.Location = new System.Drawing.Point(427, 391);
this.cmdSql.Name = "cmdSql";
this.cmdSql.Size = new System.Drawing.Size(156, 44);
this.cmdSql.TabIndex = 54;
this.cmdSql.Text = "生成SQL语句";
this.cmdSql.UseVisualStyleBackColor = true;
//
// cmdDelete2
//
this.cmdDelete2.Location = new System.Drawing.Point(508, 280);
this.cmdDelete2.Name = "cmdDelete2";
this.cmdDelete2.Size = new System.Drawing.Size(75, 44);
this.cmdDelete2.TabIndex = 53;
this.cmdDelete2.Text = "标记删除";
this.cmdDelete2.UseVisualStyleBackColor = true;
//
// chk_PopedomType
//
this.chk_PopedomType.AutoSize = true;
this.chk_PopedomType.Checked = true;
this.chk_PopedomType.CheckState = System.Windows.Forms.CheckState.Checked;
this.chk_PopedomType.Location = new System.Drawing.Point(297, 252);
this.chk_PopedomType.Name = "chk_PopedomType";
this.chk_PopedomType.Size = new System.Drawing.Size(108, 16);
this.chk_PopedomType.TabIndex = 52;
this.chk_PopedomType.Text = "是否默认有权限";
this.chk_PopedomType.UseVisualStyleBackColor = true;
//
// txtModuleUrl
//
this.txtModuleUrl.Location = new System.Drawing.Point(376, 167);
this.txtModuleUrl.Name = "txtModuleUrl";
this.txtModuleUrl.Size = new System.Drawing.Size(251, 21);
this.txtModuleUrl.TabIndex = 51;
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(293, 172);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(65, 12);
this.label4.TabIndex = 50;
this.label4.Text = "网页地址:";
//
// cmdNext
//
this.cmdNext.Location = new System.Drawing.Point(427, 340);
this.cmdNext.Name = "cmdNext";
this.cmdNext.Size = new System.Drawing.Size(75, 44);
this.cmdNext.TabIndex = 49;
this.cmdNext.Text = "下移";
this.cmdNext.UseVisualStyleBackColor = true;
//
// cmdPrev
//
this.cmdPrev.Location = new System.Drawing.Point(346, 340);
this.cmdPrev.Name = "cmdPrev";
this.cmdPrev.Size = new System.Drawing.Size(75, 44);
this.cmdPrev.TabIndex = 48;
this.cmdPrev.Text = "上移";
this.cmdPrev.UseVisualStyleBackColor = true;
//
// cmdDel
//
this.cmdDel.Location = new System.Drawing.Point(508, 340);
this.cmdDel.Name = "cmdDel";
this.cmdDel.Size = new System.Drawing.Size(75, 44);
this.cmdDel.TabIndex = 47;
this.cmdDel.Text = "直接删除";
this.cmdDel.UseVisualStyleBackColor = true;
//
// cmdSave
//
this.cmdSave.Location = new System.Drawing.Point(427, 280);
this.cmdSave.Name = "cmdSave";
this.cmdSave.Size = new System.Drawing.Size(75, 44);
this.cmdSave.TabIndex = 46;
this.cmdSave.Text = "修改";
this.cmdSave.UseVisualStyleBackColor = true;
//
// cmdAdd
//
this.cmdAdd.Location = new System.Drawing.Point(346, 280);
this.cmdAdd.Name = "cmdAdd";
this.cmdAdd.Size = new System.Drawing.Size(75, 44);
this.cmdAdd.TabIndex = 45;
this.cmdAdd.Text = "新增并保存";
this.cmdAdd.UseVisualStyleBackColor = true;
//
// txtMenuName
//
this.txtMenuName.Location = new System.Drawing.Point(376, 132);
this.txtMenuName.Name = "txtMenuName";
this.txtMenuName.Size = new System.Drawing.Size(251, 21);
this.txtMenuName.TabIndex = 44;
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(293, 135);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(65, 12);
this.label3.TabIndex = 43;
this.label3.Text = "菜单名称:";
//
// txtMenuNo
//
this.txtMenuNo.Location = new System.Drawing.Point(376, 69);
this.txtMenuNo.Name = "txtMenuNo";
this.txtMenuNo.Size = new System.Drawing.Size(251, 21);
this.txtMenuNo.TabIndex = 42;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(294, 74);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(65, 12);
this.label2.TabIndex = 41;
this.label2.Text = "菜单编号:";
//
// txtParentMenuNo
//
this.txtParentMenuNo.Location = new System.Drawing.Point(376, 103);
this.txtParentMenuNo.Name = "txtParentMenuNo";
this.txtParentMenuNo.Size = new System.Drawing.Size(251, 21);
this.txtParentMenuNo.TabIndex = 40;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(293, 106);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(77, 12);
this.label1.TabIndex = 39;
this.label1.Text = "父菜单编号:";
//
// treeView1
//
this.treeView1.CheckBoxes = true;
this.treeView1.Dock = System.Windows.Forms.DockStyle.Left;
this.treeView1.Location = new System.Drawing.Point(0, 0);
this.treeView1.Name = "treeView1";
this.treeView1.Size = new System.Drawing.Size(202, 582);
this.treeView1.TabIndex = 38;
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(300, 9);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(41, 12);
this.label6.TabIndex = 60;
this.label6.Text = "机构:";
//
// comboBox1
//
this.comboBox1.FormattingEnabled = true;
this.comboBox1.Location = new System.Drawing.Point(376, 6);
this.comboBox1.Name = "comboBox1";
this.comboBox1.Size = new System.Drawing.Size(250, 20);
this.comboBox1.TabIndex = 61;
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(294, 34);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(65, 12);
this.label7.TabIndex = 62;
this.label7.Text = "菜单类型:";
//
// comboBox2
//
this.comboBox2.FormattingEnabled = true;
this.comboBox2.Items.AddRange(new object[] {
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9"});
this.comboBox2.Location = new System.Drawing.Point(376, 34);
this.comboBox2.Name = "comboBox2";
this.comboBox2.Size = new System.Drawing.Size(250, 20);
this.comboBox2.TabIndex = 63;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 582);
this.Controls.Add(this.comboBox2);
this.Controls.Add(this.label7);
this.Controls.Add(this.comboBox1);
this.Controls.Add(this.label6);
this.Controls.Add(this.txtSortNo);
this.Controls.Add(this.label5);
this.Controls.Add(this.cmdMenuSort);
this.Controls.Add(this.cmdCopySql);
this.Controls.Add(this.txtsql);
this.Controls.Add(this.cmdSql);
this.Controls.Add(this.cmdDelete2);
this.Controls.Add(this.chk_PopedomType);
this.Controls.Add(this.txtModuleUrl);
this.Controls.Add(this.label4);
this.Controls.Add(this.cmdNext);
this.Controls.Add(this.cmdPrev);
this.Controls.Add(this.cmdDel);
this.Controls.Add(this.cmdSave);
this.Controls.Add(this.cmdAdd);
this.Controls.Add(this.txtMenuName);
this.Controls.Add(this.label3);
this.Controls.Add(this.txtMenuNo);
this.Controls.Add(this.label2);
this.Controls.Add(this.txtParentMenuNo);
this.Controls.Add(this.label1);
this.Controls.Add(this.treeView1);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
((System.ComponentModel.ISupportInitialize)(this.txtSortNo)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.NumericUpDown txtSortNo;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Button cmdMenuSort;
private System.Windows.Forms.Button cmdCopySql;
private System.Windows.Forms.RichTextBox txtsql;
private System.Windows.Forms.Button cmdSql;
private System.Windows.Forms.Button cmdDelete2;
private System.Windows.Forms.CheckBox chk_PopedomType;
private System.Windows.Forms.TextBox txtModuleUrl;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Button cmdNext;
private System.Windows.Forms.Button cmdPrev;
private System.Windows.Forms.Button cmdDel;
private System.Windows.Forms.Button cmdSave;
private System.Windows.Forms.Button cmdAdd;
private System.Windows.Forms.TextBox txtMenuName;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox txtMenuNo;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox txtParentMenuNo;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TreeView treeView1;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.ComboBox comboBox1;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.ComboBox comboBox2;
}
}

@ -0,0 +1,459 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace MenuTool
{
public partial class Form1 : Form
{
List<SysMenu> ListMenu = null;
SysMenu CurrentMenu = null;
bool IsDeleteMenu = false;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
ReadMenu();
}
#region 读取菜单
public void ReadMenu()
{
ListMenu = StaticModel.GetListMenu();
List<SysMenu> list = GetListMenu(0);
treeView1.Nodes.Clear();
foreach (var item in list)
{
TreeNode node = new TreeNode();
node.Text = item.ModuleName;
node.Tag = item;
if (item.IsUse == 1) { node.Checked = true; }
else { node.Checked = false; }
treeView1.Nodes.Add(node);
BindChildTreeView(node, item.ModuleNo);
}
}
#endregion
#region 绑定树节点
public void BindChildTreeView(TreeNode ParentNode, int ParentModuleNo)
{
List<SysMenu> list = GetListMenu(ParentModuleNo);
foreach (var item in list)
{
TreeNode node = new TreeNode();
node.Text = item.ModuleName;
node.Tag = item;
if (item.IsUse == 1) { node.Checked = true; }
else { node.Checked = false; }
ParentNode.Nodes.Add(node);
BindChildTreeView(node, item.ModuleNo);
}
}
#endregion
#region 读取子菜单
public List<SysMenu> GetListMenu(int ParentModuleNo)
{
if (ListMenu == null) return new List<SysMenu>();
var query = from item in ListMenu
where item.ParentModuleNo == ParentModuleNo
orderby item.SortNo
select item;
List<SysMenu> list = query.ToList<SysMenu>();
//int index = 11;
//foreach (var item in list)
//{
// item.SortNo = index.ToString();
// index++;
//}
return list;
}
#endregion
#region 保存选择菜单
void SaveTreeView()
{
foreach (TreeNode item in treeView1.Nodes)
{
SysMenu model = (SysMenu)item.Tag;
if (item.Checked == true) { model.IsUse = 1; }
else { model.IsUse = 0; }
StaticModel.ChangeMenuState(model.id, model.IsUse);
SaveTreeNode(item);
}
}
void SaveTreeNode(TreeNode node)
{
foreach (TreeNode item in node.Nodes)
{
SysMenu model = (SysMenu)item.Tag;
if (item.Checked == true) { model.IsUse = 1; }
else { model.IsUse = 0; }
StaticModel.ChangeMenuState(model.id, model.IsUse);
SaveTreeNode(item);
}
}
#endregion
#region 选择所有下属性节点
bool TreeNodeCheckEvent = true;
public void SelectNextTreeViewChecked(TreeNode node)
{
foreach (TreeNode item in node.Nodes)
{
SysMenu model = (SysMenu)item.Tag;
item.Checked = node.Checked;
if (item.Checked == true) { model.IsUse = 1; }
else { model.IsUse = 0; }
StaticModel.ChangeMenuState(model.id, model.IsUse);
SelectNextTreeViewChecked(item);
}
}
#endregion
#region 选择所有上属节点
public void SelectPrevTreeViewChecked(TreeNode node)
{
if (node.Checked == false) return;
if (node.Parent == null) return;
TreeNode item = (TreeNode)node.Parent;
item.Checked = true;
SysMenu model = (SysMenu)item.Tag;
if (item.Checked == true) { model.IsUse = 1; }
else { model.IsUse = 0; }
StaticModel.ChangeMenuState(model.id, model.IsUse);
SelectPrevTreeViewChecked(item);
}
#endregion
#region 清空
void Clear()
{
IsDeleteMenu = false;
txtMenuNo.Text = "";
txtParentMenuNo.Text = "";
txtMenuName.Text = "";
txtModuleUrl.Text = "";
chk_PopedomType.Checked = true;
CurrentMenu = null;
}
#endregion
private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
SysMenu model = (SysMenu)e.Node.Tag;
txtMenuNo.Text = model.ModuleNo.ToString();
txtParentMenuNo.Text = model.ParentModuleNo.ToString();
txtMenuName.Text = model.ModuleName;
txtModuleUrl.Text = model.ModuleUrl;
txtSortNo.Value = Convert.ToInt32(model.SortNo);
if (model.PopedomType == 0) { chk_PopedomType.Checked = false; }
else { chk_PopedomType.Checked = true; }
CurrentMenu = model;
IsDeleteMenu = false;
}
private void cmdAdd_Click(object sender, EventArgs e)
{
//IsDeleteMenu = false;
//txtMenuNo.Text = "";
//txtParentMenuNo.Text ="";
//txtMenuName.Text = "";
//txtModuleUrl.Text = "";
//chk_PopedomType.Checked = true;
//CurrentMenu = null;
string MenuNo = txtMenuNo.Text.Trim();
string ParentMenuNo = txtParentMenuNo.Text.Trim();
if (ParentMenuNo == "") ParentMenuNo = "0";
if (string.IsNullOrEmpty(MenuNo) == true)
{
MessageBox.Show("菜单编号必须填写");
return;
}
if (DataRegex.IsNumberInteger(MenuNo) == false)
{
MessageBox.Show("菜单编号必须是数字");
return;
}
if (string.IsNullOrEmpty(ParentMenuNo) == false && DataRegex.IsNumberInteger(ParentMenuNo) == false)
{
MessageBox.Show("父菜单编号必须是数字");
return;
}
if (CurrentMenu == null) CurrentMenu = new SysMenu();
CurrentMenu.id = 0;
CurrentMenu.ModuleNo = Convert.ToInt32(MenuNo);
CurrentMenu.ParentModuleNo = Convert.ToInt32(ParentMenuNo);
CurrentMenu.ModuleName = txtMenuName.Text.Trim();
CurrentMenu.ModuleUrl = txtModuleUrl.Text.Trim();
CurrentMenu.SortNo = txtSortNo.Value.ToString();
if (chk_PopedomType.Checked == false) { CurrentMenu.PopedomType = 0; }
else { CurrentMenu.PopedomType = 1; }
List<SysMenu> list = GetListMenu(CurrentMenu.ParentModuleNo);
if (CurrentMenu.id == 0 || IsDeleteMenu == true)
{
//CurrentMenu.SortNo = Convert.ToString(list.Count + 11);
}
if (string.IsNullOrEmpty(CurrentMenu.ModuleName) == true)
{
MessageBox.Show("菜单名称必须填写");
return;
}
foreach (var item in list)
{
if (item.id == CurrentMenu.id) continue;
StaticModel.SaveMenu(item);
}
bool bk = StaticModel.SaveMenu(CurrentMenu);
if (bk == false)
{
MessageBox.Show("菜单编号已经存在");
return;
}
CurrentMenu = null;
ReadMenu();
MessageBox.Show("新增成功");
}
private void cmdSave_Click(object sender, EventArgs e)
{
string MenuNo = txtMenuNo.Text.Trim();
string ParentMenuNo = txtParentMenuNo.Text.Trim();
if (ParentMenuNo == "") ParentMenuNo = "0";
if (string.IsNullOrEmpty(MenuNo) == true)
{
MessageBox.Show("菜单编号必须填写");
return;
}
if (DataRegex.IsNumberInteger(MenuNo) == false)
{
MessageBox.Show("菜单编号必须是数字");
return;
}
if (string.IsNullOrEmpty(ParentMenuNo) == false && DataRegex.IsNumberInteger(ParentMenuNo) == false)
{
MessageBox.Show("父菜单编号必须是数字");
return;
}
if (CurrentMenu == null) CurrentMenu = new SysMenu();
CurrentMenu.ModuleNo = Convert.ToInt32(MenuNo);
CurrentMenu.ParentModuleNo = Convert.ToInt32(ParentMenuNo);
CurrentMenu.ModuleName = txtMenuName.Text.Trim();
CurrentMenu.ModuleUrl = txtModuleUrl.Text.Trim();
CurrentMenu.SortNo = txtSortNo.Value.ToString();
if (chk_PopedomType.Checked == false) { CurrentMenu.PopedomType = 0; }
else { CurrentMenu.PopedomType = 1; }
//List<SysMenu> list = GetListMenu(CurrentMenu.ParentModuleNo);
if (CurrentMenu.id == 0 || IsDeleteMenu == true)
{
//CurrentMenu.SortNo = Convert.ToString(list.Count + 11);
}
if (string.IsNullOrEmpty(CurrentMenu.ModuleName) == true)
{
MessageBox.Show("菜单名称必须填写");
return;
}
//foreach (var item in list)
//{
// if (item.id == CurrentMenu.id) continue;
// StaticModel.SaveMenu(item);
//}
bool bk = StaticModel.SaveMenu(CurrentMenu);
if (bk == false)
{
MessageBox.Show("菜单编号已经存在");
return;
}
CurrentMenu = null;
ReadMenu();
MessageBox.Show("修改成功");
}
private void cmdDel_Click(object sender, EventArgs e)
{
//真删除
if (CurrentMenu == null)
{
MessageBox.Show("请选择菜单");
return;
}
StaticModel.DeleteMenu(CurrentMenu.id);
Clear();
ReadMenu();
MessageBox.Show("成功");
}
private void cmdDelete2_Click(object sender, EventArgs e)
{
//假删除
if (CurrentMenu == null)
{
MessageBox.Show("请选择菜单");
return;
}
StaticModel.DeleteMenu2(CurrentMenu.id);
Clear();
ReadMenu();
MessageBox.Show("成功");
}
private void cmdPrev_Click(object sender, EventArgs e)
{
if (CurrentMenu == null)
{
MessageBox.Show("请选择菜单");
return;
}
if (Convert.ToInt32(CurrentMenu.SortNo) - 10 == 1)
{
MessageBox.Show("已经是第一个了");
return;
}
List<SysMenu> list = GetListMenu(CurrentMenu.ParentModuleNo);
if (list.Count == 1)
{
MessageBox.Show("只有一个菜单不能调整");
return;
}
for (int i = 0; i < list.Count; i++)
{
if (CurrentMenu.SortNo == list[i].SortNo)
{
list[i].SortNo = Convert.ToString(Convert.ToInt32(list[i].SortNo) - 1);
StaticModel.SetMenuPosition(list[i].id, list[i].SortNo);
list[i - 1].SortNo = Convert.ToString(Convert.ToInt32(list[i - 1].SortNo) + 1);
StaticModel.SetMenuPosition(list[i - 1].id, list[i - 1].SortNo);
}
else
{
StaticModel.SetMenuPosition(list[i].id, list[i].SortNo);
}
}
Clear();
ReadMenu();
//MessageBox.Show("成功");
}
private void cmdNext_Click(object sender, EventArgs e)
{
if (CurrentMenu == null)
{
MessageBox.Show("请选择菜单");
return;
}
List<SysMenu> list = GetListMenu(CurrentMenu.ParentModuleNo);
if (list.Count == 1)
{
MessageBox.Show("只有一个菜单不能调整");
return;
}
if (Convert.ToInt32(CurrentMenu.SortNo) - 10 == list.Count)
{
MessageBox.Show("已经是最后了");
return;
}
bool bk = false;
for (int i = 0; i < list.Count; i++)
{
if (bk == true) continue;
if (CurrentMenu.SortNo == list[i].SortNo)
{
list[i].SortNo = Convert.ToString(Convert.ToInt32(list[i].SortNo) + 1);
StaticModel.SetMenuPosition(list[i].id, list[i].SortNo);
list[i + 1].SortNo = Convert.ToString(Convert.ToInt32(list[i + 1].SortNo) - 1);
StaticModel.SetMenuPosition(list[i + 1].id, list[i + 1].SortNo);
bk = true;
}
else
{
StaticModel.SetMenuPosition(list[i].id, list[i].SortNo);
}
}
Clear();
ReadMenu();
//MessageBox.Show("成功");
}
private void txtMenuNo_Leave(object sender, EventArgs e)
{
string MenuNo = txtMenuNo.Text.Trim();
if (string.IsNullOrEmpty(txtMenuNo.Text) == true) return;
if (DataRegex.IsNumberInteger(MenuNo) == false) return;
int ModuleNo = Convert.ToInt32(MenuNo);
SysMenu model = StaticModel.GetDeleteMenu(ModuleNo);
if (model == null) return;
IsDeleteMenu = true;
CurrentMenu = model;
txtMenuNo.Text = model.ModuleNo.ToString();
txtParentMenuNo.Text = model.ParentModuleNo.ToString();
txtMenuName.Text = model.ModuleName;
txtModuleUrl.Text = model.ModuleUrl;
if (model.PopedomType == 0) { chk_PopedomType.Checked = false; }
else { chk_PopedomType.Checked = true; }
}
private void cmdMenuCheck_Click(object sender, EventArgs e)
{
SaveTreeView();
MessageBox.Show("保存成功");
}
private void treeView1_AfterCheck(object sender, TreeViewEventArgs e)
{
if (TreeNodeCheckEvent == false) return;
TreeNodeCheckEvent = false;
TreeNode item = e.Node;
SysMenu model = (SysMenu)item.Tag;
if (item.Checked == true) { model.IsUse = 1; }
else { model.IsUse = 0; }
StaticModel.ChangeMenuState(model.id, model.IsUse);
SelectNextTreeViewChecked(e.Node);
SelectPrevTreeViewChecked(e.Node);
TreeNodeCheckEvent = true;
}
private void cmdSql_Click(object sender, EventArgs e)
{
if (CurrentMenu == null)
{
MessageBox.Show("请选择菜单");
return;
}
txtsql.Text = StaticModel.GetMenuSql(CurrentMenu.id);
}
private void cmdCopySql_Click(object sender, EventArgs e)
{
Clipboard.SetDataObject(txtsql.Text);
}
private void cmdMenuSort_Click(object sender, EventArgs e)
{
List<SysMenu> ListModel = StaticModel.GetListChildMenu(CurrentMenu.ModuleNo);
if (ListModel == null)
{
MessageBox.Show("该菜单下面没有子菜单");
return;
}
foreach (var item in ListModel)
{
int sort = 101 + ListModel.IndexOf(item);
StaticModel.SetMenuPosition(item.id, sort.ToString());
}
Clear();
ReadMenu();
MessageBox.Show("保存成功");
}
}
}

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

@ -0,0 +1,82 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{99FFA09B-022A-4685-8F99-F29636D5B87F}</ProjectGuid>
<OutputType>WinExe</OutputType>
<RootNamespace>MenuTool</RootNamespace>
<AssemblyName>MenuTool</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>x86</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Deployment" />
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Form1.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="Form1.Designer.cs">
<DependentUpon>Form1.cs</DependentUpon>
</Compile>
<Compile Include="Model\BaseModel.cs" />
<Compile Include="Model\SysMenu.cs" />
<Compile Include="Model\WX_App.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="StaticModel.cs" />
<EmbeddedResource Include="Form1.resx">
<DependentUpon>Form1.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.5.33516.290
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MenuTool", "MenuTool.csproj", "{99FFA09B-022A-4685-8F99-F29636D5B87F}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{99FFA09B-022A-4685-8F99-F29636D5B87F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{99FFA09B-022A-4685-8F99-F29636D5B87F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{99FFA09B-022A-4685-8F99-F29636D5B87F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{99FFA09B-022A-4685-8F99-F29636D5B87F}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {B56BC6AC-8C28-4F2F-B03C-0C4861729417}
EndGlobalSection
EndGlobal

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MenuTool
{
public class BaseModel
{
public int ID { get; set; }
public string Name { get; set; }
}
}

@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MenuTool
{
public class SysMenu
{
public int id { get; set; }
public int ModuleNo { get; set; }
public string ModuleName { get; set; }
public string ModuleUrl { get; set; }
public int ParentModuleNo { get; set; }
public string SortNo { get; set; }
public int Layer { get; set; }
public int PopedomType { get; set; }
public int IsUse { get; set; }
}
}

@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MenuTool
{
#region 手机菜单
public class WX_App
{
public Int32? Id { get; set; }
public Int32? CompanyId { get; set; }
public String AppName { get; set; }
public String FunCode { get; set; }
public Int32? SortNo { get; set; }
public String AppUrl { get; set; }
public String UserType { get; set; }
public String ICOUrl { get; set; }
public Int32? AppType { get; set; }
public Int32? PopedomType { get; set; }
public bool? IsUse { get; set; }
public WX_App()
{
ICOUrl = "resources/images/icon_nav_article.png";
}
}
#endregion
}

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace MenuTool
{
internal static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("MenuTool")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MenuTool")]
[assembly: AssemblyCopyright("Copyright © 2023")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("99ffa09b-022a-4685-8f99-f29636d5b87f")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值
//通过使用 "*",如下所示:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

@ -0,0 +1,71 @@
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本: 4.0.30319.42000
//
// 对此文件的更改可能导致不正确的行为,如果
// 重新生成代码,则所做更改将丢失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace MenuTool.Properties
{
/// <summary>
/// 强类型资源类,用于查找本地化字符串等。
/// </summary>
// 此类是由 StronglyTypedResourceBuilder
// 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
// 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen
// (以 /str 作为命令选项),或重新生成 VS 项目。
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// 返回此类使用的缓存 ResourceManager 实例。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("MenuTool.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// 重写当前线程的 CurrentUICulture 属性,对
/// 使用此强类型资源类的所有资源查找执行重写。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}

@ -0,0 +1,117 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

@ -0,0 +1,30 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace MenuTool.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}

@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>

@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data;
using System.Linq;
using System.Text;
namespace MenuTool
{
public class StaticModel
{
public static string SetupPath = "";
public static string BaseDirectoryName = "";
#region 查询机构
public static List<BaseModel> GetListCompany(int UserID, string UserType)
{
string tsql = @"
if @UserType='M' --
begin
select ID=CompanyID,Name=CompanyName from JC_Company where State=1
end
else
begin
select ID=a.CompanyID,Name=a.CompanyName from JC_Company a
inner join JC_UserInfo b on a.CompanyID=b.CompanyID
where UserID=@UserID
end
";
Database db = DatabaseFactory.CreateDatabase();
DbCommand cmd = db.GetSqlStringCommand(tsql);
db.AddInParameter(cmd, "@UserType", DbType.String, UserType);
db.AddInParameter(cmd, "@UserID", DbType.Int32, UserID);
DataTable tb = db.ExecuteDataTable(cmd);
List<BaseModel> ListModel = tb.ToList<BaseModel>();
return ListModel;
}
#endregion
}
}

@ -0,0 +1,297 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
namespace HuizhongLibrary
{
public class KeyBookHook
{
#region Windows structure definitions
[StructLayout(LayoutKind.Sequential)]
private class POINT
{
public int x;
public int y;
}
[StructLayout(LayoutKind.Sequential)]
private class MouseHookStruct
{
public POINT pt;
public int hwnd;
public int wHitTestCode;
public int dwExtraInfo;
}
[StructLayout(LayoutKind.Sequential)]
private class MouseLLHookStruct
{
public POINT pt;
public int mouseData;
public int flags;
public int time;
public int dwExtraInfo;
}
[StructLayout(LayoutKind.Sequential)]
private class KeyboardHookStruct
{
public int vkCode;
public int scanCode;
public int flags;
public int time;
public int dwExtraInfo;
}
#endregion
#region Windows function imports
[DllImport("user32.dll", CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall, SetLastError = true)]
private static extern int SetWindowsHookEx(
int idHook,
HookProc lpfn,
IntPtr hMod,
int dwThreadId);
[DllImport("user32.dll", CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall, SetLastError = true)]
private static extern int UnhookWindowsHookEx(int idHook);
[DllImport("user32.dll", CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall)]
private static extern int CallNextHookEx(
int idHook,
int nCode,
int wParam,
IntPtr lParam);
private delegate int HookProc(int nCode, int wParam, IntPtr lParam);
[DllImport("user32")]
private static extern int ToAscii(
int uVirtKey,
int uScanCode,
byte[] lpbKeyState,
byte[] lpwTransKey,
int fuState);
[DllImport("user32")]
private static extern int GetKeyboardState(byte[] pbKeyState);
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
private static extern short GetKeyState(int vKey);
[DllImport("kernel32.dll")]
public static extern IntPtr GetModuleHandle(string name);
#endregion
#region Windows constants
private const int WH_MOUSE_LL = 14;
private const int WH_KEYBOARD_LL = 13;
private const int WH_MOUSE = 7;
private const int WH_KEYBOARD = 2;
private const int WM_MOUSEMOVE = 0x200;
private const int WM_LBUTTONDOWN = 0x201;
private const int WM_RBUTTONDOWN = 0x204;
private const int WM_MBUTTONDOWN = 0x207;
private const int WM_LBUTTONUP = 0x202;
private const int WM_RBUTTONUP = 0x205;
private const int WM_MBUTTONUP = 0x208;
private const int WM_LBUTTONDBLCLK = 0x203;
private const int WM_RBUTTONDBLCLK = 0x206;
private const int WM_MBUTTONDBLCLK = 0x209;
private const int WM_MOUSEWHEEL = 0x020A;
private const int WM_KEYDOWN = 0x100;
private const int WM_KEYUP = 0x101;
private const int WM_SYSKEYDOWN = 0x104;
private const int WM_SYSKEYUP = 0x105;
private const byte VK_SHIFT = 0x10;
private const byte VK_CAPITAL = 0x14;
private const byte VK_NUMLOCK = 0x90;
#endregion
public KeyBookHook()
{
//Start();
}
public KeyBookHook(bool InstallMouseHook, bool InstallKeyboardHook)
{
Start(InstallMouseHook, InstallKeyboardHook);
}
~KeyBookHook()
{
Stop(true, true, false);
}
public event MouseEventHandler OnMouseActivity;
public event KeyEventHandler KeyDown;
public event KeyPressEventHandler KeyPress;
public event KeyEventHandler KeyUp;
private int hMouseHook = 0;
private int hKeyboardHook = 0;
private static HookProc MouseHookProcedure;
private static HookProc KeyboardHookProcedure;
public void Start()
{
this.Start(true, true);
}
public void Start(bool InstallMouseHook, bool InstallKeyboardHook)
{
if (hMouseHook == 0 && InstallMouseHook)
{
MouseHookProcedure = new HookProc(MouseHookProc);
IntPtr im = GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName);
hMouseHook = SetWindowsHookEx(WH_MOUSE_LL, MouseHookProcedure, im, 0);
if (hMouseHook == 0)
{
int errorCode = Marshal.GetLastWin32Error();
Stop(true, false, false);
throw new Win32Exception(errorCode);
}
}
if (hKeyboardHook == 0 && InstallKeyboardHook)
{
KeyboardHookProcedure = new HookProc(KeyboardHookProc);
//IntPtr im = Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]);
IntPtr im = GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName);
hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL,KeyboardHookProcedure, im, 0);
if (hKeyboardHook == 0)
{
int errorCode = Marshal.GetLastWin32Error();
Stop(false, true, false);
throw new Win32Exception(errorCode);
}
}
}
public void Stop()
{
this.Stop(true, true, true);
}
public void Stop(bool UninstallMouseHook, bool UninstallKeyboardHook, bool ThrowExceptions)
{
if (hMouseHook != 0 && UninstallMouseHook)
{
int retMouse = UnhookWindowsHookEx(hMouseHook);
hMouseHook = 0;
if (retMouse == 0 && ThrowExceptions)
{
int errorCode = Marshal.GetLastWin32Error();
throw new Win32Exception(errorCode);
}
}
if (hKeyboardHook != 0 && UninstallKeyboardHook)
{
int retKeyboard = UnhookWindowsHookEx(hKeyboardHook);
hKeyboardHook = 0;
if (retKeyboard == 0 && ThrowExceptions)
{
int errorCode = Marshal.GetLastWin32Error();
throw new Win32Exception(errorCode);
}
}
}
private int MouseHookProc(int nCode, int wParam, IntPtr lParam)
{
if ((nCode >= 0) && (OnMouseActivity != null))
{
MouseLLHookStruct mouseHookStruct = (MouseLLHookStruct)Marshal.PtrToStructure(lParam, typeof(MouseLLHookStruct));
MouseButtons button = MouseButtons.None;
short mouseDelta = 0;
switch (wParam)
{
case WM_LBUTTONDOWN:
button = MouseButtons.Left;
break;
case WM_LBUTTONUP:
button = MouseButtons.Right;
break;
case WM_MOUSEWHEEL:
mouseDelta = (short)((mouseHookStruct.mouseData >> 16) & 0xffff);
break;
}
int clickCount = 0;
if (button != MouseButtons.None)
if (wParam == WM_LBUTTONDBLCLK || wParam == WM_RBUTTONDBLCLK) clickCount = 2;
else clickCount = 1;
MouseEventArgs e = new MouseEventArgs(
button,
clickCount,
mouseHookStruct.pt.x,
mouseHookStruct.pt.y,
mouseDelta);
OnMouseActivity(this, e);
}
return CallNextHookEx(hMouseHook, nCode, wParam, lParam);
}
private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)
{
bool handled = false;
if ((nCode >= 0) && (KeyDown != null || KeyUp != null || KeyPress != null))
{
KeyboardHookStruct MyKeyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct));
if (KeyDown != null && (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN))
{
Keys keyData = (Keys)MyKeyboardHookStruct.vkCode;
KeyEventArgs e = new KeyEventArgs(keyData);
KeyDown(this, e);
handled = handled || e.Handled;
}
if (KeyPress != null && wParam == WM_KEYDOWN)
{
bool isDownShift = ((GetKeyState(VK_SHIFT) & 0x80) == 0x80 ? true : false);
bool isDownCapslock = (GetKeyState(VK_CAPITAL) != 0 ? true : false);
byte[] keyState = new byte[256];
GetKeyboardState(keyState);
byte[] inBuffer = new byte[2];
if (ToAscii(MyKeyboardHookStruct.vkCode,
MyKeyboardHookStruct.scanCode,
keyState,
inBuffer,
MyKeyboardHookStruct.flags) == 1)
{
char key = (char)inBuffer[0];
if ((isDownCapslock ^ isDownShift) && Char.IsLetter(key)) key = Char.ToUpper(key);
KeyPressEventArgs e = new KeyPressEventArgs(key);
KeyPress(this, e);
handled = handled || e.Handled;
}
}
if (KeyUp != null && (wParam == WM_KEYUP || wParam == WM_SYSKEYUP))
{
Keys keyData = (Keys)MyKeyboardHookStruct.vkCode;
KeyEventArgs e = new KeyEventArgs(keyData);
KeyUp(this, e);
handled = handled || e.Handled;
}
}
if (handled)
return 1;
else
return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam);
}
}
}

@ -0,0 +1,34 @@
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Parameters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HuizhongLibrary
{
public class AesGcm
{
private static string ALGORITHM = "AES/GCM/NoPadding";
private static int TAG_LENGTH_BIT = 128;
private static int NONCE_LENGTH_BYTE = 12;
public static string AesGcmDecrypt(string key,string associatedData, string nonce, string ciphertext)
{
GcmBlockCipher gcmBlockCipher = new GcmBlockCipher(new AesEngine());
AeadParameters aeadParameters = new AeadParameters(
new KeyParameter(Encoding.UTF8.GetBytes(key)),
128,
Encoding.UTF8.GetBytes(nonce),
Encoding.UTF8.GetBytes(associatedData));
gcmBlockCipher.Init(false, aeadParameters);
byte[] data = Convert.FromBase64String(ciphertext);
byte[] plaintext = new byte[gcmBlockCipher.GetOutputSize(data.Length)];
int length = gcmBlockCipher.ProcessBytes(data, 0, data.Length, plaintext, 0);
gcmBlockCipher.DoFinal(plaintext, length);
return Encoding.UTF8.GetString(plaintext);
}
}
}

File diff suppressed because it is too large Load Diff

@ -0,0 +1,590 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using HuizhongLibrary.Log;
using DirectShowLib;
using System.Drawing;
using System.Drawing.Imaging;
namespace HuizhongLibrary
{
public class Camera : ISampleGrabberCB, IDisposable
{
#region Member variables
/// <summary> graph builder interface. </summary>
private IFilterGraph2 m_FilterGraph = null;
private IMediaControl m_mediaCtrl = null;
/// <summary> so we can wait for the async job to finish </summary>
private ManualResetEvent m_PictureReady = null;
/// <summary> Set by async routine when it captures an image </summary>
private volatile bool m_bGotOne = false;
/// <summary> Indicates the status of the graph </summary>
private bool m_bRunning = false;
/// <summary> Dimensions of the image, calculated once in constructor. </summary>
private IntPtr m_handle = IntPtr.Zero;
private int m_videoWidth;
private int m_videoHeight;
private int m_stride;
public int m_Dropped = 0;
#endregion
#region API
[DllImport("Kernel32.dll", EntryPoint = "RtlMoveMemory")]
private static extern void CopyMemory(IntPtr Destination, IntPtr Source, int Length);
#endregion
/// <summary> Use capture device zero, default frame rate and size</summary>
public Camera()
{
_Capture(0, 0, 0, 0);
}
/// <summary> Use specified capture device, default frame rate and size</summary>
public Camera(int iDeviceNum)
{
_Capture(iDeviceNum, 0, 0, 0);
}
/// <summary> Use specified capture device, specified frame rate and default size</summary>
public Camera(int iDeviceNum, int iFrameRate)
{
_Capture(iDeviceNum, iFrameRate, 0, 0);
}
/// <summary> Use specified capture device, specified frame rate and size</summary>
public Camera(int iDeviceNum, int iFrameRate, int iWidth, int iHeight)
{
_Capture(iDeviceNum, iFrameRate, iWidth, iHeight);
}
#region 初始化线程
private AutoResetEvent AutoReset = new AutoResetEvent(false);
Thread CameraThread = null;
public bool IsScreenImage = false;
public event Action<Bitmap> OutImage;
public void StartScreenImage()
{
CameraThread = new Thread(ScreenImage);
CameraThread.Start();
}
#endregion
#region 停止录像
public void StopScreenImage()
{
IsScreenImage = false;
if (CameraThread == null) return;
while (CameraThread.IsAlive)
{
System.Threading.Thread.Sleep(500);
}
//System.Threading.Thread.Sleep(1000);
//CameraThread.Abort();
//CameraThread = null;
}
#endregion
#region 录像
void ScreenImage()
{
IsScreenImage = true;
while (this.IsScreenImage)
{
try
{
Bitmap image = null;
IntPtr ip = IntPtr.Zero;
ip = this.GetBitMap();
image = new Bitmap(this.Width, this.Height, this.Stride, PixelFormat.Format24bppRgb, ip);
//旋转
image.RotateFlip(RotateFlipType.RotateNoneFlipY);
//释放指针ip
Marshal.FreeCoTaskMem(ip);
//回收垃圾
GC.Collect();
//不安全的刷新
if (this.OutImage != null) this.OutImage(image);
AutoReset.WaitOne(100);
}
catch (Exception ex)
{
ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message);
}
}
}
#endregion
#region 截图
public Bitmap GrabImage()
{
try
{
StopScreenImage();
Bitmap image = null;
IntPtr ip = IntPtr.Zero;
ip = this.GetBitMap();
image = new Bitmap(this.Width, this.Height, this.Stride, PixelFormat.Format24bppRgb, ip);
//旋转
image.RotateFlip(RotateFlipType.RotateNoneFlipY);
//释放指针ip
Marshal.FreeCoTaskMem(ip);
//回收垃圾
GC.Collect();
return image;
}
catch (Exception ex)
{
ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message);
}
return null;
}
#endregion
#region 截图
public void GrabImage(string filePath)
{
try
{
StopScreenImage();
Bitmap image = null;
IntPtr ip = IntPtr.Zero;
ip = this.GetBitMap();
image = new Bitmap(this.Width, this.Height, this.Stride, PixelFormat.Format24bppRgb, ip);
//旋转
image.RotateFlip(RotateFlipType.RotateNoneFlipY);
//释放指针ip
Marshal.FreeCoTaskMem(ip);
//回收垃圾
GC.Collect();
image.Save(filePath, ImageFormat.Jpeg);
StartScreenImage();
}
catch (Exception ex)
{
ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message);
}
}
#endregion
#region 截图并转成数组
public byte[] GrabImageToByte()
{
try
{
StopScreenImage();
Bitmap image = null;
IntPtr ip = IntPtr.Zero;
ip = this.GetBitMap();
image = new Bitmap(this.Width, this.Height, this.Stride, PixelFormat.Format24bppRgb, ip);
//旋转
image.RotateFlip(RotateFlipType.RotateNoneFlipY);
//释放指针ip
Marshal.FreeCoTaskMem(ip);
//回收垃圾
GC.Collect();
byte[] bytes=CustomIO.GetPhoto(image);
image.Dispose();
image = null;
StartScreenImage();
return bytes;
}
catch (Exception ex)
{
ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message);
}
return null;
}
#endregion
#region 读取所有摄像头设备
public static DsDevice[] GetDevices()
{
DsDevice[] capDevices = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice);
return capDevices;
}
#endregion
#region 是否存在摄像头
public static bool IsCamera()
{
DsDevice[] capDevices = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice);
if (capDevices.Length == 0) return false;
return true;
}
#endregion
/// <summary> release everything. </summary>
public void Dispose()
{
this.m_bRunning = false;
CloseInterfaces();
if (m_PictureReady != null)
{
m_PictureReady.Close();
m_PictureReady = null;
}
}
// Destructor
~Camera()
{
Dispose();
}
public int Width
{
get
{
return m_videoWidth;
}
}
public int Height
{
get
{
return m_videoHeight;
}
}
public int Stride
{
get
{
return m_stride;
}
}
/// <summary> capture the next image </summary>
public IntPtr GetBitMap()
{
m_handle = Marshal.AllocCoTaskMem(m_stride * m_videoHeight);
try
{
// get ready to wait for new image
m_PictureReady.Reset();
m_bGotOne = false;
// If the graph hasn't been started, start it.
Start();
// Start waiting
if (!m_PictureReady.WaitOne(5000, false))
{
throw new Exception("Timeout waiting to get picture");
}
}
catch
{
Marshal.FreeCoTaskMem(m_handle);
throw;
}
return m_handle;
}
// Start the capture graph
public void Start()
{
if (!m_bRunning)
{
int hr = m_mediaCtrl.Run();
DsError.ThrowExceptionForHR(hr);
m_bRunning = true;
}
}
// Pause the capture graph.
// Running the graph takes up a lot of resources. Pause it when it
// isn't needed.
public void Pause()
{
if (m_bRunning)
{
int hr = m_mediaCtrl.Pause();
DsError.ThrowExceptionForHR(hr);
m_bRunning = false;
}
}
// Internal capture
private void _Capture(int iDeviceNum, int iFrameRate, int iWidth, int iHeight)
{
DsDevice[] capDevices;
// Get the collection of video devices
capDevices = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice);
if (iDeviceNum + 1 > capDevices.Length)
{
throw new Exception("No video capture devices found at that index!");
}
try
{
// Set up the capture graph
SetupGraph(capDevices[iDeviceNum], iFrameRate, iWidth, iHeight);
// tell the callback to ignore new images
m_PictureReady = new ManualResetEvent(false);
m_bGotOne = true;
m_bRunning = false;
}
catch
{
Dispose();
throw;
}
}
/// <summary> build the capture graph for grabber. </summary>
private void SetupGraph(DsDevice dev, int iFrameRate, int iWidth, int iHeight)
{
int hr;
ISampleGrabber sampGrabber = null;
IBaseFilter capFilter = null;
ICaptureGraphBuilder2 capGraph = null;
// Get the graphbuilder object
m_FilterGraph = (IFilterGraph2)new FilterGraph();
m_mediaCtrl = m_FilterGraph as IMediaControl;
try
{
// Get the ICaptureGraphBuilder2
capGraph = (ICaptureGraphBuilder2)new CaptureGraphBuilder2();
// Get the SampleGrabber interface
sampGrabber = (ISampleGrabber)new SampleGrabber();
// Start building the graph
hr = capGraph.SetFiltergraph(m_FilterGraph);
DsError.ThrowExceptionForHR(hr);
// Add the video device
hr = m_FilterGraph.AddSourceFilterForMoniker(dev.Mon, null, "Video input", out capFilter);
DsError.ThrowExceptionForHR(hr);
IBaseFilter baseGrabFlt = (IBaseFilter)sampGrabber;
ConfigureSampleGrabber(sampGrabber);
// Add the frame grabber to the graph
hr = m_FilterGraph.AddFilter(baseGrabFlt, "Ds.NET Grabber");
DsError.ThrowExceptionForHR(hr);
// If any of the default config items are set
if (iFrameRate + iHeight + iWidth > 0)
{
SetConfigParms(capGraph, capFilter, iFrameRate, iWidth, iHeight);
}
hr = capGraph.RenderStream(PinCategory.Capture, MediaType.Video, capFilter, null, baseGrabFlt);
DsError.ThrowExceptionForHR(hr);
SaveSizeInfo(sampGrabber);
}
finally
{
if (capFilter != null)
{
Marshal.ReleaseComObject(capFilter);
capFilter = null;
}
if (sampGrabber != null)
{
Marshal.ReleaseComObject(sampGrabber);
sampGrabber = null;
}
if (capGraph != null)
{
Marshal.ReleaseComObject(capGraph);
capGraph = null;
}
}
}
private void SaveSizeInfo(ISampleGrabber sampGrabber)
{
int hr;
// Get the media type from the SampleGrabber
AMMediaType media = new AMMediaType();
hr = sampGrabber.GetConnectedMediaType(media);
DsError.ThrowExceptionForHR(hr);
if ((media.formatType != FormatType.VideoInfo) || (media.formatPtr == IntPtr.Zero))
{
throw new NotSupportedException("Unknown Grabber Media Format");
}
// Grab the size info
VideoInfoHeader videoInfoHeader = (VideoInfoHeader)Marshal.PtrToStructure(media.formatPtr, typeof(VideoInfoHeader));
m_videoWidth = videoInfoHeader.BmiHeader.Width;
m_videoHeight = videoInfoHeader.BmiHeader.Height;
m_stride = m_videoWidth * (videoInfoHeader.BmiHeader.BitCount / 8);
DsUtils.FreeAMMediaType(media);
media = null;
}
private void ConfigureSampleGrabber(ISampleGrabber sampGrabber)
{
AMMediaType media;
int hr;
// Set the media type to Video/RBG24
media = new AMMediaType();
media.majorType = MediaType.Video;
media.subType = MediaSubType.RGB24;
media.formatType = FormatType.VideoInfo;
hr = sampGrabber.SetMediaType(media);
DsError.ThrowExceptionForHR(hr);
DsUtils.FreeAMMediaType(media);
media = null;
// Configure the samplegrabber
hr = sampGrabber.SetCallback(this, 1);
DsError.ThrowExceptionForHR(hr);
}
// Set the Framerate, and video size
private void SetConfigParms(ICaptureGraphBuilder2 capGraph, IBaseFilter capFilter, int iFrameRate, int iWidth, int iHeight)
{
int hr;
object o;
AMMediaType media;
// Find the stream config interface
hr = capGraph.FindInterface(
PinCategory.Capture, MediaType.Video, capFilter, typeof(IAMStreamConfig).GUID, out o);
IAMStreamConfig videoStreamConfig = o as IAMStreamConfig;
if (videoStreamConfig == null)
{
throw new Exception("Failed to get IAMStreamConfig");
}
// Get the existing format block
hr = videoStreamConfig.GetFormat(out media);
DsError.ThrowExceptionForHR(hr);
// copy out the videoinfoheader
VideoInfoHeader v = new VideoInfoHeader();
Marshal.PtrToStructure(media.formatPtr, v);
// if overriding the framerate, set the frame rate
if (iFrameRate > 0)
{
v.AvgTimePerFrame = 10000000 / iFrameRate;
}
// if overriding the width, set the width
if (iWidth > 0)
{
v.BmiHeader.Width = iWidth;
}
// if overriding the Height, set the Height
if (iHeight > 0)
{
v.BmiHeader.Height = iHeight;
}
// Copy the media structure back
Marshal.StructureToPtr(v, media.formatPtr, false);
// Set the new format
hr = videoStreamConfig.SetFormat(media);
DsError.ThrowExceptionForHR(hr);
DsUtils.FreeAMMediaType(media);
media = null;
}
/// <summary> Shut down capture </summary>
private void CloseInterfaces()
{
int hr;
try
{
if (m_mediaCtrl != null)
{
// Stop the graph
hr = m_mediaCtrl.Stop();
m_bRunning = false;
}
}
catch (Exception ex)
{
ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message);
}
if (m_FilterGraph != null)
{
Marshal.ReleaseComObject(m_FilterGraph);
m_FilterGraph = null;
}
}
/// <summary> sample callback, NOT USED. </summary>
int ISampleGrabberCB.SampleCB(double SampleTime, IMediaSample pSample)
{
if (!m_bGotOne)
{
// Set bGotOne to prevent further calls until we
// request a new bitmap.
m_bGotOne = true;
IntPtr pBuffer;
pSample.GetPointer(out pBuffer);
int iBufferLen = pSample.GetSize();
if (pSample.GetSize() > m_stride * m_videoHeight)
{
throw new Exception("Buffer is wrong size");
}
CopyMemory(m_handle, pBuffer, m_stride * m_videoHeight);
// Picture is ready.
m_PictureReady.Set();
}
Marshal.ReleaseComObject(pSample);
return 0;
}
/// <summary> buffer callback, COULD BE FROM FOREIGN THREAD. </summary>
int ISampleGrabberCB.BufferCB(double SampleTime, IntPtr pBuffer, int BufferLen)
{
if (!m_bGotOne)
{
// The buffer should be long enought
if (BufferLen <= m_stride * m_videoHeight)
{
// Copy the frame to the buffer
CopyMemory(m_handle, pBuffer, m_stride * m_videoHeight);
}
else
{
throw new Exception("Buffer is wrong size");
}
// Set bGotOne to prevent further calls until we
// request a new bitmap.
m_bGotOne = true;
// Picture is ready.
m_PictureReady.Set();
}
else
{
m_Dropped++;
}
return 0;
}
}
}

@ -0,0 +1,170 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace HuizhongLibrary.Common.Configuration
{
public class Config
{
private string m_Key;
/// <summary>
/// 键
/// </summary>
public string Key
{
get { return m_Key; }
set { m_Key = value; }
}
private string m_Value;
/// <summary>
/// 值
/// </summary>
public string Value
{
get { return m_Value; }
set { m_Value = value; }
}
private string m_Namespace;
/// <summary>
/// 命名空间
/// </summary>
public string Namespace
{
get { return m_Namespace; }
set { m_Namespace = value; }
}
}
public class ConfigCollection:IList<Config>
{
public List<Config> items = new List<Config>();
#region IList<Config> 成员
public int IndexOf(Config item)
{
return items.IndexOf(item);
}
public void Insert(int index, Config item)
{
items.Insert(index, item);
}
public void RemoveAt(int index)
{
items.RemoveAt(index);
}
public Config this[int index]
{
get
{
return items[index];
}
set
{
items[index]=value;
}
}
public Config this[string key]
{
get
{
foreach (Config cf in this.items)
{
if (cf.Key == key) return cf;
}
return null;
}
}
public string getValue(string key)
{
foreach (Config cf in this.items)
{
if (cf.Key == key) return cf.Value;
}
return "";
}
public string getNameSpace(string key)
{
foreach (Config cf in this.items)
{
if (cf.Key == key) return cf.Namespace;
}
return "";
}
public bool ContainsKey(string key)
{
foreach (Config cf in this.items)
{
if (cf.Key == key) return true;
}
return false;
}
#endregion
#region ICollection<Config> 成员
public void Add(Config item)
{
items.Add(item);
}
public void Clear()
{
items.Clear();
}
public bool Contains(Config item)
{
return items.Contains(item);
}
public void CopyTo(Config[] array, int arrayIndex)
{
items.CopyTo(array, arrayIndex);
}
public int Count
{
get { return items.Count; }
}
public bool IsReadOnly
{
get { return true; }
}
public bool Remove(Config item)
{
return items.Remove(item);
}
#endregion
#region IEnumerable<Config> 成员
public IEnumerator<Config> GetEnumerator()
{
return items.GetEnumerator();
}
#endregion
#region IEnumerable 成员
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return items.GetEnumerator();
}
#endregion
}
}

@ -0,0 +1,555 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Data;
using System.Data.SqlClient;
using HuizhongLibrary.Data;
using HuizhongLibrary.Safety;
using System.Data.Common;
namespace HuizhongLibrary.Common.Configuration
{
public class ConfigurationSourceSection
{
#region 读取数据库连接
/// <summary>
/// 读取数据库连接
/// </summary>
/// <param name="AttributeName">属性名称</param>
public static void GetConnection(string AttributeName)
{ //读取属性值
string filePath = AppDomain.CurrentDomain.BaseDirectory + ConfigurationSourceSection.LoadXml_Attribute(AppDomain.CurrentDomain.BaseDirectory + "Setup.ini", "SetupPath");
if (filePath.Substring(filePath.Length - 1) != "/") filePath = AppDomain.CurrentDomain.BaseDirectory + ConfigurationSourceSection.LoadXml_Attribute(AppDomain.CurrentDomain.BaseDirectory + "Setup.ini", "SetupPath");
XmlDocument Document = new XmlDocument();
Document.Load(filePath);
XmlNodeList nodelist = Document.SelectNodes("child::configuration/appSettings/add");
Config cf =null;
foreach (XmlNode node in nodelist)
{
if (node.Attributes["key"].Value == AttributeName)
{
if (DataCache.ConfigCache.ContainsKey(AttributeName) == false)
{
cf = new Config();
DataCache.ConfigCache.Add(cf);
}
else
{
cf = DataCache.ConfigCache[AttributeName];
}
cf.Key = AttributeName;
try
{
var node2 = node.Attributes.GetNamedItem("NameSpace");
if (node2!=null) cf.Namespace = node.Attributes["NameSpace"].Value;
}
catch
{
cf.Namespace = "System.Data.SqlClient";
}
try
{
cf.Value = CryptoPrivate.Decryp(node.Attributes["value"].Value);
}
catch
{
cf.Value = node.Attributes["value"].Value;
}
}
}
}
#endregion
#region 读取数据库连接
/// <summary>
/// 读取数据库连接
/// </summary>
/// <param name="AttributeName">属性名称</param>
public static void GetConnection2(string AttributeName)
{ //读取属性值
string filePath = AppDomain.CurrentDomain.BaseDirectory + "Setup.ini";
XmlDocument Document = new XmlDocument();
Document.Load(filePath);
XmlNodeList nodelist = Document.SelectNodes("child::configuration/appSettings/add");
Config cf = null;
foreach (XmlNode node in nodelist)
{
if (node.Attributes["key"].Value == AttributeName)
{
if (DataCache.ConfigCache.ContainsKey(AttributeName) == false)
{
cf = new Config();
DataCache.ConfigCache.Add(cf);
}
else
{
cf = DataCache.ConfigCache[AttributeName];
}
cf.Key = AttributeName;
try
{
cf.Namespace = node.Attributes["NameSpace"].Value;
}
catch
{
cf.Namespace = "System.Data.SqlClient";
}
try
{
cf.Value = CryptoPrivate.Decryp(node.Attributes["value"].Value);
}
catch
{
cf.Value = node.Attributes["value"].Value;
}
}
}
}
#endregion
#region 读取XML配置文件-属性值
/// <summary>
/// 返回指点节点指点属性的值,AttributeName属性名称
/// </summary>
/// <param name="filePath">配置文件路径</param>
/// <param name="AttributeName">属性名称</param>
public static string LoadXml_Attribute(string filePath, string AttributeName)
{ //读取属性值
if (System.IO.File.Exists(filePath) == false) return "";
XmlDocument Document = new XmlDocument();
Document.Load(filePath);
XmlNodeList nodelist = Document.SelectNodes("child::configuration/appSettings/add");
foreach (XmlNode node in nodelist)
{
if (node.Attributes["key"].Value == AttributeName)
{
string KeyValue = "";
try
{
KeyValue = CryptoPrivate.Decryp(node.Attributes["value"].Value);
}
catch
{
KeyValue = node.Attributes["value"].Value;
}
return KeyValue;
}
}
return "";
}
#endregion
#region 保存XML配置文件
/// <summary>
///AttributeName属性名称,AttributeValue属性值
/// </summary>
/// <param name="AttributeName">属性名称</param>
/// <param name="AttributeValue">属性值</param>
/// <param name="IsEncrypt">是否加密</param>
public static void SaveXml_Attribute(string filePath, string AttributeName, string AttributeValue, bool IsEncrypt)
{
bool bk = true;
XmlDocument Document = new XmlDocument();
Document.Load(filePath);
//XmlNodeList nodelist = Document.GetElementsByTagName(NodeTypeName);
XmlNodeList nodelist = Document.SelectNodes("child::configuration/appSettings/add");
foreach (XmlNode node in nodelist)
{
if (node.Attributes["key"].Value == AttributeName)
{
if (IsEncrypt == true) { node.Attributes["value"].Value = CryptoPrivate.Encryp(AttributeValue); }
else { node.Attributes["value"].Value = AttributeValue; }
bk = false;
}
}
if (bk == true)
{
XmlElement Element = Document.CreateElement("add");
XmlAttribute Attrib = null;
Attrib = Document.CreateAttribute("key");
Attrib.Value = AttributeName;
Element.Attributes.Append(Attrib);
Attrib = Document.CreateAttribute("value");
if (IsEncrypt == true) { Attrib.Value = CryptoPrivate.Encryp(AttributeValue); }
else { Attrib.Value = AttributeValue; }
Element.Attributes.Append(Attrib);
nodelist = Document.SelectNodes("child::configuration/appSettings");
nodelist[0].AppendChild(Element);
}
Document.Save(filePath);
}
#endregion
#region 查询服务器上所有数据库
/// <summary>
///查询服务器上所有数据库
/// </summary>
public static DataTable getDataBase(string connectString)
{
// string dn="";
// if (userid != "") { dn = "data source=" + datasource + ";initial catalog=master;user id=" + userid + ";password=" + password; }
// else { dn = "data source=" + datasource + ";initial catalog=master;Integrated Security=True"; }
DataTable tb = new DataTable();
SqlConnection cn = new SqlConnection(connectString);
cn.Open();
cn.ChangeDatabase("master");
SqlCommand cmd = new SqlCommand("select name from sysdatabases order by name asc", cn);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(tb);
cn.Close();
return tb;
}
#endregion
#region 查询数据库中所有表名
/// <summary>
///查询数据库中所有表名
/// </summary>
public static DataTable getTables(string connectString)
{
DataTable tb = new DataTable();
SqlConnection cn = new SqlConnection(connectString);
cn.Open();
SqlCommand cmd = new SqlCommand("select * from [sysobjects] where xtype='u' order by name asc", cn);//and status>0
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(tb);
cn.Close();
return tb;
}
#endregion
#region 查询数据库中所有表名
/// <summary>
///查询数据库中所有表名
/// </summary>
public static DataTable getTables(string connectString,string DataName)
{
DataTable tb = new DataTable();
SqlConnection cn = new SqlConnection(connectString);
cn.Open();
if (DataName!="") cn.ChangeDatabase(DataName);
SqlCommand cmd = new SqlCommand("select * from [sysobjects] where xtype='u' order by name asc", cn);//and status>0
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(tb);
cn.Close();
return tb;
}
#endregion
#region 查询数据库中所有视图名
/// <summary>
///查询数据库中所有视图名
/// </summary>
public static DataTable getViews(string connectString, string DataName)
{
DataTable tb = new DataTable();
SqlConnection cn = new SqlConnection(connectString);
cn.Open();
cn.ChangeDatabase(DataName);
SqlCommand cmd = new SqlCommand("select v.[name] from sys.views as v, sys.schemas as s where v.schema_id = s.schema_id order by v.name", cn);//and status>0
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(tb);
cn.Close();
return tb;
}
#endregion
#region 检索列
public static DataTable getColumns(string connectString, string TableName)
{
DataTable tb = new DataTable(TableName);
SqlConnection cn = new SqlConnection(connectString);
if (cn.State == ConnectionState.Closed) { cn.Open(); }
int ver = Convert.ToInt32(cn.ServerVersion.Substring(0,2));
string tsql = @"
select ColumnRemark=d.value,ColumnName=a.name,Type=b.name,
ColumnType=case when b.name='varchar' or b.name='nvarchar' then b.name+'('+cast(a.Length as varchar(10))+')' when b.name='varchar' or b.name='decimal' then b.name+'('+cast(a.prec as varchar(10))+','+cast(a.xscale as varchar(10))+')' else cast(b.name as varchar(10))+'('+cast(a.Length as varchar(10))+')' end
from [sysobjects] c
inner join [syscolumns] a on c.id=a.id
inner join [systypes] b on b.xtype=a.xtype
left join [sysproperties] d on a.colid=d.smallid and a.id=d.id
where c.xtype='u' and c.name<>'dtproperties' and c.name=@TableName and b.name<>'sysname'
order by a.colorder
";
if (ver > 8)
{
tsql = @"
select a.ColumnName,ColumnType=replace(a.ColumnType,'(-1)','(MAX)'),a.ColumnRemark,a.Type
from (
select ColumnRemark=d.value,ColumnName=a.name,Type=b.name,
ColumnType=case when b.name='varchar' or b.name='nvarchar' then b.name+'('+cast(a.Length as varchar(10))+')' when b.name='varchar' or b.name='decimal' then b.name+'('+cast(a.prec as varchar(10))+','+cast(a.xscale as varchar(10))+')' else cast(b.name as varchar(10))+'('+cast(a.Length as varchar(10))+')' end,a.colorder
from [sysobjects] c
inner join [syscolumns] a on c.id=a.id
inner join [systypes] b on b.xtype=a.xtype
left join [sys].[extended_properties] d on a.colid=d.[minor_id] and a.id=d.major_id
where c.xtype='u' and c.name<>'dtproperties' and c.name=@TableName and b.name<>'sysname'
) a
order by a.colorder
";
}
//sql2005以上
/*
select ColumnRemark=d.value,ColumnName=a.name,Type=b.name,ColumnType=case when b.name='varchar' or b.name='nvarchar' then b.name+'('+cast(a.Length as varchar(10))+')' when b.name='varchar' or b.name='decimal' then b.name+'('+cast(a.prec as varchar(10))+','+cast(a.xscale as varchar(10))+')' else cast(b.name as varchar(10))+'('+cast(a.Length as varchar(10))+')' end from [sysobjects] c inner join [syscolumns] a on c.id=a.id inner join [systypes] b on b.xtype=a.xtype left join [sys].[extended_properties] d on a.colid=d.[minor_id] and a.id=d.major_id where c.xtype='u' and c.name<>'dtproperties' and c.name=@TableName and b.name<>'sysname' order by a.colorder
*/
SqlCommand cmd = new SqlCommand(tsql, cn);
cmd.Parameters.Add("@TableName", SqlDbType.VarChar).Value = TableName;
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(tb);
cn.Close();
return tb;
}
public static DataTable getColumns2(string connectString, string TableName)
{
DataTable tb = new DataTable(TableName);
SqlConnection cn = new SqlConnection(connectString);
if (cn.State == ConnectionState.Closed) { cn.Open(); }
int ver = Convert.ToInt32(cn.ServerVersion.Substring(0, 2));
string tsql = @"
select ColRemark=d.value,ColName=a.name,ColType=b.name,
ColumnType=case when b.name='varchar' or b.name='nvarchar' then b.name+'('+cast(a.Length as varchar(10))+')' when b.name='varchar' or b.name='decimal' then b.name+'('+cast(a.prec as varchar(10))+','+cast(a.xscale as varchar(10))+')' else cast(b.name as varchar(10))+'('+cast(a.Length as varchar(10))+')' end
from [sysobjects] c
inner join [syscolumns] a on c.id=a.id
inner join [systypes] b on b.xtype=a.xtype
left join [sysproperties] d on a.colid=d.smallid and a.id=d.id
where c.xtype='u' and c.name<>'dtproperties' and c.name=@TableName and b.name<>'sysname'
order by a.colorder
";
if (ver > 8)
{
tsql = @"
select a.ColName,ColumnType=replace(a.ColumnType,'(-1)','(MAX)'),a.ColRemark,a.ColType
from (
select ColRemark=d.value,ColName=a.name,ColType=b.name,
ColumnType=case when b.name='varchar' or b.name='nvarchar' then b.name+'('+cast(a.Length as varchar(10))+')' when b.name='varchar' or b.name='decimal' then b.name+'('+cast(a.prec as varchar(10))+','+cast(a.xscale as varchar(10))+')' else cast(b.name as varchar(10))+'('+cast(a.Length as varchar(10))+')' end,a.colorder
from [sysobjects] c
inner join [syscolumns] a on c.id=a.id
inner join [systypes] b on b.xtype=a.xtype
left join [sys].[extended_properties] d on a.colid=d.[minor_id] and a.id=d.major_id
where c.xtype='u' and c.name<>'dtproperties' and c.name=@TableName and b.name<>'sysname'
) a
order by a.colorder
";
}
//sql2005以上
/*
select ColumnRemark=d.value,ColumnName=a.name,Type=b.name,ColumnType=case when b.name='varchar' or b.name='nvarchar' then b.name+'('+cast(a.Length as varchar(10))+')' when b.name='varchar' or b.name='decimal' then b.name+'('+cast(a.prec as varchar(10))+','+cast(a.xscale as varchar(10))+')' else cast(b.name as varchar(10))+'('+cast(a.Length as varchar(10))+')' end from [sysobjects] c inner join [syscolumns] a on c.id=a.id inner join [systypes] b on b.xtype=a.xtype left join [sys].[extended_properties] d on a.colid=d.[minor_id] and a.id=d.major_id where c.xtype='u' and c.name<>'dtproperties' and c.name=@TableName and b.name<>'sysname' order by a.colorder
*/
SqlCommand cmd = new SqlCommand(tsql, cn);
cmd.Parameters.Add("@TableName", SqlDbType.VarChar).Value = TableName;
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(tb);
cn.Close();
return tb;
}
public static DataTable getColumns(string connectString, string DataName, string TableName)
{
DataTable tb = new DataTable(TableName);
SqlConnection cn = new SqlConnection(connectString);
if (cn.State == ConnectionState.Closed) { cn.Open(); }
cn.ChangeDatabase(DataName);
int ver = Convert.ToInt32(cn.ServerVersion.Substring(0, 2));
string tsql = @"
select ColumnRemark=d.value,ColumnName=a.name,Type=b.name,
ColumnType=case when b.name='varchar' or b.name='nvarchar' then b.name+'('+cast(a.Length as varchar(10))+')' when b.name='varchar' or b.name='decimal' then b.name+'('+cast(a.prec as varchar(10))+','+cast(a.xscale as varchar(10))+')' else cast(b.name as varchar(10))+'('+cast(a.Length as varchar(10))+')' end
from [sysobjects] c
inner join [syscolumns] a on c.id=a.id
inner join [systypes] b on b.xtype=a.xtype
left join [sysproperties] d on a.colid=d.smallid and a.id=d.id
where c.xtype='u' and c.name<>'dtproperties' and c.name=@TableName and b.name<>'sysname'
order by a.colorder
";
if (ver > 8)
{
tsql = @"
select a.ColumnName,ColumnType=replace(a.ColumnType,'(-1)','(MAX)'),a.ColumnRemark,a.Type
from (
select ColumnRemark=d.value,ColumnName=a.name,Type=b.name,
ColumnType=case when b.name='varchar' or b.name='nvarchar' then b.name+'('+cast(a.Length as varchar(10))+')' when b.name='varchar' or b.name='decimal' then b.name+'('+cast(a.prec as varchar(10))+','+cast(a.xscale as varchar(10))+')' else cast(b.name as varchar(10))+'('+cast(a.Length as varchar(10))+')' end,a.colorder
from [sysobjects] c
inner join [syscolumns] a on c.id=a.id
inner join [systypes] b on b.xtype=a.xtype
left join [sys].[extended_properties] d on a.colid=d.[minor_id] and a.id=d.major_id
where c.xtype='u' and c.name<>'dtproperties' and c.name=@TableName and b.name<>'sysname'
) a
order by a.colorder
";
}
//sql2005以上
/*
select ColumnRemark=d.value,ColumnName=a.name,Type=b.name,ColumnType=case when b.name='varchar' or b.name='nvarchar' then b.name+'('+cast(a.Length as varchar(10))+')' when b.name='varchar' or b.name='decimal' then b.name+'('+cast(a.prec as varchar(10))+','+cast(a.xscale as varchar(10))+')' else cast(b.name as varchar(10))+'('+cast(a.Length as varchar(10))+')' end from [sysobjects] c inner join [syscolumns] a on c.id=a.id inner join [systypes] b on b.xtype=a.xtype left join [sys].[extended_properties] d on a.colid=d.[minor_id] and a.id=d.major_id where c.xtype='u' and c.name<>'dtproperties' and c.name=@TableName and b.name<>'sysname' order by a.colorder
*/
SqlCommand cmd = new SqlCommand(tsql, cn);
cmd.Parameters.Add("@TableName", SqlDbType.VarChar).Value = TableName;
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(tb);
cn.Close();
return tb;
}
#endregion
#region 判断列是否存在
public static int CheckColumnName(string connectString,string TableName, string ColName)
{
string tsql = @"
select name=case when b.name='varchar' or b.name='nvarchar' or b.name='decimal' then b.name+'('+cast(a.prec as varchar(10))+')' when b.name='decimal' then b.name+'('+cast(a.prec as varchar(10))+','+cast(a.xscale as varchar(10))+')' else cast(b.name as varchar(50)) end from syscolumns a
inner join [systypes] b on a.xtype=b.xtype
where a.id=object_id('" + TableName + @"') and a.name='" + ColName + @"'
";
Database db = new Database(connectString);
db.IsCheckKeyword = false;
DbCommand cmd = db.GetSqlStringCommand(tsql);
string a = Convert.ToString(db.ExecuteScalar(cmd));
if (string.IsNullOrEmpty(a) == true) return 0; //不存在
return 1; //存在
}
#endregion
#region 判断列是否存在
public static int CheckColumnName(string TableName, string ColName)
{
string tsql = @"
select name=case when b.name='varchar' or b.name='nvarchar' or b.name='decimal' then b.name+'('+cast(a.prec as varchar(10))+')' when b.name='decimal' then b.name+'('+cast(a.prec as varchar(10))+','+cast(a.xscale as varchar(10))+')' else cast(b.name as varchar(50)) end from syscolumns a
inner join [systypes] b on a.xtype=b.xtype
where a.id=object_id('" + TableName + @"') and a.name='" + ColName + @"'
";
Database db = DatabaseFactory.CreateDatabase();
db.IsCheckKeyword = false;
DbCommand cmd = db.GetSqlStringCommand(tsql);
string a = Convert.ToString(db.ExecuteScalar(cmd));
if (string.IsNullOrEmpty(a) == true) return 0; //不存在
return 1; //存在
}
#endregion
#region 执行SQL语句
public static void ExecuteNonQuery(string tsql)
{
if (string.IsNullOrEmpty(tsql) == true) return;
Database db = DatabaseFactory.CreateDatabase();
db.IsCheckKeyword = false;
DbCommand cmd = db.GetSqlStringCommand(tsql);
db.ExecuteNonQuery(cmd);
}
#endregion
#region 获取数据库名
public static string GetDataBaseName(string connectString)
{
SqlConnection cn = new SqlConnection(connectString);
return cn.Database;
}
#endregion
#region 表去除自增列
public static void Set_Table_AutoIncrement_ON(string tbName)
{
if (string.IsNullOrEmpty(tbName) == true) return;
string tsql = "SET IDENTITY_INSERT ["+ tbName + "] ON";
Database db = DatabaseFactory.CreateDatabase();
DbCommand cmd = db.GetSqlStringCommand(tsql);
db.ExecuteNonQuery(cmd);
}
#endregion
#region 表恢复自增列
public static void Set_Table_AutoIncrement_OFF(string tbName)
{
if (string.IsNullOrEmpty(tbName) == true) return;
string tsql = "SET IDENTITY_INSERT [" + tbName + "] OFF";
Database db = DatabaseFactory.CreateDatabase();
DbCommand cmd = db.GetSqlStringCommand(tsql);
db.ExecuteNonQuery(cmd);
}
#endregion
#region "读取XML配置文件-属性值"
/// <summary>
/// 返回指点节点指点属性的值,AttributeName属性名称
/// </summary>
/// <param name="filePath">配置文件路径</param>
/// <param name="AttributeName">属性名称</param>
public static string LoadXml_Attribute(string filePath, string AttributeName, string NameSpace)
{ //读取属性值
if (System.IO.File.Exists(filePath) == false) return "";
XmlDocument Document = new XmlDocument();
Document.Load(filePath);
XmlNodeList nodelist = Document.SelectNodes("child::configuration/appSettings/add");
foreach (XmlNode node in nodelist)
{
if (node.Attributes["key"].Value == AttributeName && node.Attributes["NameSpace"].Value == NameSpace)
{
string KeyValue = "";
try
{
KeyValue = CryptoPrivate.Decryp(node.Attributes["value"].Value);
}
catch
{
KeyValue = node.Attributes["value"].Value;
}
return KeyValue;
}
}
return "";
}
#endregion
#region "保存XML配置文件"
/// <summary>
///AttributeName属性名称,AttributeValue属性值
/// </summary>
/// <param name="AttributeName">属性名称</param>
/// <param name="AttributeValue">属性值</param>
/// <param name="IsEncrypt">是否加密</param>
public static void SaveXml_Attribute(string filePath, string AttributeName, string AttributeValue, string NameSpace, bool IsEncrypt)
{
bool bk = true;
XmlDocument Document = new XmlDocument();
Document.Load(filePath);
//XmlNodeList nodelist = Document.GetElementsByTagName(NodeTypeName);
XmlNodeList nodelist = Document.SelectNodes("child::configuration/appSettings/add");
foreach (XmlNode node in nodelist)
{
if (node.Attributes["NameSpace"] == null)
{
node.Attributes.Append(Document.CreateAttribute("NameSpace"));
}
if (node.Attributes["key"].Value == AttributeName && node.Attributes["NameSpace"].Value == NameSpace)
{
if (IsEncrypt == true) { node.Attributes["value"].Value = CryptoPrivate.Encryp(AttributeValue); }
else { node.Attributes["value"].Value = AttributeValue; }
bk = false;
}
}
if (bk == true)
{
XmlElement Element = Document.CreateElement("add");
XmlAttribute Attrib = null;
Attrib = Document.CreateAttribute("key");
Attrib.Value = AttributeName;
Element.Attributes.Append(Attrib);
Attrib = Document.CreateAttribute("value");
if (IsEncrypt == true) { Attrib.Value = CryptoPrivate.Encryp(AttributeValue); }
else { Attrib.Value = AttributeValue; }
Element.Attributes.Append(Attrib);
Attrib = Document.CreateAttribute("NameSpace");
Attrib.Value = NameSpace;
Element.Attributes.Append(Attrib);
nodelist[0].ParentNode.AppendChild(Element);
}
Document.Save(filePath);
}
#endregion
}
}

File diff suppressed because it is too large Load Diff

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Text;
using HuizhongLibrary.Common.Configuration;
namespace HuizhongLibrary.Data
{
public class DataCache
{
public static ConfigCollection ConfigCache = new ConfigCollection();
public static Dictionary<string, string> DataConnection = new Dictionary<string, string>();
public static int ConnectNumber = 0;
public static int MaxConnectNumber = 0;
}
}

@ -0,0 +1,316 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace HuizhongLibrary
{
public class DataConvert
{
public static DateTime? ToDateTime(object val)
{
string value=Convert.ToString(val);
if (value == null || value == "") return null;
DateTime? dt = null;
try { dt = Convert.ToDateTime(value); }
catch { return null; }
return dt;
}
public static Int32? ToInt32(object val)
{
string value = Convert.ToString(val);
if (value == null || value == "") return null;
Int32? dt = null;
try { dt = Convert.ToInt32(value); }
catch { return null; }
return dt;
}
public static Decimal? ToDecimal(object val)
{
string value = Convert.ToString(val);
if (value == null || value == "") return null;
Decimal? dt = null;
try { dt = Convert.ToDecimal(value); }
catch { return null; }
return dt;
}
public static Double? ToDouble(object val)
{
string value = Convert.ToString(val);
if (value == null || value == "") return null;
Double? dt = null;
try { dt = Convert.ToDouble(value); }
catch { return null; }
return dt;
}
public static Single? ToSingle(object val)
{
string value = Convert.ToString(val);
if (value == null || value == "") return null;
Single? dt = null;
try { dt = Convert.ToSingle(value); }
catch { return null; }
return dt;
}
public static Int16? ToInt16(object val)
{
string value = Convert.ToString(val);
if (value == null || value == "") return null;
Int16? dt = null;
try { dt = Convert.ToInt16(value); }
catch { return null; }
return dt;
}
public static String ToString(object val)
{
string value = Convert.ToString(val);
if (value == null || value == "") return "";
return value.Trim();
}
#region 过滤网页标签
public static String CleanHTMLTag(string htmlStream)
{
if (!string.IsNullOrEmpty(htmlStream))
{
/*
* HTMLUnicodeHash
*/
//先单独测试,成功后,再把所有模式合并
//注:这两个必须单独处理
//去掉嵌套了HTML标记的JavaScript:(<script)[\\s\\S]*(</script>)
//去掉css标记:(<style)[\\s\\S]*(</style>)
//去掉css标记:\\..*\\{[\\s\\S]*\\}
htmlStream = Regex.Replace(htmlStream, "(<script)[\\s\\S]*?(</script>)|(<style)[\\s\\S]*?(</style>)", " ", RegexOptions.IgnoreCase);
//htmlStream = RemoveTag(htmlStream, "script");
//htmlStream = RemoveTag(htmlStream, "style");
//去掉普通HTML标记:<[^>]+>
//替换空格:&nbsp;|&amp;|&shy;|&#160;|&#173;
htmlStream = Regex.Replace(htmlStream, "<[^>]+>|&nbsp;|&amp;|&shy;|&#160;|&#173;|&bull;|&lt;|&gt;", " ", RegexOptions.IgnoreCase);
//htmlStream = RemoveTag(htmlStream);
//替换左尖括号
//htmlStream = Regex.Replace(htmlStream, "&lt;", "<");
//替换右尖括号
//htmlStream = Regex.Replace(htmlStream, "&gt;", ">");
//替换空行
//htmlStream = Regex.Replace(htmlStream, "[\n|\r|\t]", " ");//[\n|\r][\t*| *]*[\n|\r]
htmlStream = Regex.Replace(htmlStream, "(\r\n[\r|\n|\t| ]*\r\n)|(\n[\r|\n|\t| ]*\n)", "\r\n");
htmlStream = Regex.Replace(htmlStream, "[\t| ]{1,}", " ");
}
return htmlStream.Trim();
}
#endregion
#region 过滤网页代码
public static String ToCodeString(string value)
{
if (value == null || value == "") return "";
Dictionary<string, string> where = new Dictionary<string, string>();
where.Add(@"<P .+?>", "");
where.Add(@"<P>", "");
where.Add(@"</P>", "");
where.Add(@"<SPAN .+?>", "");
where.Add(@"<SPAN>", "");
where.Add(@"</SPAN>", "");
where.Add(@"<STRONG>", "");
where.Add(@"</STRONG>", "");
where.Add(@"<U>", "");
where.Add(@"</U>", "");
where.Add(@"<EM>", "");
where.Add(@"</EM>", "");
where.Add(@"<o:p>", "");
where.Add(@"</o:p>", "");
where.Add(@"<FONT .+?>", "");
where.Add(@"</FONT>", "");
where.Add(@"<I .+?>", "");
where.Add(@"</I>", "");
where.Add(@"<B .+?>", "");
where.Add(@"</B>", "");
where.Add(@"<.xml:namespace .+?>", "");
where.Add(@"<st1:chmetcnv .+?>", "");
where.Add(@"</st1:chmetcnv>", "");
where.Add(@"\r", "");
where.Add(@"\n", "");
where.Add(@"\t", "");
where.Add(@"&nbsp;", " ");
where.Add(@"&lt;", "<");
where.Add(@"&gt;", ">");
foreach (string s in where.Keys)
{
value = Regex.Replace(value, s, where[s], RegexOptions.IgnoreCase);
}
return value;
}
#endregion
/// <summary>
/// 转换空值
/// </summary>
/// <param name="value">校验值</param>
/// <param name="defaultValue">如果是空值,那么用这个值替换</param>
/// <returns></returns>
public static object IsNull(object value, object defaultValue)
{
if (value != null && value != DBNull.Value) { return value; }
else { return defaultValue; }
}
public static string Format(object value, TypeCode type, string format)
{
if (value == null || value.ToString() == "" || value == DBNull.Value) return "";
if (format == null || format == "") return value.ToString();
switch (type)
{
case TypeCode.DateTime:
return Convert.ToDateTime(value).ToString(format);
case TypeCode.Decimal:
return Convert.ToDecimal(value).ToString(format);
case TypeCode.Double:
return Convert.ToDouble(value).ToString(format);
case TypeCode.Single:
return Convert.ToSingle(value).ToString(format);
default:
return "";
}
}
public static string Format(object value, string format)
{
if (value == null || value.ToString() == "" || value == DBNull.Value) return "";
if (format == null || format == "") return value.ToString();
try
{
return Convert.ToDecimal(value).ToString(format);
}
catch
{ }
try
{
return Convert.ToDateTime(value).ToString(format);
}
catch
{ }
return value.ToString();
}
/// <summary>
/// 十六进制转换到十进制
/// </summary>
/// <param name="hex"></param>
/// <returns></returns>
public static string Hex2Ten(string hex)
{
int ten = 0;
for (int i = 0, j = hex.Length - 1; i < hex.Length; i++)
{
ten += HexChar2Value(hex.Substring(i, 1)) * ((int)Math.Pow(16, j));
j--;
}
return ten.ToString();
}
public static int HexChar2Value(string hexChar)
{
switch (hexChar)
{
case "0":
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9":
return Convert.ToInt32(hexChar);
case "a":
case "A":
return 10;
case "b":
case "B":
return 11;
case "c":
case "C":
return 12;
case "d":
case "D":
return 13;
case "e":
case "E":
return 14;
case "f":
case "F":
return 15;
default:
return 0;
}
}
/// <summary>
/// 从十进制转换到十六进制
/// </summary>
/// <param name="ten"></param>
/// <returns></returns>
public static string Ten2Hex(string ten)
{
ulong tenValue = Convert.ToUInt64(ten);
ulong divValue, resValue;
string hex = "";
do
{
//divValue = (ulong)Math.Floor(tenValue / 16);
divValue = (ulong)Math.Floor((decimal)(tenValue / 16));
resValue = tenValue % 16;
hex = tenValue2Char(resValue) + hex;
tenValue = divValue;
}
while (tenValue >= 16);
if (tenValue != 0)
hex = tenValue2Char(tenValue) + hex;
return hex;
}
public static string tenValue2Char(ulong ten)
{
switch (ten)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
return ten.ToString();
case 10:
return "A";
case 11:
return "B";
case 12:
return "C";
case 13:
return "D";
case 14:
return "E";
case 15:
return "F";
default:
return "";
}
}
}
}

@ -0,0 +1,84 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
namespace HuizhongLibrary.Data
{
/// <summary>
/// 数据传送
/// </summary>
/// <typeparam name="T">泛型</typeparam>
public class DataEventArgs<T>:EventArgs
{
private int m_ID;
public int ID
{
get { return m_ID; }
set { m_ID = value; }
}
private string m_DeviceNo;
public string DeviceNo
{
get { return m_DeviceNo; }
set { m_DeviceNo = value; }
}
private string m_Name;
public string Name
{
get { return m_Name; }
set { m_Name = value; }
}
private T m_Data;
/// <summary>
/// 返回数据
/// </summary>
public T Data
{
get { return m_Data; }
set { m_Data = value; }
}
private string m_TypeName;
/// <summary>
/// 出错地点
/// </summary>
public string TypeName
{
get { return m_TypeName; }
set { m_TypeName = value; }
}
private string m_StackTrace;
/// <summary>
/// 出错对象信息
/// </summary>
public string StackTrace
{
get { return m_StackTrace; }
set { m_StackTrace = value; }
}
private string m_ErrorMsg;
/// <summary>
/// 出错信息
/// </summary>
public string ErrorMsg
{
get { return m_ErrorMsg; }
set { m_ErrorMsg = value; }
}
private bool m_IsError = false;
/// <summary>
/// 是否发生错误
/// </summary>
public bool IsError
{
get { return m_IsError; }
set { m_IsError = value; }
}
}
}

@ -0,0 +1,124 @@
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Globalization;
namespace HuizhongLibrary.Control
{
[DefaultProperty("Value"),
ToolboxData("<{0}:DataGridRadioButton runat=server></{0}:DataGridRadioButton>"),ParseChildren(true),
PersistChildren(false)]
public class DataGridRadioButton : RadioButton,INamingContainer,IPostBackDataHandler
{
public DataGridRadioButton() : base()
{
this.PreRender +=new EventHandler(DataGridRadioButton_PreRender);
}
private void DataGridRadioButton_PreRender(object sender, EventArgs e)
{
// Page.RegisterHiddenField("RadioButton_Checked", this.Checked.ToString());
// Page.RegisterStartupScript("jsSetRadioButton_Checked", "<script type=\"text/javascript\">document.getElementById("+this.ClientID+").Checked=" + this.Checked.ToString() + ";</script>");
// this.Attributes.Add("onclick","document.getElementById('RadioButton_Checked').value = this.Checked;");
// 将控件注册为要求在页回发至服务器时进行回发处理的控件
if (Page != null) Page.RegisterRequiresPostBack(this);
}
#region Properties
private string Value
{
get
{
string val = Attributes["value"];
if(val == null)
val = UniqueID;
else
val = UniqueID + "_" + val;
return val;
}
}
#endregion
#region Rendering
protected override void Render(HtmlTextWriter output)
{
RenderInputTag(output);
}
private void RenderInputTag(HtmlTextWriter htw)
{
htw.AddAttribute(HtmlTextWriterAttribute.Id, ClientID);
htw.AddAttribute(HtmlTextWriterAttribute.Type, "radio");
htw.AddAttribute(HtmlTextWriterAttribute.Name, GroupName);
htw.AddAttribute(HtmlTextWriterAttribute.Value, Value);
if(Checked)
htw.AddAttribute(HtmlTextWriterAttribute.Checked, "checked");
if(!Enabled)
htw.AddAttribute(HtmlTextWriterAttribute.Disabled, "disabled");
string onClick = Attributes["onclick"];
if(AutoPostBack)
{
if(onClick != null)
onClick = String.Empty;
onClick += Page.GetPostBackClientEvent(this, String.Empty);
htw.AddAttribute(HtmlTextWriterAttribute.Onclick, onClick);
htw.AddAttribute("language", "javascript");
}
else
{
if(onClick != null)
htw.AddAttribute(HtmlTextWriterAttribute.Onclick, onClick);
}
if(AccessKey.Length > 0)
htw.AddAttribute(HtmlTextWriterAttribute.Accesskey, AccessKey);
if(TabIndex != 0)
htw.AddAttribute(HtmlTextWriterAttribute.Tabindex,
TabIndex.ToString(NumberFormatInfo.InvariantInfo));
htw.RenderBeginTag(HtmlTextWriterTag.Input);
htw.RenderEndTag();
}
#endregion
#region IPostBackDataHandler Members
void IPostBackDataHandler.RaisePostDataChangedEvent()
{
OnCheckedChanged(EventArgs.Empty);
}
bool IPostBackDataHandler.LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection)
{
bool result = false;
string value = postCollection[GroupName];
if((value != null) && (value == Value))
{
if(!Checked)
{
Checked = true;
result = true;
}
}
else
{
if(Checked)
Checked = false;
}
// if (postCollection["RadioButton_Checked"]!=null)this.Checked=Convert.ToBoolean(postCollection["RadioButton_Checked"]);
return result;
}
#endregion
}
}

@ -0,0 +1,241 @@
using System;
using System.Text;
using System.Text.RegularExpressions;
namespace HuizhongLibrary.RegularExpressions
{
public class DataRegex
{
//验证日期格式
public static bool IsDateTime(string value)
{
if (value == "") return true;
try
{
DateTime dt = Convert.ToDateTime(value);
if (dt > new DateTime(3000, 1, 1) || dt < new DateTime(1900, 1, 1)) return false;
}
catch
{
return false;
}
return true;
}
/// <summary>
/// 验证日期格式
/// </summary>
/// <param name="Date"></param>
/// <returns>{0格式正确}{1空值}{2日期格式错误}{3日期超出范围1900-1-1至3000-1-1}</returns>
public static int IsDate(string value)
{
if (value == "") return 1;
DateTime dt;
try
{
dt = Convert.ToDateTime(value);
}
catch
{
return 2;
}
if (dt > new DateTime(3000, 1, 1) || dt < new DateTime(1900, 1, 1)) return 3;
return 0;
}
/// <summary>
/// 验证是否是整数
/// </summary>
/// <param name="value"></param>
/// <param name="IsMinus">验证是否可为负,true验证不能为负,flase可为负</param>
/// <returns></returns>
public static bool IsNumberInteger(string value, bool IsMinus)
{
if (value == "") return true;
try
{
if (IsMinus == false)
{
Convert.ToInt32(value);
}
else
{
if (Convert.ToInt32(value) < 0) return false;
}
}
catch
{
return false;
}
return true;
}
/// <summary>
/// 验证是否是整数
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static bool IsNumberInteger(string value, int minNumber, int maxNumber)
{
if (value == "") return true;
int sl = 0;
try
{
sl = Convert.ToInt32(value);
if (sl < minNumber || sl > maxNumber) return false;
}
catch
{
return false;
}
return true;
}
/// <summary>
/// 验证是否是整数
/// </summary>
public static bool IsNumberInteger(string value)
{
if (value == "") return true;
try
{
Convert.ToInt32(value);
}
catch
{
return false;
}
return true;
}
/// <summary>
/// 验证是否是浮点数
/// </summary>
public static bool IsNumberDouble(string value, Double minNumber, Double maxNumber)
{
if (value == "") return true;
double sl = 0;
try
{
sl = Convert.ToDouble(value);
if (sl < minNumber || sl > maxNumber) return false;
}
catch
{
return false;
}
return true;
}
/// <summary>
/// 验证是否是浮点数
/// </summary>
public static bool IsNumberDouble(string value)
{
if (value == "") return true;
try
{
Convert.ToDouble(value);
}
catch
{
return false;
}
return true;
}
/// <summary>
/// 验证是否是浮点数,并且小数位不能超过N位
/// </summary>
public static bool IsNumberDouble(string value, int len)
{
if (value == "") return true;
try
{
Match mc = Regex.Match(value, @"\d{1,9}$|\d{1,9}[.]\d{1," + len.ToString() + "}$");
if (value != mc.Value) return false;//如果找到的字符串不等于原字符串那么说明是错误的格式
}
catch
{
return false;
}
return true;
}
/// <summary>
/// 验证Email地址
/// </summary>
public static bool IsEmail(string value)
{
if (value == "") return true;
if (Regex.Matches(value, @"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$").Count == 0) return false;
return true;
}
/// <summary>
/// 验证身份证号码
/// </summary>
public static bool IsIdentityCard(string value)
{
if (value == "") return true;
if (Regex.Matches(value, @"^\d{15}$|^\d{18}$|^\d{17}(\d|X|x)$").Count == 0) return false;
return true;
}
/// <summary>
/// 验证邮政编码
/// </summary>
public static bool IsPostalcode(string value)
{
if (value == "") return true;
if (Regex.Matches(value, @"^\d{6}$").Count == 0) return false;
return true;
}
/// <summary>
/// 验证电话号码
/// </summary>
public static bool IsPhone(string value)
{
if (value == "") return true;
if (Regex.Matches(value, @"^^\d{11}$|\d{8}$|0\d{2,3}-?\d{8}$").Count == 0) return false;
return true;
}
/// <summary>
/// 验证IP地址
/// </summary>
public static bool IsIP(string value)
{
if (value == "") return true;
string[] ss = value.Split('.');
if (ss.Length != 4) return false;
foreach (string s in ss)
{
if (DataRegex.IsNumberInteger(s, 0, 255) == false) return false;
}
return true;
}
/// <summary>
/// 验证Url地址
/// </summary>
public static bool IsUrlAddress(string value)
{
if (value == "") return true;
if (Regex.Matches(value, @"^http://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?$").Count == 0) return false;
return true;
}
/// <summary>
/// 验证时间
/// </summary>
public static bool IsTime(string value)
{
if (value == "") return true;
if (Regex.Matches(value, @"^[0-1][0-9]:[0-5][0-9]:[0-5][0-9]$|^2[0-3]:[0-5][0-9]:[0-5][0-9]$").Count == 0) return false;
return true;
}
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

@ -0,0 +1,55 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using HuizhongLibrary.Data;
using HuizhongLibrary.Log;
namespace HuizhongLibrary
{
public class DatabaseConnect
{
private AutoResetEvent AutoReset = new AutoResetEvent(false);
bool IsRun = false;
public event Action ConnectComplete;
#region 启动检测
public void Start()
{
Thread t = new Thread(this.ThreadWhile);
t.Start();
}
#endregion
#region 停止检测
public void Stop()
{
IsRun = false;
AutoReset.Set();
}
#endregion
#region 测试连接
void ThreadWhile()
{
IsRun = true;
while (IsRun)
{
Database db = DatabaseFactory.CreateDatabase();
bool bk=db.TestConnection();
if (bk == true)
{
IsRun = false;
if (this.ConnectComplete != null) this.ConnectComplete();
return;
}
ErrorFollow.TraceWrite("数据库连接失败","暂停30秒后再试", db.ConnectionString);
AutoReset.WaitOne(30000);
}
}
#endregion
}
}

@ -0,0 +1,63 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Common;
using HuizhongLibrary.Common.Configuration;
namespace HuizhongLibrary.Data
{
public static class DatabaseFactory
{
public static Database CreateDatabase()
{
return CreateDatabase("ConnectionString");
}
public static Database CreateDatabasel()
{
return CreateDatabase("BaseConnectionString");
}
public static Database CreateDatabase(string name)
{
Database db = null;
if (DataCache.ConfigCache.ContainsKey(name) == false)
{
ConfigurationSourceSection.GetConnection(name);
}
if (DataCache.ConfigCache.ContainsKey(name) == false) return null;
string Namespace = DataCache.ConfigCache[name].Namespace;
string ConnectionString = DataCache.ConfigCache[name].Value;
if (string.IsNullOrEmpty(ConnectionString) == true) return null;
if (Namespace == "System.Data.Oledb")
{
ConnectionString = CustomIO.AccessReplacePath(ConnectionString);
}
db = new Database(Namespace, ConnectionString);
return db;
}
public static Database CreateDatabase2(string name)
{
Database db = null;
if (DataCache.ConfigCache.ContainsKey(name) == false)
{
ConfigurationSourceSection.GetConnection2(name);
}
if (DataCache.ConfigCache.ContainsKey(name) == false) return null;
string Namespace = DataCache.ConfigCache[name].Namespace;
string ConnectionString = DataCache.ConfigCache[name].Value;
if (string.IsNullOrEmpty(ConnectionString) == true) return null;
if (Namespace == "System.Data.Oledb")
{
ConnectionString = CustomIO.AccessReplacePath(ConnectionString);
}
db = new Database(Namespace, ConnectionString);
return db;
}
}
}

@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HuizhongLibrary
{
public static class DateUtils
{
public static long ToTimestamp(this DateTime dateTime)
{
DateTime historyDate = new DateTime(1970, 1, 1);
long timestamp = (dateTime.Ticks - historyDate.Ticks) / 10000000 - 8 * 60 * 60;
return timestamp;
}
public static DateTime ToDateTime(this long timestamp)
{
DateTime historyDate = new DateTime(1970, 1, 1);
long timeTicks = (timestamp + 8 * 60 * 60) * 10000000 + historyDate.Ticks;
return DateTime.FromBinary(timeTicks);
}
/// <summary>
/// 获取北京时间
/// </summary>
/// <returns></returns>
public static DateTime GetBJNow()
{
return DateTime.Now.ToUniversalTime().AddHours(8);
}
}
}

@ -0,0 +1,490 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HuizhongLibrary.Dingtalk
{
#region 用户信息
public class DingtalkUser
{
public int errcode { get; set; }
public string errmsg { get; set; }
public string userid { get; set; }
public string deviceId { get; set; }
public bool is_sys { get; set; }
public int sys_level { get; set; }
}
public class DingtalkUserZZD
{
public bool success { get; set; }
public DingtalkUserContentZZD content { get; set; }
}
public class DingtalkUserContentZZD
{
public string responseMessage { get; set; }
public DingtalkUserInfoZZD data { get; set; }
public string responseCode { get; set; }
}
public class DingtalkUserInfoZZD
{
public string account { get; set; }
public long accountId { get; set; }
public string employeeCode { get; set; }
public string lastName { get; set; }
public string nickNameCn { get; set; }
public long realmId { get; set; }
public string realmName { get; set; }
public string tenantUserId { get; set; }
public string openid { get; set; }
}
public class DingtalkUserInfo
{
public int errcode { get; set; }
public string openId { get; set; }
public string userid { get; set; }
public string mobile { get; set; }
public string name { get; set; }
}
#endregion
#region AccessToken
public class DingtalkAccessToken
{
public string access_token { get; set; }
public int errcode { get; set; }
public string errmsg { get; set; }
}
public class DingtalkAccessTokenZZD
{
public string accessToken { get; set; }
}
public class DingtalkAccessTokenContentZZD
{
public string requestId { get; set; }
public bool success { get; set; }
public string responseMessage { get; set; }
public string responseCode { get; set; }
public DingtalkAccessTokenZZD data { get; set; }
}
public class DingtalkAccessTokenMessZZD
{
public bool success { get; set; }
public DingtalkAccessTokenContentZZD content { get; set; }
}
#endregion
#region 工作消息
public class DingtalkMessage
{
public int agent_id { get; set; }
public string userid_list { get; set; }
//public string dept_id_list { get; set; }
public bool to_all_user { get; set; }
public string msgtype { get; set; }
public string url { get; set; }
public string title { get; set; }
public string msg { get; set; }
public DingtalkMessage()
{
msgtype = "text";
}
public string ToJson()
{
StringBuilder sb = new StringBuilder();
sb.Append("{");
sb.Append("\"agent_id\":"+this.agent_id+",");
if (to_all_user == true)
{
sb.Append("\"to_all_user\":true,");
}
else
{
sb.Append("\"userid_list\":\"" + this.userid_list + "\",");
}
//sb.Append("\"userid_list\":\"" + this.userid_list + "\",");
//sb.Append("\"dept_id_list\":\"" + this.dept_id_list + "\",");
if (msgtype == "text")
{
sb.Append("\"msg\":{\"msgtype\":\"text\",\"text\":{\"content\":\""+this.msg + "\"}}");
}
if (msgtype == "action_card")
{
sb.Append("\"msg\":{\"msgtype\":\"action_card\",\"action_card\":{\"title\":\"" + this.title + "\",\"markdown\":\"" + this.msg + "\",\"single_title\":\"查看详情\",\"single_url\":\"" + this.url + "\"}}");
}
sb.Append("}");
return sb.ToString();
}
}
#endregion
#region 消息结果
public class DingResult
{
public int errcode { get; set; }
public string errmsg { get; set; }
public int id { get; set; }
public bool hasMore { get; set; }
public string userid { get; set; }
public List<DingDepartMent> department { get; set; }
public List<DingUser> userlist { get; set; }
public LeaveTimeResult result { get; set; }
}
#endregion
#region 消息结果2
public class DingResult2
{
public int errcode { get; set; }
public string errmsg { get; set; }
public Exam_process_instance process_instance { get; set; }
}
#endregion
#region 部门
public class DingDepartMent
{
public int id { get; set; }
public string name { get; set; }
public string parentid { get; set; }
public string order { get; set; }
public string ToJson()
{
StringBuilder sb = new StringBuilder();
sb.Append("{");
if (id>0)sb.Append("\"id\":" + this.id + ",");
sb.Append("\"name\":\"" + this.name + "\",");
sb.Append("\"parentid\":\"" + this.parentid + "\",");
sb.Append("\"order\":\"" + this.order + "\"");
sb.Append("}");
return sb.ToString();
}
}
#endregion
#region 员工
public class DingUser
{
public string userid { get; set; }
public string name { get; set; }
public List<int> department { get; set; }
public string mobile { get; set; }
public DingUser()
{
department = new List<int>();
}
}
public class DingUserGet
{
public int errcode { get; set; }
public string errmsg { get; set; }
public string userid { get; set; }
}
#endregion
#region 考勤请求
public class DingWorkRequest
{
public String workDateFrom { get; set; }
public String workDateTo { get; set; }
public String checkDateFrom { get; set; }
public String checkDateTo { get; set; }
public List<string> userIdList { get; set; }
public List<string> userIds { get; set; }
public int offset { get; set; }
public int limit { get; set; }
public DingWorkRequest()
{
limit = 50;
userIdList = new List<string>();
userIds = new List<string>();
}
}
#endregion
#region 考勤结果
public class DingWorkResult
{
public int errcode { get; set; }
public string errmsg { get; set; }
public bool hasMore { get; set; }
public List<DingWorkResult2> recordresult { get; set; }
}
public class DingWorkResult2
{
public long id { get; set; }
/// <summary>
/// 考勤组ID
/// </summary>
public long groupId { get; set; }
/// <summary>
/// 排班ID
/// </summary>
public long planId { get; set; }
/// <summary>
/// 打卡记录ID
/// </summary>
public long recordId { get; set; }
/// <summary>
/// 考勤日期
/// </summary>
public long workDate { get; set; }
public string userId { get; set; }
public string userAddress { get; set; }
/// <summary>
/// 打卡时间
/// </summary>
public Int64 userCheckTime { get; set; }
/// <summary>
/// OnDuty=上班,OffDuty=下班
/// </summary>
public string checkType { get; set; }
/// <summary>
/// Normal=范围内,Outside=范围外,NotSigned=未打卡
/// </summary>
public string locationResult { get; set; }
/// <summary>
/// Normal=正常,Early=早退,Late=迟到,SeriousLate=严重迟到,Absenteeism=旷工迟到,NotSigned=未打卡
/// </summary>
public string timeResult { get; set; }
public DateTime GetuserCheckTime()
{
return CustomIO.ConvertTimeStampToDateTime(userCheckTime);
}
public DingWorkResult2 Copy()
{
var model = new DingWorkResult2();
model.id = this.id;
model.groupId = this.groupId;
model.planId = this.planId;
model.recordId = this.recordId;
model.workDate = this.workDate;
model.userId = this.userId;
model.userCheckTime = this.userCheckTime;
model.checkType = this.checkType;
model.locationResult = this.locationResult;
model.timeResult = this.timeResult;
model.userAddress = this.userAddress;
return model;
}
public string deviceId { get; set; }
}
#endregion
#region 请假时长请求
public class LeaveTimeRequest
{
public string userid { get; set; }
public string from_date { get; set; }
public string to_date { get; set; }
}
#endregion
#region 请假时长
public class LeaveTimeResult
{
public int duration_in_minutes { get; set; }
}
#endregion
#region 审批请求
public class ExamIdRequest
{
public string process_code { get; set; }
public long start_time { get; set; }
public long end_time { get; set; }
public int size { get; set; }
public int cursor { get; set; }
//public List<string> userid_list { get; set; }
public ExamIdRequest()
{
size = 20;
}
public string ToJson()
{
return this.ToJsonString();
}
}
#endregion
#region 获取审批实例id
public class ExamIdResult
{
public int errcode { get; set; }
public string errmsg { get; set; }
public ExamIdResult2 result { get; set; }
}
public class ExamIdResult2
{
public int next_cursor { get; set; }
public List<string> list { get; set; }
}
#endregion
#region 获取审批实例详情
public class ExamResult
{
public int errcode { get; set; }
public string errmsg { get; set; }
public string process_instance_id { get; set; }
public ExamResult2 process_instance { get; set; }
}
public class ExamResult2
{
public string title { get; set; }
public string create_time { get; set; }
public string finish_time { get; set; }
public string originator_userid { get; set; }
public string originator_dept_id { get; set; }
public string status { get; set; }
public List<string> cc_userids { get; set; }
public List<ExamResult3_1> form_component_values { get; set; }
public string result { get; set; }
public string business_id { get; set; }
public List<ExamResult3_2> operation_records { get; set; }
public List<ExamResult3_3> tasks { get; set; }
public string originator_dept_name { get; set; }
public string biz_action { get; set; }
public List<string> attached_process_instance_ids { get; set; }
}
public class ExamResult3_1
{
public string component_type { get; set; }
public string name { get; set; }
public string value { get; set; }
public string ext_value { get; set; }
}
public class ExamResult3_2
{
public string userid { get; set; }
public string date { get; set; }
public string operation_type { get; set; }
public string operation_result { get; set; }
public string remark { get; set; }
}
public class ExamResult3_3
{
public string userid { get; set; }
public string task_status { get; set; }
public string task_result { get; set; }
public string create_time { get; set; }
public string finish_time { get; set; }
public string taskid { get; set; }
}
#endregion
#region 请假详情
public class LeaveResult
{
public string userid { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public string LeaveType{get;set;}
public int LeaveDay { get; set; }
public string Cause { get; set; }
public int State { get; set; }
}
public class Exam_process_instance
{
public string originator_userid { get; set; }
public string result { get; set; }
public List<Exam_form_component_values> form_component_values { get; set; }
}
public class Exam_form_component_values
{
public string name { get; set; }
public string value { get; set; }
}
#endregion
#region 日志请求
public class DingLogRequest
{
public long start_time { get; set; }
public long end_time { get; set; }
public string template_name { get; set; }
public string userid { get; set; }
public long cursor { get; set; }
public int size { get; set; }
public DingLogRequest()
{
size = 20;
}
public string ToJson()
{
return this.ToJsonString();
}
}
#endregion
#region 日志结果
public class DingLogResult
{
public int errcode { get; set; }
public string errmsg { get; set; }
public DingLogResult2 result { get; set; }
}
public class DingLogResult2
{
public int size { get; set; }
/// <summary>
/// 是否还有下一页
/// </summary>
public bool has_more { get; set; }
/// <summary>
/// 下次查询起始页
/// </summary>
public long next_cursor { get; set; }
public List<DingLogResult3> data_list { get; set; }
}
public class DingLogResult3
{
/// <summary>
/// 日志唯一id
/// </summary>
public string report_id { get; set; }
/// <summary>
/// 日志创建时间
/// </summary>
public long create_time { get; set; }
/// <summary>
/// 日志创建人userid
/// </summary>
public string creator_id { get; set; }
/// <summary>
/// 日志创建人
/// </summary>
public string creator_name { get; set; }
/// <summary>
/// 部门
/// </summary>
public string dept_name { get; set; }
public string template_name { get; set; }
public string remark { get; set; }
public List<DingLogResult4> contents { get; set; }
public DingLogResult3 Copy()
{
var model=new DingLogResult3();
model.report_id = this.report_id;
model.create_time = this.create_time;
model.creator_id = this.creator_id;
model.creator_name = this.creator_name;
model.dept_name = this.dept_name;
model.template_name = this.template_name;
model.remark = this.remark;
model.contents = this.contents;
return model;
}
}
public class DingLogResult4
{
public string sort { get; set; }
public string type { get; set; }
public string key { get; set; }
public string value { get; set; }
}
#endregion
}

@ -0,0 +1,888 @@
using HuizhongLibrary.Log;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Web.Script.Serialization;
namespace HuizhongLibrary.Dingtalk
{
public class DingtalkService
{
#region 获取签名
public static String GetSignName(string AccessToken, out string ErrorMessage)
{
ErrorMessage="";
return "";
}
#endregion
#region 获取AccessToken
public static string DingtalkAccessToken(string Appid, string Secret, out string ErrorMessage)
{
string url = "https://oapi.dingtalk.com/gettoken?corpid=" + Appid + "&corpsecret=" + Secret;
JavaScriptSerializer JsonConvert = new JavaScriptSerializer();
UTF8Encoding encoding = new UTF8Encoding();
string XmlContent = CustomIO.HttpRequest(url, "GET", "", null, HttpVersion.Version10, null, out ErrorMessage);
if (string.IsNullOrEmpty(ErrorMessage) == false) return "";
DingtalkAccessToken model2 = JsonConvert.Deserialize<DingtalkAccessToken>(XmlContent);
if (model2.errcode == 0)
{
return model2.access_token;
}
else
{
ErrorMessage = model2.errmsg;
}
return "";
}
#endregion
#region 获取AccessToken
public static string DingtalkAccessTokenNew(string Appid, string Secret, out string ErrorMessage)
{
string url = "https://oapi.dingtalk.com/gettoken?appkey=" + Appid + "&appsecret=" + Secret;
JavaScriptSerializer JsonConvert = new JavaScriptSerializer();
UTF8Encoding encoding = new UTF8Encoding();
string XmlContent = CustomIO.HttpRequest(url, "GET", "", null, HttpVersion.Version10, null, out ErrorMessage);
if (string.IsNullOrEmpty(ErrorMessage) == false) return "";
DingtalkAccessToken model2 = JsonConvert.Deserialize<DingtalkAccessToken>(XmlContent);
if (model2.errcode == 0)
{
return model2.access_token;
}
else
{
ErrorMessage = model2.errmsg;
}
return "";
}
#endregion
#region 获取AccessToken
public static string DingtalkAccessTokenNewZZD(string Appid, string Secret, out string ErrorMessage,string ip, string mac)
{
//string url = "https://openplatform.dg-work.cn/gettoken.json?appkey=" + Appid + "&appsecret=" + Secret;
//JavaScriptSerializer JsonConvert = new JavaScriptSerializer();
//UTF8Encoding encoding = new UTF8Encoding();
//string XmlContent = CustomIO.HttpRequest(url, "GET", "", null, HttpVersion.Version10, null, out ErrorMessage);
//if (string.IsNullOrEmpty(ErrorMessage) == false) return "";
ErrorMessage="";
string url = "https://openplatform-pro.ding.zj.gov.cn/gettoken.json?appkey=" + Appid + "&appsecret=" + Secret;
string XmlContent = GetAccessTokenZZD(url, ip, mac, Appid, Secret);
JavaScriptSerializer JsonConvert = new JavaScriptSerializer();
DingtalkAccessTokenMessZZD model2 = JsonConvert.Deserialize<DingtalkAccessTokenMessZZD>(XmlContent);
if (model2.success == true)
{
if (model2.content.success == true)
{
return model2.content.data.accessToken;
}
else
{
ErrorMessage = XmlContent;
}
}
else
{
ErrorMessage = XmlContent;
}
return "";
}
//根据authCode换取用户信息
//参数 paramData"access_token=" + access_token + "&auth_code=" + auth_code + ""
public static string ZzdPostWebRequest(string postUrl, string paramData, string access_token, string auth_code, string ip, string mac, string Appid, string Secret)
{
try
{
string ret = string.Empty;
byte[] byteArray = Encoding.UTF8.GetBytes(paramData); //转化
var AccessKey = Appid;
var SecretKey = Secret;
var Timestamp = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:sszzz");
var Nonce = ConvertDateTimeToInt(DateTime.Now) + "1234";
var CanonicalURI = "/rpc/oauth2/dingtalk_app_user.json";
var HttpRequestParams = "access_token=" + access_token + "&auth_code=" + auth_code + "";
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
webReq.Method = "POST";
webReq.ContentType = "application/json";
webReq.ContentLength = byteArray.Length;
webReq.Headers.Add("X-Hmac-Auth-IP", ip);
webReq.Headers.Add("X-Hmac-Auth-MAC", mac);
webReq.Headers.Add("X-Hmac-Auth-Timestamp", Timestamp);
webReq.Headers.Add("X-Hmac-Auth-Version", "1.0");
webReq.Headers.Add("X-Hmac-Auth-Nonce", Nonce);
webReq.Headers.Add("apiKey", AccessKey);
var bytesToSign = "POST" + '\n' + Timestamp + '\n' + Nonce + '\n' + CanonicalURI + '\n' + HttpRequestParams;
webReq.Headers.Add("X-Hmac-Auth-Signature", GetSignature(bytesToSign, SecretKey));
System.IO.Stream newStream = webReq.GetRequestStream();
newStream.Write(byteArray, 0, byteArray.Length);//写入参数
newStream.Close();
HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);
ret = sr.ReadToEnd();
sr.Close();
response.Close();
newStream.Close();
return ret;
}
catch (WebException ex)
{
var res = (HttpWebResponse)ex.Response;
System.IO.StreamReader sr = new System.IO.StreamReader(res.GetResponseStream(), Encoding.UTF8);
var ret = sr.ReadToEnd();
return ret;
}
}
///<summary>
///获取AccessToken
///</summary>
///<paramname="url"></param>
///<returns></returns>
public static string GetAccessTokenZZD(string url, string ip, string mac, string Appid, string Secret)
{
try
{
var AccessKey = Appid;
var SecretKey = Secret;
var xmlResponse = "";
var Timestamp = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:sszzz");
var Nonce = ConvertDateTimeToInt(DateTime.Now) + "1234";
var CanonicalURI = "/gettoken.json";
var HttpRequestParams = "appkey=" + AccessKey + "&appsecret=" + SecretKey + "";
//发起请求
var webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
//webRequest.Headers.Add("X-Hmac-Auth-IP",ip);
//webRequest.Headers.Add("X-Hmac-Auth-MAC",mac);
webRequest.Headers.Add("X-Hmac-Auth-Timestamp", Timestamp);
webRequest.Headers.Add("X-Hmac-Auth-Version", "1.0");
webRequest.Headers.Add("X-Hmac-Auth-Nonce", Nonce);
webRequest.Headers.Add("apiKey", AccessKey);
var bytesToSign = "GET" + '\n' + Timestamp + '\n' + Nonce + '\n' + CanonicalURI +'\n' + HttpRequestParams;
webRequest.Headers.Add("X-Hmac-Auth-Signature", GetSignature(bytesToSign,SecretKey));
webRequest.ContentType = "application/json";
webRequest.Method = "GET";
//响应
WebResponse webResponse = webRequest.GetResponse();
System.IO.StreamReader sr = new System.IO.StreamReader(webResponse.GetResponseStream(),
Encoding.UTF8);
xmlResponse = sr.ReadToEnd();
return xmlResponse;
}
catch (WebException ex)
{
var res = (HttpWebResponse)ex.Response;
System.IO.StreamReader sr = new System.IO.StreamReader(res.GetResponseStream(), Encoding.UTF8);
var ret = sr.ReadToEnd();
return ret;
}
}
/// <summary>  
        /// 将c# DateTime时间格式转换为Unix时间戳格式  
        /// </summary>  
        /// <param name="time">时间</param>  
        /// <returns>long</returns>  
        private static long ConvertDateTimeToInt(System.DateTime time)
{
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
long t = (time.Ticks - startTime.Ticks) / 10000;   //除10000调整为13位      
            return t;
}
/// <summary>
/// 获取签名
/// </summary>
/// <param name="message">将bytesToSign作为消息</param>
/// <param name="secret">将SecretKey作为秘钥</param>
/// <returns></returns>
private static string GetSignature(string message, string secret)
{
secret = secret ?? "";
var encoding = new System.Text.ASCIIEncoding();
byte[] keyByte = encoding.GetBytes(secret);
byte[] messageBytes = encoding.GetBytes(message);
using (var hmacsha256 = new System.Security.Cryptography.HMACSHA256(keyByte))
{
byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
return Convert.ToBase64String(hashmessage);
}
}
// private T DingGovRequest<T>(HttpMethod method, string canonicalURI, Dictionary<string, string> requestParas)
// {
// var domain = ModuleConfig.DingGovAPIDomain;
// var accessKey = ModuleConfig.DingGovAppKey;
// var secretKey = ModuleConfig.DingGovAppSecret;
// var timestamp = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:sszzz");
// var nonce = ConvertDateTimeToInt(DateTime.Now) + "1234";
// var requestUrl = domain + canonicalURI;
// try
// {
// var bytesToSign = $"{method}\n{timestamp}\n{nonce}\n{canonicalURI}";//参数参与签名
// bytesToSign += '\n' + DicionartyToUrlParameters(requestParas);
// var message = new HttpRequestMessage
// {
// Method = method,
// };
// message.Headers.Add("X-Hmac-Auth-IP", "1.1.1.1");
// message.Headers.Add("X-Hmac-Auth-MAC", "MAC");
// message.Headers.Add("X-Hmac-Auth-Timestamp", timestamp);
// message.Headers.Add("X-Hmac-Auth-Version", "1.0");
// message.Headers.Add("X-Hmac-Auth-Nonce", nonce.ToString());
// message.Headers.Add("apiKey", accessKey);
// message.Headers.Add("X-Hmac-Auth-Signature", GetSignature(bytesToSign, secretKey));
////Post时放入body
// if (method == HttpMethod.Post)
// {
// var paras = new Dictionary<string, string>();
// foreach (var dic in requestParas)
// {
// paras.Add(dic.Key, Uri.UnescapeDataString(dic.Value));
// }
// message.Content = new FormUrlEncodedContent(paras);
// message.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
// }
////Get时放入urlParameters
// else if (method == HttpMethod.Get)
// {
// requestUrl += $"?{DicionartyToUrlParameters(requestParas)}";
// }
// message.RequestUri = new Uri(requestUrl);
// using (var client = new HttpClient())
// {
// var request = client.SendAsync(message);
// request.Wait();
// var reponseContent = request.Result.Content.ReadAsStringAsync();
// reponseContent.Wait();
// //记录日志
// if (!request.Result.IsSuccessStatusCode)
// {
// throw new Exception(reponseContent.Result);
// }
// return JsonConvert.DeserializeObject<T>(reponseContent.Result);
// }
// }
// catch (Exception ex)
// {
////记录日志
// return (T)default;
// }
// }
#endregion
#region 根据code获取用户信息
public static DingtalkUserInfo GetDingtalkUserInfo(string AccessToken, string code, out string ErrorMessage)
{
string url = "https://oapi.dingtalk.com/user/getuserinfo?access_token=" + AccessToken + "&code=" + code;
JavaScriptSerializer JsonConvert = new JavaScriptSerializer();
UTF8Encoding encoding = new UTF8Encoding();
string XmlContent = CustomIO.HttpRequest(url, "GET", "", null, HttpVersion.Version10, null, out ErrorMessage);
if (string.IsNullOrEmpty(ErrorMessage) == false) return null;
DingtalkUser model2 = JsonConvert.Deserialize<DingtalkUser>(XmlContent);
if (model2.errcode != 0)
{
ErrorMessage = XmlContent;
return null;
}
ErrorFollow.TraceWrite("获取钉钉用户ID", "", model2.ToJsonString());
url = "https://oapi.dingtalk.com/user/get?access_token=" + AccessToken + "&userid=" + model2.userid;
XmlContent = CustomIO.HttpRequest(url, "GET", "", null, HttpVersion.Version10, null, out ErrorMessage);
if (string.IsNullOrEmpty(ErrorMessage) == false) return null;
DingtalkUserInfo model3 = JsonConvert.Deserialize<DingtalkUserInfo>(XmlContent);
if (model3.errcode != 0)
{
ErrorMessage = XmlContent;
}
return model3;
}
#endregion
#region 根据code获取用户信息
public static DingtalkUserInfoZZD GetDingtalkUserInfoZZD(string AccessToken, string code, out string ErrorMessage, string ip, string mac,string Appid, string Secret)
{
//string url = "https://openplatform.dg-work.cn/rpc/oauth2/dingtalk_app_user.json?access_token=" + AccessToken + "&auth_code=" + code;
//JavaScriptSerializer JsonConvert = new JavaScriptSerializer();
//UTF8Encoding encoding = new UTF8Encoding();
//string XmlContent = CustomIO.HttpRequest(url, "GET", "", null, HttpVersion.Version10, null, out ErrorMessage);
//if (string.IsNullOrEmpty(ErrorMessage) == false) return null;
ErrorMessage = "";
string url = "https://openplatform-pro.ding.zj.gov.cn/rpc/oauth2/dingtalk_app_user.json";
string paramData = "access_token=" + AccessToken + "&auth_code=" + code + "";
JavaScriptSerializer JsonConvert = new JavaScriptSerializer();
string XmlContent = ZzdPostWebRequest(url, paramData, AccessToken, code, ip, mac, Appid, Secret);
DingtalkUserZZD model2 = JsonConvert.Deserialize<DingtalkUserZZD>(XmlContent);
if (model2.success != true)
{
ErrorMessage = XmlContent;
return null;
}
ErrorFollow.TraceWrite("获取钉钉用户ID", "", model2.ToJsonString());
//url = "https://oapi.dingtalk.com/user/get?access_token=" + AccessToken + "&userid=" + model2.content.data.accountId;
//XmlContent = CustomIO.HttpRequest(url, "GET", "", null, HttpVersion.Version10, null, out ErrorMessage);
//if (string.IsNullOrEmpty(ErrorMessage) == false) return null;
//DingtalkUserInfo model3 = JsonConvert.Deserialize<DingtalkUserInfo>(XmlContent);
//if (model3.errcode != 0)
//{
// ErrorMessage = XmlContent;
//}
return model2.content.data;
}
#endregion
#region 发送工作消息
public static void SendMessage(string AccessToken,int AgentID, DingtalkMessage model,out string ErrorMessage)
{
ErrorMessage="";
string url = "https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token=" + AccessToken;
string postmessage = model.ToJson();
UTF8Encoding encoding = new UTF8Encoding();
byte[] data = encoding.GetBytes(postmessage);
JavaScriptSerializer JsonConvert = new JavaScriptSerializer();
string XmlContent = CustomIO.HttpRequest(url, "POST", "Content-Type:application/json", null, HttpVersion.Version10, data, out ErrorMessage);
if (string.IsNullOrEmpty(ErrorMessage) == false) return;
DingResult model2 = JsonConvert.Deserialize<DingResult>(XmlContent);
if (model2.errcode == 0) return;
ErrorMessage = model2.errmsg;
}
#endregion
#region 发送工作消息
public static void SendMessage(string AccessToken, int AgentID, string msg, out string ErrorMessage)
{
ErrorMessage = "";
string url = "https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token=" + AccessToken;
string postmessage = msg;
UTF8Encoding encoding = new UTF8Encoding();
byte[] data = encoding.GetBytes(postmessage);
JavaScriptSerializer JsonConvert = new JavaScriptSerializer();
string XmlContent = CustomIO.HttpRequest(url, "POST", "Content-Type:application/json", null, HttpVersion.Version10, data, out ErrorMessage);
if (string.IsNullOrEmpty(ErrorMessage) == false) return;
DingResult model2 = JsonConvert.Deserialize<DingResult>(XmlContent);
if (model2.errcode == 0) return;
ErrorMessage = model2.errmsg;
}
#endregion
#region 创建部门接口
public static int DingDepartMentCreate(string AccessToken, DingDepartMent model, out string ErrorMessage)
{
string url = "https://oapi.dingtalk.com/department/create?access_token=" + AccessToken;
JavaScriptSerializer JsonConvert = new JavaScriptSerializer();
//string postmessage = JsonConvert.Serialize(model);
string postmessage = model.ToJson();
UTF8Encoding encoding = new UTF8Encoding();
byte[] data = encoding.GetBytes(postmessage);
string XmlContent = CustomIO.HttpRequest(url, "POST", "text/json", null, HttpVersion.Version10, data, out ErrorMessage);
if (string.IsNullOrEmpty(ErrorMessage) == false) return 0;
DingResult model2 = JsonConvert.Deserialize<DingResult>(XmlContent);
if (model2.errcode == 0) return model2.id;
ErrorMessage = model2.errmsg;
return 0;
}
#endregion
#region 创建部门接口
public static int DingDepartMentCreate(string AccessToken, string msg, out string ErrorMessage)
{
string url = "https://oapi.dingtalk.com/department/create?access_token=" + AccessToken;
JavaScriptSerializer JsonConvert = new JavaScriptSerializer();
//string postmessage = JsonConvert.Serialize(model);
string postmessage = msg;
UTF8Encoding encoding = new UTF8Encoding();
byte[] data = encoding.GetBytes(postmessage);
string XmlContent = CustomIO.HttpRequest(url, "POST", "text/json", null, HttpVersion.Version10, data, out ErrorMessage);
if (string.IsNullOrEmpty(ErrorMessage) == false) return 0;
DingResult model2 = JsonConvert.Deserialize<DingResult>(XmlContent);
if (model2.errcode == 0) return model2.id;
ErrorMessage = model2.errmsg;
return 0;
}
#endregion
#region 修改部门接口
public static int DingDepartMentUpdate(string AccessToken, DingDepartMent model, out string ErrorMessage)
{
string
url = "https://oapi.dingtalk.com/department/update?access_token=" + AccessToken;
JavaScriptSerializer JsonConvert = new JavaScriptSerializer();
//string postmessage = JsonConvert.Serialize(model);
string postmessage = model.ToJsonString();
UTF8Encoding encoding = new UTF8Encoding();
byte[] data = encoding.GetBytes(postmessage);
string XmlContent = CustomIO.HttpRequest(url, "POST", "text/json", null, HttpVersion.Version10, data, out ErrorMessage);
if (string.IsNullOrEmpty(ErrorMessage) == false) return 0;
DingResult model2 = JsonConvert.Deserialize<DingResult>(XmlContent);
if (model2.errcode == 0) return model2.id;
ErrorMessage = model2.errmsg;
return 0;
}
#endregion
#region 修改部门接口
public static int DingDepartMentUpdate(string AccessToken, string msg, out string ErrorMessage)
{
string
url = "https://oapi.dingtalk.com/department/update?access_token=" + AccessToken;
JavaScriptSerializer JsonConvert = new JavaScriptSerializer();
//string postmessage = JsonConvert.Serialize(model);
string postmessage = msg;
UTF8Encoding encoding = new UTF8Encoding();
byte[] data = encoding.GetBytes(postmessage);
string XmlContent = CustomIO.HttpRequest(url, "POST", "text/json", null, HttpVersion.Version10, data, out ErrorMessage);
if (string.IsNullOrEmpty(ErrorMessage) == false) return 0;
DingResult model2 = JsonConvert.Deserialize<DingResult>(XmlContent);
if (model2.errcode == 0) return model2.id;
ErrorMessage = model2.errmsg;
return 0;
}
#endregion
#region 删除部门接口
public static void DingDepartMentDelete(string AccessToken, string DeptID, out string ErrorMessage)
{
string url = "https://oapi.dingtalk.com/department/delete?access_token=" + AccessToken + "&id=" + DeptID;
JavaScriptSerializer JsonConvert = new JavaScriptSerializer();
string XmlContent = CustomIO.HttpRequest(url, "GET", "", null, HttpVersion.Version10, null, out ErrorMessage);
if (string.IsNullOrEmpty(ErrorMessage) == false) return;
DingResult model2 = JsonConvert.Deserialize<DingResult>(XmlContent);
if (model2.errcode == 0) return;
ErrorMessage = model2.errmsg;
}
#endregion
#region 获取部门列表
public static List<DingDepartMent> DingDepartMent(string Appid, string Secret, out string ErrorMessage)
{
string AccessToken = DingtalkService.DingtalkAccessToken(Appid, Secret, out ErrorMessage);
if (string.IsNullOrEmpty(AccessToken) == true) return null;
ErrorFollow.TraceWrite("DingDepartMent", AccessToken, "");
// AccessToken = "49f5edfc4cc6317a888091616f7000eb";
string url = "https://oapi.dingtalk.com/department/list?access_token=" + AccessToken+ "";
JavaScriptSerializer JsonConvert = new JavaScriptSerializer();
//string postmessage = "{\"id\":\"1\",\"fetch_child\":true}";
//UTF8Encoding encoding = new UTF8Encoding();
//byte[] data = encoding.GetBytes(postmessage);
string XmlContent = CustomIO.HttpRequest(url, "GET", "text/json", null, HttpVersion.Version10, null, out ErrorMessage);
if (string.IsNullOrEmpty(ErrorMessage) == false) return null;
DingResult model2 = JsonConvert.Deserialize<DingResult>(XmlContent);
if (model2.errcode == 0) return model2.department;
ErrorMessage = model2.errmsg;
return null;
}
#endregion
#region 获取部门列表
public static List<DingDepartMent> DingDepartMent2(string Appid, int did,string Secret, out string ErrorMessage)
{
string AccessToken = DingtalkService.DingtalkAccessToken(Appid, Secret, out ErrorMessage);
if (string.IsNullOrEmpty(AccessToken) == true) return null;
ErrorFollow.TraceWrite("DingDepartMent", AccessToken, "");
// AccessToken = "49f5edfc4cc6317a888091616f7000eb";
string url = "https://oapi.dingtalk.com/department/list?access_token=" + AccessToken + "&id="+ did;//98995365
JavaScriptSerializer JsonConvert = new JavaScriptSerializer();
//string postmessage = "{\"id\":\"1\",\"fetch_child\":true}";
//UTF8Encoding encoding = new UTF8Encoding();
//byte[] data = encoding.GetBytes(postmessage);
string XmlContent = CustomIO.HttpRequest(url, "GET", "text/json", null, HttpVersion.Version10, null, out ErrorMessage);
if (string.IsNullOrEmpty(ErrorMessage) == false) return null;
DingResult model2 = JsonConvert.Deserialize<DingResult>(XmlContent);
if (model2.errcode == 0) return model2.department;
ErrorMessage = model2.errmsg;
return null;
}
#endregion
#region 获取部门id列表
public static List<DingDepartMent> DingDepartMentId(string Appid, int did, string Secret, out string ErrorMessage)
{
string AccessToken = DingtalkService.DingtalkAccessToken(Appid, Secret, out ErrorMessage);
if (string.IsNullOrEmpty(AccessToken) == true) return null;
ErrorFollow.TraceWrite("DingDepartMentId", AccessToken, "");
// AccessToken = "49f5edfc4cc6317a888091616f7000eb";
string url = "https://oapi.dingtalk.com/department/list_ids?access_token=" + AccessToken + "&id=1";//98995365
JavaScriptSerializer JsonConvert = new JavaScriptSerializer();
//string postmessage = "{\"id\":\"1\",\"fetch_child\":true}";
//UTF8Encoding encoding = new UTF8Encoding();
//byte[] data = encoding.GetBytes(postmessage);
string XmlContent = CustomIO.HttpRequest(url, "GET", "text/json", null, HttpVersion.Version10, null, out ErrorMessage);
if (string.IsNullOrEmpty(ErrorMessage) == false) return null;
ErrorFollow.TraceWrite("DingDepartMentId", XmlContent, "");
// DingResult model2 = JsonConvert.Deserialize<DingResult>(XmlContent);
// if (model2.errcode == 0) return model2.department;
// ErrorMessage = model2.errmsg;
return null;
}
#endregion
#region 创建员工接口
public static string DingUserCreate(string AccessToken, DingUser model, out string ErrorMessage)
{
string url = "https://oapi.dingtalk.com/user/create?access_token=" + AccessToken;
JavaScriptSerializer JsonConvert = new JavaScriptSerializer();
//string postmessage = JsonConvert.Serialize(model);
string postmessage = model.ToJsonString();
UTF8Encoding encoding = new UTF8Encoding();
byte[] data = encoding.GetBytes(postmessage);
string XmlContent = CustomIO.HttpRequest(url, "POST", "text/json", null, HttpVersion.Version10, data, out ErrorMessage);
if (string.IsNullOrEmpty(ErrorMessage) == false) return "";
DingResult model2 = JsonConvert.Deserialize<DingResult>(XmlContent);
if (model2.errcode == 0) return model2.userid;
ErrorMessage = model2.errmsg;
return "";
}
#endregion
#region 创建员工接口
public static string DingUserCreate(string AccessToken, string msg, out string ErrorMessage)
{
string url = "https://oapi.dingtalk.com/user/create?access_token=" + AccessToken;
JavaScriptSerializer JsonConvert = new JavaScriptSerializer();
//string postmessage = JsonConvert.Serialize(model);
string postmessage = msg;
UTF8Encoding encoding = new UTF8Encoding();
byte[] data = encoding.GetBytes(postmessage);
string XmlContent = CustomIO.HttpRequest(url, "POST", "text/json", null, HttpVersion.Version10, data, out ErrorMessage);
if (string.IsNullOrEmpty(ErrorMessage) == false) return "";
DingResult model2 = JsonConvert.Deserialize<DingResult>(XmlContent);
if (model2.errcode == 0) return model2.userid;
ErrorMessage = model2.errmsg;
return "";
}
#endregion
#region 修改员工接口
public static void DingUserUpdate(string AccessToken, DingUser model, out string ErrorMessage)
{
string url = "https://oapi.dingtalk.com/user/update?access_token=" + AccessToken;
JavaScriptSerializer JsonConvert = new JavaScriptSerializer();
//string postmessage = JsonConvert.Serialize(model);
string postmessage = model.ToJsonString();
UTF8Encoding encoding = new UTF8Encoding();
byte[] data = encoding.GetBytes(postmessage);
string XmlContent = CustomIO.HttpRequest(url, "POST", "text/json", null, HttpVersion.Version10, data, out ErrorMessage);
if (string.IsNullOrEmpty(ErrorMessage) == false) return;
DingResult model2 = JsonConvert.Deserialize<DingResult>(XmlContent);
if (model2.errcode == 0) return;
ErrorMessage = model2.errmsg;
}
#endregion
#region 修改员工接口
public static void DingUserUpdate(string AccessToken, string msg, out string ErrorMessage)
{
string url = "https://oapi.dingtalk.com/user/update?access_token=" + AccessToken;
JavaScriptSerializer JsonConvert = new JavaScriptSerializer();
//string postmessage = JsonConvert.Serialize(model);
string postmessage = msg;
UTF8Encoding encoding = new UTF8Encoding();
byte[] data = encoding.GetBytes(postmessage);
string XmlContent = CustomIO.HttpRequest(url, "POST", "text/json", null, HttpVersion.Version10, data, out ErrorMessage);
if (string.IsNullOrEmpty(ErrorMessage) == false) return;
DingResult model2 = JsonConvert.Deserialize<DingResult>(XmlContent);
if (model2.errcode == 0) return;
ErrorMessage = model2.errmsg;
}
#endregion
#region 删除员工接口
public static void DingUserDelete(string AccessToken, string UserID, out string ErrorMessage)
{
string url = "https://oapi.dingtalk.com/user/delete?access_token=" + AccessToken + "&userid=" + UserID;
JavaScriptSerializer JsonConvert = new JavaScriptSerializer();
string XmlContent = CustomIO.HttpRequest(url, "GET", "", null, HttpVersion.Version10, null, out ErrorMessage);
if (string.IsNullOrEmpty(ErrorMessage) == false) return;
DingResult model2 = JsonConvert.Deserialize<DingResult>(XmlContent);
if (model2.errcode == 0) return;
ErrorMessage = model2.errmsg;
}
#endregion
#region 按手机号查询钉钉用户ID接口
public static string DingUserGet(string AccessToken, string Mobile, out string ErrorMessage)
{
string url = "https://oapi.dingtalk.com/user/get_by_mobile?access_token="+ AccessToken + "&mobile="+ Mobile;
JavaScriptSerializer JsonConvert = new JavaScriptSerializer();
//string postmessage = JsonConvert.Serialize(model);
//string postmessage = model.ToJsonString();
//UTF8Encoding encoding = new UTF8Encoding();
//byte[] data = encoding.GetBytes(postmessage);
string XmlContent = CustomIO.HttpRequest(url, "GET", "text/json", null, HttpVersion.Version10, null, out ErrorMessage);
if (string.IsNullOrEmpty(ErrorMessage) == false) return "";
DingUserGet model2 = JsonConvert.Deserialize<DingUserGet>(XmlContent);
if (model2.errcode == 0) return model2.userid;
ErrorMessage = model2.errmsg;
return "";
}
#endregion
#region 获取员工列表
public static List<DingUser> DingUser(string Appid,string Secret, string deptid, out string ErrorMessage)
{
string AccessToken = DingtalkService.DingtalkAccessToken(Appid, Secret, out ErrorMessage);
if (string.IsNullOrEmpty(AccessToken) == true) return null;
string url = "https://oapi.dingtalk.com/user/simplelist?access_token=" + AccessToken + "&department_id=" + deptid;
JavaScriptSerializer JsonConvert = new JavaScriptSerializer();
string XmlContent = CustomIO.HttpRequest(url, "GET", "", null, HttpVersion.Version10, null, out ErrorMessage);
if (string.IsNullOrEmpty(ErrorMessage) == false) return null;
DingResult model2 = JsonConvert.Deserialize<DingResult>(XmlContent);
if (model2.errcode == 0) return model2.userlist;
ErrorMessage = model2.errmsg;
return null;
}
#endregion
#region 获取考勤结果
public static List<DingWorkResult2> GetWork(string AccessToken, DingWorkRequest model, out string ErrorMessage)
{
var ListModel = new List<DingWorkResult2>();
GetWorkDetail(AccessToken, model, ListModel, out ErrorMessage);
return ListModel;
}
public static void GetWorkDetail(string AccessToken, DingWorkRequest model, List<DingWorkResult2> ListResult, out string ErrorMessage)
{
string url = "https://oapi.dingtalk.com/attendance/list?access_token=" + AccessToken;
JavaScriptSerializer JsonConvert = new JavaScriptSerializer();
string postmessage = model.ToJsonString();
UTF8Encoding encoding = new UTF8Encoding();
byte[] data = encoding.GetBytes(postmessage);
string XmlContent = CustomIO.HttpRequest(url, "POST", "text/json", null, HttpVersion.Version10, data, out ErrorMessage);
if (string.IsNullOrEmpty(ErrorMessage) == false) return;
var model2 = JsonConvert.Deserialize<DingWorkResult>(XmlContent);
if (model2.errcode == 0)
{
foreach (var item in model2.recordresult)
{
ListResult.Add(item.Copy());
}
if (model2.hasMore == false)
{
return;
}
model.offset += model.limit;
GetWorkDetail(AccessToken, model, ListResult, out ErrorMessage);
}
else
{
ErrorMessage = model2.errmsg;
}
}
public static List<DingWorkResult2> GetWordRecord(string AccessToken, DingWorkRequest model, out string ErrorMessage)
{
var ListModel = new List<DingWorkResult2>();
GetWorkDetailRecord(AccessToken, model, ListModel, out ErrorMessage);
return ListModel;
}
public static void GetWorkDetailRecord(string AccessToken, DingWorkRequest model, List<DingWorkResult2> ListResult, out string ErrorMessage)
{
string url = "https://oapi.dingtalk.com/attendance/listRecord?access_token=" + AccessToken;
JavaScriptSerializer JsonConvert = new JavaScriptSerializer();
string postmessage = model.ToJsonString();
UTF8Encoding encoding = new UTF8Encoding();
byte[] data = encoding.GetBytes(postmessage);
string XmlContent = CustomIO.HttpRequest(url, "POST", "text/json", null, HttpVersion.Version10, data, out ErrorMessage);
if (string.IsNullOrEmpty(ErrorMessage) == false) return;
var model2 = JsonConvert.Deserialize<DingWorkResult>(XmlContent);
if (model2.errcode == 0)
{
foreach (var item in model2.recordresult)
{
ListResult.Add(item.Copy());
}
if (model2.hasMore == false)
{
return;
}
model.offset += model.limit;
GetWorkDetail(AccessToken, model, ListResult, out ErrorMessage);
}
else
{
ErrorMessage = model2.errmsg;
}
}
#endregion
#region 获取请假时长
public static int GetLeaveTime(string AccessToken,string userid, DateTime StartDate, DateTime StopDate, out string ErrorMessage)
{
string url = "https://oapi.dingtalk.com/topapi/attendance/getleaveapproveduration?access_token=" + AccessToken;
JavaScriptSerializer JsonConvert = new JavaScriptSerializer();
var model = new LeaveTimeRequest();
model.from_date = StartDate.ToString("yyyy-MM-dd HH:mm:ss");
model.to_date = StopDate.ToString("yyyy-MM-dd HH:mm:ss");
model.userid = userid;
string postmessage = model.ToJsonString();
UTF8Encoding encoding = new UTF8Encoding();
byte[] data = encoding.GetBytes(postmessage);
string XmlContent = CustomIO.HttpRequest(url, "POST", "text/json", null, HttpVersion.Version10, data, out ErrorMessage);
if (string.IsNullOrEmpty(ErrorMessage) == false) return -1;
DingResult model2 = JsonConvert.Deserialize<DingResult>(XmlContent);
if (model2.errcode == 0)return model2.result.duration_in_minutes;
ErrorMessage = model2.errmsg;
return -1;
}
#endregion
#region 获取审批
public static List<ExamResult> GetListExam(string AccessToken,string examcode, DateTime StartTime,DateTime StopTime, out string ErrorMessage)
{
var requst1 = new ExamIdRequest();
requst1.process_code = examcode;
requst1.start_time = CustomIO.GetTimeStamp(StartTime);
requst1.end_time = CustomIO.GetTimeStamp(StopTime);
var list1 = DingtalkService.GetExamIds(AccessToken, examcode, requst1, out ErrorMessage);
if (string.IsNullOrEmpty(ErrorMessage) == false) return null;
var ListExam = new List<ExamResult>();
foreach (string item in list1)
{
var model = DingtalkService.GetExam(AccessToken, item, out ErrorMessage);
if (string.IsNullOrEmpty(ErrorMessage) == false) return null;
ListExam.Add(model);
}
return ListExam;
}
#endregion
#region 获取审批ID列表
public static List<string> GetExamIds(string AccessToken, string code, ExamIdRequest model,out string ErrorMessage)
{
var ListModel = new List<string>();
GetExamIdsDetail(AccessToken, code, model, ListModel, out ErrorMessage);
return ListModel;
}
public static void GetExamIdsDetail(string AccessToken, string code, ExamIdRequest model, List<string> ListResult,out string ErrorMessage)
{
string url = "https://oapi.dingtalk.com/topapi/processinstance/listids?access_token=" + AccessToken;
JavaScriptSerializer JsonConvert = new JavaScriptSerializer();
string postmessage = model.ToJsonString();
UTF8Encoding encoding = new UTF8Encoding();
byte[] data = encoding.GetBytes(postmessage);
string XmlContent = CustomIO.HttpRequest(url, "POST", "text/json", null, HttpVersion.Version10, data, out ErrorMessage);
if (string.IsNullOrEmpty(ErrorMessage) == false) return;
var model2 = JsonConvert.Deserialize<ExamIdResult>(XmlContent);
if (model2.errcode == 0)
{
foreach (var item in model2.result.list)
{
ListResult.Add(item);
}
if (model2.result.next_cursor == 0)
{
return;
}
model.cursor += model2.result.next_cursor;
GetExamIdsDetail(AccessToken, code, model, ListResult, out ErrorMessage);
}
else
{
ErrorMessage = model2.errmsg;
}
}
#endregion
#region 获取审批详情
public static ExamResult GetExam(string AccessToken, string process_instance_id,out string ErrorMessage)
{
string url = "https://oapi.dingtalk.com/topapi/processinstance/get?access_token=" + AccessToken;
JavaScriptSerializer JsonConvert = new JavaScriptSerializer();
string postmessage = "{\"process_instance_id\":\""+ process_instance_id + "\"}";
UTF8Encoding encoding = new UTF8Encoding();
byte[] data = encoding.GetBytes(postmessage);
string XmlContent = CustomIO.HttpRequest(url, "POST", "text/json", null, HttpVersion.Version10, data, out ErrorMessage);
if (string.IsNullOrEmpty(ErrorMessage) == false) return null;
var model2 = JsonConvert.Deserialize<ExamResult>(XmlContent);
model2.process_instance_id = process_instance_id;
if (model2.errcode == 0) return model2;
ErrorMessage = model2.errmsg;
return null;
}
#endregion
#region 获取请假详情
public static LeaveResult GetLeave(string AccessToken, string process_instance_id, out string ErrorMessage)
{
//string XmlContent = GetExam(AccessToken, process_instance_id, out ErrorMessage);
//if (string.IsNullOrEmpty(ErrorMessage) == false) return null;
//JavaScriptSerializer JsonConvert = new JavaScriptSerializer();
//DingResult2 model2 = JsonConvert.Deserialize<DingResult2>(XmlContent);
//if (model2.errcode != 0)
//{
// ErrorMessage = model2.errmsg;
// return null;
//}
//var model = new LeaveResult();
//model.userid = model2.process_instance.originator_userid;
//model.State = -1;
//if (model2.process_instance.result == "refuse") model.State = 0;
//if (model2.process_instance.result== "agree") model.State = 1;
//foreach (var item in model2.process_instance.form_component_values)
//{
// if (item.name == "请假类型") model.LeaveType = item.value;
// if (item.name == "请假事由") model.Cause = item.value;
// if (item.name == "请假天数") model.LeaveDay = Convert.ToInt32(item.value);
// if (item.name == "[\"开始时间\",\"结束时间\"]")
// {
// string sss = item.value.Replace("[", "").Replace("]","").Replace("\"", "");
// string[] ss = sss.Split(',');
// model.StartTime = Convert.ToDateTime(ss[0]);
// model.EndTime = Convert.ToDateTime(ss[1]);
// }
//}
//return model;
ErrorMessage = "";
return null;
}
#endregion
#region 获取日志详情
public static List<DingLogResult3> GetLog(string AccessToken, DingLogRequest model, out string ErrorMessage)
{
var ListModel = new List<DingLogResult3>();
GetLogDetail(AccessToken, model, ListModel, out ErrorMessage);
return ListModel;
}
public static void GetLogDetail(string AccessToken, DingLogRequest model, List<DingLogResult3> ListResult,out string ErrorMessage)
{
string url = "https://oapi.dingtalk.com/topapi/report/list?access_token=" + AccessToken;
JavaScriptSerializer JsonConvert = new JavaScriptSerializer();
string postmessage = model.ToJsonString();
UTF8Encoding encoding = new UTF8Encoding();
byte[] data = encoding.GetBytes(postmessage);
ErrorFollow.TraceWrite("获取日志详情请求", "", postmessage);
string XmlContent = CustomIO.HttpRequest(url, "POST", "text/json", null, HttpVersion.Version10, data, out ErrorMessage);
if (string.IsNullOrEmpty(ErrorMessage) == false) return;
ErrorFollow.TraceWrite("获取日志详情返回", "", XmlContent);
var model2 = JsonConvert.Deserialize<DingLogResult>(XmlContent);
if (model2.errcode == 0)
{
foreach (var item in model2.result.data_list)
{
ListResult.Add(item.Copy());
}
if (model2.result.has_more == false)
{
return;
}
model.cursor = model2.result.next_cursor;
GetLogDetail(AccessToken, model, ListResult, out ErrorMessage);
}
else
{
ErrorMessage = model2.errmsg;
}
}
#endregion
}
}

@ -0,0 +1,68 @@
using HuizhongLibrary.Log;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace HuizhongLibrary
{
public class DllInvoke
{
[DllImport("kernel32.dll")]
private extern static IntPtr LoadLibrary(String path);
[DllImport("kernel32.dll")]
private extern static IntPtr GetProcAddress(IntPtr lib, String funcName);
[DllImport("kernel32.dll")]
private extern static bool FreeLibrary(IntPtr lib);
private IntPtr hLib;
public DllInvoke(String DLLPath)
{
if (System.IO.File.Exists(DLLPath) == false)
{
ErrorFollow.TraceWrite("加载动态库错误", DLLPath, "文件不存在");
return;
}
try
{
hLib = LoadLibrary(DLLPath);
}
catch (Exception ex)
{
ErrorFollow.TraceWrite("加载动态库错误", DLLPath, ex.Message);
}
}
~DllInvoke()
{
FreeLibrary(hLib);
}
public int GetHandle()
{
return hLib.ToInt32();
}
//将要执行的函数转换为委托
public Delegate Invoke(String APIName, Type t)
{
IntPtr api = GetProcAddress(hLib, APIName);
return (Delegate)Marshal.GetDelegateForFunctionPointer(api, t);
}
public delegate int Compile(String command, StringBuilder inf);
public void test()
{
//编译
DllInvoke dll = new DllInvoke("~/Bin/Judge.dll");
Compile compile = (Compile)dll.Invoke("Compile", typeof(Compile));
//compile();//这里就是调用我的DLL里定义的Compile函数
}
}
}

@ -0,0 +1,160 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace HuizhongLibrary
{
public class EcanConvertToCh
{
//定义拼音区编码数组
private static int[] getValue = new int[]
{
-20319,-20317,-20304,-20295,-20292,-20283,-20265,-20257,-20242,-20230,-20051,-20036,
-20032,-20026,-20002,-19990,-19986,-19982,-19976,-19805,-19784,-19775,-19774,-19763,
-19756,-19751,-19746,-19741,-19739,-19728,-19725,-19715,-19540,-19531,-19525,-19515,
-19500,-19484,-19479,-19467,-19289,-19288,-19281,-19275,-19270,-19263,-19261,-19249,
-19243,-19242,-19238,-19235,-19227,-19224,-19218,-19212,-19038,-19023,-19018,-19006,
-19003,-18996,-18977,-18961,-18952,-18783,-18774,-18773,-18763,-18756,-18741,-18735,
-18731,-18722,-18710,-18697,-18696,-18526,-18518,-18501,-18490,-18478,-18463,-18448,
-18447,-18446,-18239,-18237,-18231,-18220,-18211,-18201,-18184,-18183, -18181,-18012,
-17997,-17988,-17970,-17964,-17961,-17950,-17947,-17931,-17928,-17922,-17759,-17752,
-17733,-17730,-17721,-17703,-17701,-17697,-17692,-17683,-17676,-17496,-17487,-17482,
-17468,-17454,-17433,-17427,-17417,-17202,-17185,-16983,-16970,-16942,-16915,-16733,
-16708,-16706,-16689,-16664,-16657,-16647,-16474,-16470,-16465,-16459,-16452,-16448,
-16433,-16429,-16427,-16423,-16419,-16412,-16407,-16403,-16401,-16393,-16220,-16216,
-16212,-16205,-16202,-16187,-16180,-16171,-16169,-16158,-16155,-15959,-15958,-15944,
-15933,-15920,-15915,-15903,-15889,-15878,-15707,-15701,-15681,-15667,-15661,-15659,
-15652,-15640,-15631,-15625,-15454,-15448,-15436,-15435,-15419,-15416,-15408,-15394,
-15385,-15377,-15375,-15369,-15363,-15362,-15183,-15180,-15165,-15158,-15153,-15150,
-15149,-15144,-15143,-15141,-15140,-15139,-15128,-15121,-15119,-15117,-15110,-15109,
-14941,-14937,-14933,-14930,-14929,-14928,-14926,-14922,-14921,-14914,-14908,-14902,
-14894,-14889,-14882,-14873,-14871,-14857,-14678,-14674,-14670,-14668,-14663,-14654,
-14645,-14630,-14594,-14429,-14407,-14399,-14384,-14379,-14368,-14355,-14353,-14345,
-14170,-14159,-14151,-14149,-14145,-14140,-14137,-14135,-14125,-14123,-14122,-14112,
-14109,-14099,-14097,-14094,-14092,-14090,-14087,-14083,-13917,-13914,-13910,-13907,
-13906,-13905,-13896,-13894,-13878,-13870,-13859,-13847,-13831,-13658,-13611,-13601,
-13406,-13404,-13400,-13398,-13395,-13391,-13387,-13383,-13367,-13359,-13356,-13343,
-13340,-13329,-13326,-13318,-13147,-13138,-13120,-13107,-13096,-13095,-13091,-13076,
-13068,-13063,-13060,-12888,-12875,-12871,-12860,-12858,-12852,-12849,-12838,-12831,
-12829,-12812,-12802,-12607,-12597,-12594,-12585,-12556,-12359,-12346,-12320,-12300,
-12120,-12099,-12089,-12074,-12067,-12058,-12039,-11867,-11861,-11847,-11831,-11798,
-11781,-11604,-11589,-11536,-11358,-11340,-11339,-11324,-11303,-11097,-11077,-11067,
-11055,-11052,-11045,-11041,-11038,-11024,-11020,-11019,-11018,-11014,-10838,-10832,
-10815,-10800,-10790,-10780,-10764,-10587,-10544,-10533,-10519,-10331,-10329,-10328,
-10322,-10315,-10309,-10307,-10296,-10281,-10274,-10270,-10262,-10260,-10256,-10254
};
//定义拼音数组
private static string[] getName = new string[]
{
"A","Ai","An","Ang","Ao","Ba","Bai","Ban","Bang","Bao","Bei","Ben",
"Beng","Bi","Bian","Biao","Bie","Bin","Bing","Bo","Bu","Ba","Cai","Can",
"Cang","Cao","Ce","Ceng","Cha","Chai","Chan","Chang","Chao","Che","Chen","Cheng",
"Chi","Chong","Chou","Chu","Chuai","Chuan","Chuang","Chui","Chun","Chuo","Ci","Cong",
"Cou","Cu","Cuan","Cui","Cun","Cuo","Da","Dai","Dan","Dang","Dao","De",
"Deng","Di","Dian","Diao","Die","Ding","Diu","Dong","Dou","Du","Duan","Dui",
"Dun","Duo","E","En","Er","Fa","Fan","Fang","Fei","Fen","Feng","Fo",
"Fou","Fu","Ga","Gai","Gan","Gang","Gao","Ge","Gei","Gen","Geng","Gong",
"Gou","Gu","Gua","Guai","Guan","Guang","Gui","Gun","Guo","Ha","Hai","Han",
"Hang","Hao","He","Hei","Hen","Heng","Hong","Hou","Hu","Hua","Huai","Huan",
"Huang","Hui","Hun","Huo","Ji","Jia","Jian","Jiang","Jiao","Jie","Jin","Jing",
"Jiong","Jiu","Ju","Juan","Jue","Jun","Ka","Kai","Kan","Kang","Kao","Ke",
"Ken","Keng","Kong","Kou","Ku","Kua","Kuai","Kuan","Kuang","Kui","Kun","Kuo",
"La","Lai","Lan","Lang","Lao","Le","Lei","Leng","Li","Lia","Lian","Liang",
"Liao","Lie","Lin","Ling","Liu","Long","Lou","Lu","Lv","Luan","Lue","Lun",
"Luo","Ma","Mai","Man","Mang","Mao","Me","Mei","Men","Meng","Mi","Mian",
"Miao","Mie","Min","Ming","Miu","Mo","Mou","Mu","Na","Nai","Nan","Nang",
"Nao","Ne","Nei","Nen","Neng","Ni","Nian","Niang","Niao","Nie","Nin","Ning",
"Niu","Nong","Nu","Nv","Nuan","Nue","Nuo","O","Ou","Pa","Pai","Pan",
"Pang","Pao","Pei","Pen","Peng","Pi","Pian","Piao","Pie","Pin","Ping","Po",
"Pu","Qi","Qia","Qian","Qiang","Qiao","Qie","Qin","Qing","Qiong","Qiu","Qu",
"Quan","Que","Qun","Ran","Rang","Rao","Re","Ren","Reng","Ri","Rong","Rou",
"Ru","Ruan","Rui","Run","Ruo","Sa","Sai","San","Sang","Sao","Se","Sen",
"Seng","Sha","Shai","Shan","Shang","Shao","She","Shen","Sheng","Shi","Shou","Shu",
"Shua","Shuai","Shuan","Shuang","Shui","Shun","Shuo","Si","Song","Sou","Su","Suan",
"Sui","Sun","Suo","Ta","Tai","Tan","Tang","Tao","Te","Teng","Ti","Tian",
"Tiao","Tie","Ting","Tong","Tou","Tu","Tuan","Tui","Tun","Tuo","Wa","Wai",
"Wan","Wang","Wei","Wen","Weng","Wo","Wu","Xi","Xia","Xian","Xiang","Xiao",
"Xie","Xin","Xing","Xiong","Xiu","Xu","Xuan","Xue","Xun","Ya","Yan","Yang",
"Yao","Ye","Yi","Yin","Ying","Yo","Yong","You","Yu","Yuan","Yue","Yun",
"Za", "Zai","Zan","Zang","Zao","Ze","Zei","Zen","Zeng","Zha","Zhai","Zhan",
"Zhang","Zhao","Zhe","Zhen","Zheng","Zhi","Zhong","Zhou","Zhu","Zhua","Zhuai","Zhuan",
"Zhuang","Zhui","Zhun","Zhuo","Zi","Zong","Zou","Zu","Zuan","Zui","Zun","Zuo"
};
//建立一个convertCh方法用于将汉字转换成全拼的拼音其中参数代表汉字字符串此方法的返回值是转换后的拼音字符串
/// <summary>
/// 汉字转换成全拼的拼音
/// </summary>
/// <param name="Chstr">汉字字符串</param>
/// <returns>转换后的拼音字符串</returns>
public string convertCh(string Chstr)
{
Regex reg = new Regex("^[\u4e00-\u9fa5]$");//验证是否输入汉字
byte[] arr = new byte[2];
string pystr = "";
int asc = 0, M1 = 0, M2 = 0;
char[] mChar = Chstr.ToCharArray();//获取汉字对应的字符数组
for (int j = 0; j < mChar.Length; j++)
{
//如果输入的是汉字
if (reg.IsMatch(mChar[j].ToString()))
{
arr = System.Text.Encoding.Default.GetBytes(mChar[j].ToString());
M1 = (short)(arr[0]);
M2 = (short)(arr[1]);
asc = M1 * 256 + M2 - 65536;
if (asc > 0 && asc < 160)
{
pystr += mChar[j];
}
else
{
switch (asc)
{
case -9254:
pystr += "Zhen"; break;
case -8985:
pystr += "Qian"; break;
case -5463:
pystr += "Jia"; break;
case -8274:
pystr += "Ge"; break;
case -5448:
pystr += "Ga"; break;
case -5447:
pystr += "La"; break;
case -4649:
pystr += "Chen"; break;
case -5436:
pystr += "Mao"; break;
case -5213:
pystr += "Mao"; break;
case -3597:
pystr += "Die"; break;
case -5659:
pystr += "Tian"; break;
default:
for (int i = (getValue.Length - 1); i >= 0; i--)
{
if (getValue[i] <= asc)//判断汉字的拼音区编码是否在指定范围内
{
pystr += getName[i];//如果不超出范围则获取对应的拼音
break;
}
}
break;
}
}
}
else//如果不是汉字
{
pystr += mChar[j].ToString();//如果不是汉字则返回
}
}
return pystr;//返回获取到的汉字拼音
}
}
}

@ -0,0 +1,389 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using HuizhongLibrary.Data;
using System.Data.Common;
using System.Data;
using System.Diagnostics;
namespace HuizhongLibrary.Log
{
public class ErrorFollow
{
public static bool IsDebug = true;
#region 输出错误信息
/// <summary>
/// 输出错误信息
/// </summary>
public static void TraceWrite(string TypeName, string StackTrace, string ErrorMsg)
{
if (ErrorFollow.IsDebug == false) return;
if (string.IsNullOrEmpty(ErrorMsg) == true) ErrorMsg = "消息为空字符串";
try
{
string DirectoryName = AppDomain.CurrentDomain.BaseDirectory + "ServerCookies";
if (Directory.Exists(DirectoryName) == false) Directory.CreateDirectory(DirectoryName);
string filePath = DirectoryName + "/" + DateTime.Today.ToString("yyyy-MM-dd") + "EventLog.log";
bool append = true;
if (File.Exists(filePath) == false) File.Create(filePath).Close();
FileInfo f = new FileInfo(filePath);
if (f.Length / 1024 / 1024 > 1)
{
append = false;
string newFile = DirectoryName + "/" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + "EventLog.log";
f.CopyTo(newFile, true);
}
f = null;
using (StreamWriter sw = new StreamWriter(filePath, append, System.Text.Encoding.Default))
{
sw.WriteLine("------------");
sw.WriteLine(TypeName);
sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
if (string.IsNullOrEmpty(StackTrace) == false) sw.WriteLine(StackTrace);
sw.WriteLine(ErrorMsg);
sw.Close();
}
if (ErrorMsg.Contains("OutOfMemoryException") == true)
{
string file2 = AppDomain.CurrentDomain.BaseDirectory + "自动启动服务脚本/hz.bat";
CustomIO.ReStartService(file2);
}
}
catch { }
}
#endregion
#region 输出错误信息
/// <summary>
/// 输出错误信息
/// </summary>
public static void TraceWrite2(string FileName,string TypeName, string StackTrace, string ErrorMsg)
{
if (ErrorFollow.IsDebug == false) return;
if (string.IsNullOrEmpty(ErrorMsg) == true) ErrorMsg = "消息为空字符串";
try
{
string DirectoryName = AppDomain.CurrentDomain.BaseDirectory + "ServerCookies";
if (Directory.Exists(DirectoryName) == false) Directory.CreateDirectory(DirectoryName);
string filePath = DirectoryName + "/" + FileName + DateTime.Today.ToString("yyyy-MM-dd") + "EventLog.log";
bool append = true;
if (File.Exists(filePath) == false) File.Create(filePath).Close();
FileInfo f = new FileInfo(filePath);
if (f.Length / 1024 / 1024 > 1)
{
append = false;
string newFile = DirectoryName + "/" + FileName + DateTime.Now.ToString("yyyyMMdd_HHmmss") + "EventLog.log";
f.CopyTo(newFile, true);
}
f = null;
using (StreamWriter sw = new StreamWriter(filePath, append, System.Text.Encoding.Default))
{
sw.WriteLine("------------");
sw.WriteLine(TypeName);
sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
if (string.IsNullOrEmpty(StackTrace) == false) sw.WriteLine(StackTrace);
sw.WriteLine(ErrorMsg);
sw.Close();
}
if (ErrorMsg.Contains("OutOfMemoryException") == true)
{
string file2 = AppDomain.CurrentDomain.BaseDirectory + "自动启动服务脚本/hz.bat";
CustomIO.ReStartService(file2);
}
}
catch { }
}
#endregion
#region 输出错误信息_并且保存到数据库
/// <summary>
/// 输出错误信息_并且保存到数据库
/// </summary>
public static void TraceWriteError(string TypeName, Exception ex, string DataMsg)
{
if (string.IsNullOrEmpty(DataMsg) == true && ex == null) DataMsg = "消息为空字符串";
try
{
string DirectoryName = AppDomain.CurrentDomain.BaseDirectory + "ServerCookies";
if (Directory.Exists(DirectoryName) == false) Directory.CreateDirectory(DirectoryName);
string filePath = DirectoryName + "/" + DateTime.Today.ToString("yyyy-MM-dd") + "EventLog.log";
bool append = true;
if (File.Exists(filePath) == false) File.Create(filePath).Close();
FileInfo f = new FileInfo(filePath);
if (f.Length / 1024 / 1024 > 1)
{
append = false;
string newFile = DirectoryName + "/" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + "EventLog.log";
f.CopyTo(newFile, true);
}
f = null;
using (StreamWriter sw = new StreamWriter(filePath, append, System.Text.Encoding.Default))
{
sw.WriteLine("------------");
sw.WriteLine(TypeName);
sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
if (ex != null)
{
if (string.IsNullOrEmpty(ex.StackTrace) == false) sw.WriteLine(ex.StackTrace);
sw.WriteLine(ex.Message);
}
if (string.IsNullOrEmpty(DataMsg) == false) sw.WriteLine(DataMsg);
sw.Close();
}
string tsql = @"
if (select count(0) from PD_ErrorLog where TypeName=@TypeName and ErrorMsg=@ErrorMsg and DATEDIFF(s,InDate,getdate())<300)=0
begin
INSERT INTO [PD_ErrorLog]([TypeName],[StackTrace],[ErrorMsg],[DataMsg],[InDate])values(@TypeName,@StackTrace,@ErrorMsg,@DataMsg,getdate())
end
";
Database db = DatabaseFactory.CreateDatabase();
DbCommand cmd = db.GetSqlStringCommand(tsql);
db.AddInParameter(cmd, "@TypeName", DbType.String, TypeName);
string StackTrace = "";
string ErrorMsg = "";
if (ex != null)
{
StackTrace = ex.StackTrace;
ErrorMsg = ex.Message;
}
if (ErrorMsg == "") ErrorMsg = DataMsg;
db.AddInParameter(cmd, "@StackTrace", DbType.String, StackTrace);
db.AddInParameter(cmd, "@ErrorMsg", DbType.String, ErrorMsg);
db.AddInParameter(cmd, "@DataMsg", DbType.String, DataMsg);
try
{
db.ExecuteNonQuery(cmd);
}
catch
{ }
}
catch { }
}
#endregion
#region 输出10.4挂号收费信息
/// <summary>
/// 输出错误信息
/// </summary>
public static void TraceWrite_GH(string TypeName, string StackTrace, string ErrorMsg)
{
if (ErrorFollow.IsDebug == false) return;
if (string.IsNullOrEmpty(ErrorMsg) == true) ErrorMsg = "消息为空字符串";
try
{
string DirectoryName = AppDomain.CurrentDomain.BaseDirectory + "ServerCookies";
if (Directory.Exists(DirectoryName) == false) Directory.CreateDirectory(DirectoryName);
string filePath = DirectoryName + "/" + DateTime.Today.ToString("yyyy-MM-dd") + "挂号收费日志.log";
bool append = true;
if (File.Exists(filePath) == false) File.Create(filePath).Close();
FileInfo f = new FileInfo(filePath);
if (f.Length / 1024 / 1024 > 1)
{
append = false;
string newFile = DirectoryName + "/" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + "EventLog.log";
f.CopyTo(newFile, true);
}
f = null;
using (StreamWriter sw = new StreamWriter(filePath, append, System.Text.Encoding.Default))
{
sw.WriteLine("------------");
sw.WriteLine(TypeName);
sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
if (string.IsNullOrEmpty(StackTrace) == false) sw.WriteLine(StackTrace);
sw.WriteLine(ErrorMsg);
sw.Close();
}
}
catch { }
}
#endregion
#region 输出错误信息
/// <summary>
/// 输出错误信息
/// </summary>
public static void TraceWrite(string filePath, string TypeName, string StackTrace, string ErrorMsg)
{
if (ErrorFollow.IsDebug == false) return;
if (string.IsNullOrEmpty(ErrorMsg) == true) ErrorMsg = "未知错误";
try
{
bool append = true;
if (File.Exists(filePath) == false) File.Create(filePath).Close();
FileInfo f = new FileInfo(filePath);
if (f.Length / 1024 / 32 > 10) append = false;
f = null;
using (StreamWriter sw = new StreamWriter(filePath, append, System.Text.Encoding.Default))
{
sw.WriteLine("------------");
sw.WriteLine(TypeName);
sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
sw.WriteLine(StackTrace);
sw.WriteLine(ErrorMsg);
sw.Close();
}
if (ErrorMsg.Contains("OutOfMemoryException") == true)
{
string file2 = AppDomain.CurrentDomain.BaseDirectory + "自动启动服务脚本/hz.bat";
CustomIO.ReStartService(file2);
}
}
catch { }
}
#endregion
#region 清理错误日志
public static void DeleteLog(int Day)
{
Action<int> act = new Action<int>(DeleteTempFile);
act.BeginInvoke(Day, null, null);
}
public static void DeleteTempFile(int Day)
{
try
{
string DirectoryName = AppDomain.CurrentDomain.BaseDirectory + "ServerCookies/";
if (Directory.Exists(DirectoryName) == false) return;
//string[] files = Directory.GetFiles(DirectoryName, "*.*");
//foreach (string filePath in files)
//{
// DateTime dt = File.GetCreationTime(filePath);
// if (dt.AddDays(Day) > DateTime.Now) continue;
// File.Delete(filePath);
//}
DeleteFile(DirectoryName, Day);
}
catch (Exception ex)
{
ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message);
}
}
#region 删除文件夹及下面所有文件
public static void DeleteFile(string Directory,int Day)
{
ErrorFollow obj = new ErrorFollow();
obj.DeleteFileTree(Directory, true, 0, Day);
foreach (string s in obj.files)
{
System.IO.Directory.Delete(s);
TraceWrite("删除临时日志文件", "", s);
}
}
List<string> files = new List<string>();
void DeleteFileTree(string dir, bool showFiles, int level, int Day)
{
try
{
if (showFiles == true)
{
foreach (string fname in Directory.GetFiles(dir))
{
DateTime dt = File.GetLastWriteTime(fname);
if (dt.AddDays(Day) > DateTime.Now) continue;
System.IO.File.Delete(fname);
TraceWrite("删除临时日志文件", "", fname);
}
}
foreach (string subdir in Directory.GetDirectories(dir))
{
DeleteFileTree(subdir, showFiles, level + 1,Day);
string[] files2 = Directory.GetFiles(subdir, "*.*");
if (files2.Length==0) files.Add(subdir);
}
}
catch
{}
}
#endregion
#endregion
#region 输出接口信息
/// <summary>
/// 输出接口信息
/// </summary>
public static void TraceInfoWrite(string TypeName, string StackTrace, string ErrorMsg)
{
if (ErrorFollow.IsDebug == false) return;
if (string.IsNullOrEmpty(ErrorMsg) == true) ErrorMsg = "消息为空字符串";
try
{
string DirectoryName = AppDomain.CurrentDomain.BaseDirectory + "ServerCookies";
if (Directory.Exists(DirectoryName) == false) Directory.CreateDirectory(DirectoryName);
string filePath = DirectoryName + "/" + DateTime.Today.ToString("yyyy-MM-dd") + "EventInfoLog.log";
bool append = true;
if (File.Exists(filePath) == false) File.Create(filePath).Close();
FileInfo f = new FileInfo(filePath);
if (f.Length / 1024 / 1024 > 1)
{
append = false;
string newFile = DirectoryName + "/" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + "EventInfoLog.log";
f.CopyTo(newFile, true);
}
f = null;
using (StreamWriter sw = new StreamWriter(filePath, append, System.Text.Encoding.Default))
{
sw.WriteLine("------------");
sw.WriteLine(TypeName);
sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
if (string.IsNullOrEmpty(StackTrace) == false) sw.WriteLine(StackTrace);
sw.WriteLine(ErrorMsg);
sw.Close();
}
}
catch { }
}
#endregion
#region 日志文件保存数据库
public static void SaveEventLog(string DeviceNo, DateTime InDate)
{
string InDate2 = InDate.ToString("yyyy-MM-dd");
string dir = AppDomain.CurrentDomain.BaseDirectory + "ServerCookies";
string[] files = Directory.GetFiles(dir, "*.log");
foreach (string filePath in files)
{
DateTime dt = File.GetCreationTime(filePath);
string dt2 = dt.ToString("yyyy-MM-dd");
if (dt2 != InDate2) continue;
byte[] bytes = CustomIO.GetOffice(filePath);
SaveEventLogData(DeviceNo, dt, bytes);
}
}
public static void SaveEventLogData(string DeviceNo,DateTime CreateTime,byte[] bytes)
{
string tsql = @"
select id from PD_EventLog where DeviceNo=@DeviceNo and InDate=@InDate
";
Database db = DatabaseFactory.CreateDatabase();
DbCommand cmd = db.GetSqlStringCommand(tsql);
db.AddInParameter(cmd, "@DeviceNo", DbType.String, DeviceNo);
db.AddInParameter(cmd, "@InDate", DbType.DateTime, CreateTime);
string a =Convert.ToString(db.ExecuteScalar(cmd));
if (string.IsNullOrEmpty(a) == true)
{
tsql = @"
insert PD_EventLog(DeviceNo,Filelog,InDate)values(@DeviceNo,@Filelog,@InDate)
";
cmd = db.GetSqlStringCommand(tsql);
db.AddInParameter(cmd, "@DeviceNo", DbType.String, DeviceNo);
db.AddInParameter(cmd, "@InDate", DbType.DateTime, CreateTime);
db.AddInParameter(cmd, "@Filelog", DbType.Binary, bytes);
db.ExecuteNonQuery(cmd);
}
else
{
tsql = @"
update PD_EventLog set Filelog=@Filelog where id=@id
";
cmd = db.GetSqlStringCommand(tsql);
db.AddInParameter(cmd, "@id", DbType.Int32, a);
db.AddInParameter(cmd, "@Filelog", DbType.Binary, bytes);
db.ExecuteNonQuery(cmd);
}
}
#endregion
}
}

@ -0,0 +1,460 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using HuizhongLibrary.Data;
using HuizhongLibrary.Log;
namespace HuizhongLibrary
{
/// <summary>
/// DataTable扩展
/// </summary>
public static class DataTableExtension
{
#region DataTable转List
/// <summary>
/// DataTable转List
/// </summary>
/// <param name="obj">扩展对象</param>
public static List<T> ToList<T>(this DataTable tb)
{
if (tb == null || tb.Rows.Count == 0) return null;
//获取对象所有属性
Type t = typeof(T);
List<T> ListModel = new List<T>();
PropertyInfo[] propertyInfo = t.GetProperties();
bool bk = false;
string json = "";
if (propertyInfo.Length > 0)
{
#region 全部是属性
for (int i = 0; i < tb.Rows.Count; i++)
{
//创建泛型对象
DataRow row = tb.Rows[i];
T model = Activator.CreateInstance<T>();
for (int j = 0; j < tb.Columns.Count; j++)
{
foreach (PropertyInfo info in propertyInfo)
{
//属性名称和列名相同时赋值
if (tb.Columns[j].ColumnName.ToUpper().Equals(info.Name.ToUpper()))
{
bk = SetPropertyValue(model, info, row[j]);
if (bk == false)
{
json = row.ToJson();
ErrorFollow.TraceWrite("转换错误", "行信息", json);
break;
}
}
}
}
ListModel.Add(model);
}
#endregion
}
else
{
#region 全部是字段
FieldInfo[] fieldinfo = t.GetFields();
for (int i = 0; i < tb.Rows.Count; i++)
{
//创建泛型对象
DataRow row = tb.Rows[i];
T model = Activator.CreateInstance<T>();
for (int j = 0; j < tb.Columns.Count; j++)
{
foreach (FieldInfo info in fieldinfo)
{
//属性名称和列名相同时赋值
if (tb.Columns[j].ColumnName.ToUpper().Equals(info.Name.ToUpper()))
{
bk = SetFieldValue(model, info, row[j]);
if (bk == false)
{
json = row.ToJson();
ErrorFollow.TraceWrite("转换错误", "行信息", json);
break;
}
}
}
}
ListModel.Add(model);
}
#endregion
}
return ListModel;
}
#endregion
#region 转换DataRow为Model
public static T ToModel<T>(this DataRow row)
{
//获取对象所有属性
DataTable tb = row.Table;
Type t = typeof(T);
T model = Activator.CreateInstance<T>();
PropertyInfo[] propertyInfo = t.GetProperties();
bool bk = false;
string json = "";
if (propertyInfo.Length > 0)
{
for (int j = 0; j < tb.Columns.Count; j++)
{
foreach (PropertyInfo info in propertyInfo)
{
//属性名称和列名相同时赋值
if (tb.Columns[j].ColumnName.ToUpper().Equals(info.Name.ToUpper()))
{
bk=SetPropertyValue(model, info, row[j]);
if (bk == false)
{
json = row.ToJson();
ErrorFollow.TraceWrite("转换错误", "行信息", json);
break;
}
}
}
}
}
else
{
FieldInfo[] fieldinfo = t.GetFields();
for (int j = 0; j < tb.Columns.Count; j++)
{
foreach (FieldInfo info in fieldinfo)
{
//属性名称和列名相同时赋值
if (tb.Columns[j].ColumnName.ToUpper().Equals(info.Name.ToUpper()))
{
bk=SetFieldValue(model, info, row[j]);
if (bk == false)
{
json = row.ToJson();
ErrorFollow.TraceWrite("转换错误", "行信息", json);
break;
}
}
}
}
}
return model;
}
#endregion
#region 属性赋值
public static bool SetPropertyValue<T>(T model,PropertyInfo info,object value)
{
if (value == DBNull.Value || value == null)
{
info.SetValue(model, null, null);
return true;
}
if (info.PropertyType == typeof(byte[]))
{
info.SetValue(model, (byte[])value, null);
return true;
}
string val = Convert.ToString(value);
if (val == "")
{
if (info.PropertyType == typeof(string))
{
info.SetValue(model, Convert.ToString(val), null);
}
else
{
info.SetValue(model, null, null);
}
return true;
}
try
{
if (info.PropertyType == typeof(byte) || info.PropertyType == typeof(Nullable<byte>))
{
info.SetValue(model, Convert.ToByte(val), null);
}
else if (info.PropertyType == typeof(Int16) || info.PropertyType == typeof(Nullable<Int16>))
{
info.SetValue(model, Convert.ToInt16(val), null);
}
else if (info.PropertyType == typeof(int) || info.PropertyType == typeof(Nullable<int>))
{
info.SetValue(model, Convert.ToInt32(val), null);
}
else if (info.PropertyType == typeof(Int64) || info.PropertyType == typeof(Nullable<Int64>))
{
info.SetValue(model, Convert.ToInt64(val), null);
}
else if (info.PropertyType == typeof(bool) || info.PropertyType == typeof(Nullable<bool>))
{
if (val == "True" || val == "False")
{
info.SetValue(model, Convert.ToBoolean(val), null);
}
else
{
int valbool = Convert.ToInt32(val);
info.SetValue(model, Convert.ToBoolean(valbool), null);
}
}
else if (info.PropertyType == typeof(decimal) || info.PropertyType == typeof(Nullable<decimal>))
{
info.SetValue(model, Convert.ToDecimal(val), null);
}
else if (info.PropertyType == typeof(Double) || info.PropertyType == typeof(Nullable<Double>))
{
info.SetValue(model, Convert.ToDouble(val), null);
}
else if (info.PropertyType == typeof(Single) || info.PropertyType == typeof(Nullable<Single>))
{
info.SetValue(model, Convert.ToSingle(val), null);
}
else if (info.PropertyType == typeof(DateTime) || info.PropertyType == typeof(Nullable<DateTime>))
{
info.SetValue(model, Convert.ToDateTime(val), null);
}
else
{
info.SetValue(model, Convert.ToString(val), null);
}
return true;
}
catch (Exception ex)
{
string str = "列名="+ info.Name+",内容="+ val;
ErrorFollow.TraceWrite("数据格式转换错误", "", str);
ErrorFollow.TraceWrite(ex.TargetSite.Name,ex.StackTrace, ex.Message);
}
return false;
}
#endregion
#region 字段赋值
public static bool SetFieldValue<T>(T model, FieldInfo info, object value)
{
if (value == DBNull.Value || value == null)
{
info.SetValue(model, null);
return true;
}
if (info.FieldType == typeof(byte[]))
{
info.SetValue(model, (byte[])value);
return true;
}
string val = Convert.ToString(value);
if (val == "")
{
if (info.FieldType == typeof(string))
{
info.SetValue(model, Convert.ToString(val));
}
else
{
info.SetValue(model, null);
}
return true;
}
try
{
if (info.FieldType == typeof(byte) || info.FieldType == typeof(Nullable<byte>))
{
info.SetValue(model, Convert.ToByte(val));
}
else if (info.FieldType == typeof(Int16) || info.FieldType == typeof(Nullable<Int16>))
{
info.SetValue(model, Convert.ToInt16(val));
}
else if (info.FieldType == typeof(int) || info.FieldType == typeof(Nullable<int>))
{
info.SetValue(model, Convert.ToInt32(val));
}
else if (info.FieldType == typeof(Int64) || info.FieldType == typeof(Nullable<Int64>))
{
info.SetValue(model, Convert.ToInt64(val));
}
else if (info.FieldType == typeof(bool) || info.FieldType == typeof(Nullable<bool>))
{
if (val == "True" || val == "False")
{
info.SetValue(model, Convert.ToBoolean(val));
}
else
{
int valbool = Convert.ToInt32(val);
info.SetValue(model, Convert.ToBoolean(valbool));
}
}
else if (info.FieldType == typeof(decimal) || info.FieldType == typeof(Nullable<decimal>))
{
info.SetValue(model, Convert.ToDecimal(val));
}
else if (info.FieldType == typeof(Double) || info.FieldType == typeof(Nullable<Double>))
{
info.SetValue(model, Convert.ToDouble(val));
}
else if (info.FieldType == typeof(Single) || info.FieldType == typeof(Nullable<Single>))
{
info.SetValue(model, Convert.ToSingle(val));
}
else if (info.FieldType == typeof(DateTime) || info.FieldType == typeof(Nullable<DateTime>))
{
info.SetValue(model, Convert.ToDateTime(val));
}
else
{
info.SetValue(model, Convert.ToString(val));
}
return true;
}
catch (Exception ex)
{
string str = "列名=" + info.Name + ",内容=" + val;
ErrorFollow.TraceWrite("数据格式转换错误", "", str);
ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message);
}
return false;
}
#endregion
#region DataTable转Json
public static string ToJson(this DataTable tb)
{
if (tb.Rows.Count == 0) return "";
DateTime time = new DateTime(0x7b2, 1, 1, 0, 0, 0, DateTimeKind.Utc);
long DatetimeMinTimeTicks = time.Ticks;
string s = "[";
foreach (DataRow row in tb.Rows)
{
string a = "{";
foreach (DataColumn col in tb.Columns)
{
if (col.ExtendedProperties.Contains("NoJson") == true) continue;
if (row.IsNull(col.ColumnName) == true)
{
a += "\"" + col.ColumnName + "\":null,";
continue;
}
if (col.DataType == typeof(string) || col.DataType == typeof(System.Guid))
{
string vvv = row[col.ColumnName].ToString();
vvv = vvv.Replace("\r\n", "\\r\\n").Replace("\n", "\\n");
a += "\"" + col.ColumnName + "\":\"" + vvv + "\",";
continue;
}
if (col.DataType == typeof(DateTime))
{
DateTime datetime = Convert.ToDateTime(row[col.ColumnName]);
a += "\"" + col.ColumnName + "\":\"\\/Date(" + (long)((datetime.ToUniversalTime().Ticks - DatetimeMinTimeTicks) / 0x2710) + ")\\/\",";
continue;
}
if (col.DataType == typeof(bool))
{
a += "\"" + col.ColumnName + "\":" + row[col.ColumnName].ToString().ToLower() + ",";
continue;
}
if (col.DataType == typeof(Int64))
{
a += "\"" + col.ColumnName + "\":\"" + row[col.ColumnName] + "\",";
continue;
}
if (col.DataType == typeof(decimal))
{
a += "\"" + col.ColumnName + "\":" + Convert.ToDecimal(row[col.ColumnName]).ToString("0.#########") + ",";
continue;
}
if (col.DataType == typeof(Int32) || col.DataType == typeof(Int16) || col.DataType == typeof(float) || col.DataType == typeof(short))
{
a += "\"" + col.ColumnName + "\":" + row[col.ColumnName] + ",";
continue;
}
}
a = a.Remove(a.Length - 1);
a += "},";
s += a;
}
s = s.Remove(s.Length - 1);
s += "]";
return s;
}
#endregion
#region 转换DataRow为Json
public static string ToJson(this DataRow row)
{
DateTime time = new DateTime(0x7b2, 1, 1, 0, 0, 0, DateTimeKind.Utc);
long DatetimeMinTimeTicks = time.Ticks;
string a = "{";
foreach (DataColumn col in row.Table.Columns)
{
if (col.ExtendedProperties.Contains("NoJson") == true) continue;
if (row.IsNull(col.ColumnName) == true)
{
a += "\"" + col.ColumnName + "\":null,";
continue;
}
if (col.DataType == typeof(string) || col.DataType == typeof(System.Guid))
{
string vvv = row[col.ColumnName].ToString();
vvv = vvv.Replace("\r\n", "\\r\\n").Replace("\n", "\\n");
a += "\"" + col.ColumnName + "\":\"" + vvv + "\",";
continue;
}
if (col.DataType == typeof(DateTime))
{
DateTime datetime = Convert.ToDateTime(row[col.ColumnName]);
a += "\"" + col.ColumnName + "\":\"\\/Date(" + (long)((datetime.ToUniversalTime().Ticks - DatetimeMinTimeTicks) / 0x2710) + ")\\/\",";
continue;
}
if (col.DataType == typeof(bool))
{
a += "\"" + col.ColumnName + "\":" + row[col.ColumnName].ToString().ToLower() + ",";
continue;
}
if (col.DataType == typeof(Int64))
{
a += "\"" + col.ColumnName + "\":\"" + row[col.ColumnName] + "\",";
continue;
}
if (col.DataType == typeof(decimal))
{
a += "\"" + col.ColumnName + "\":" + Convert.ToDecimal(row[col.ColumnName]).ToString("0.#########") + ",";
continue;
}
if (col.DataType == typeof(Int32) || col.DataType == typeof(Int16) || col.DataType == typeof(float) || col.DataType == typeof(short))
{
a += "\"" + col.ColumnName + "\":" + row[col.ColumnName] + ",";
continue;
}
}
a = a.Remove(a.Length - 1);
a += "}";
return a;
}
#endregion
#region DataTable转JavaDataTable
public static JavaDataTable ToJavaDataTable(this DataTable tb)
{
var tb2 = new JavaDataTable();
foreach (DataColumn item in tb.Columns)
{
tb2.Columns.Add(new JavaDataTableColumn { ColumnName = item.ColumnName });
}
foreach (DataRow item in tb.Rows)
{
var row = new JavaDataTableRow();
row.ItemArray = item.ItemArray.ToList<object>();
tb2.Rows.Add(row);
}
return tb2;
}
#endregion
}
}

@ -0,0 +1,207 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;
using System.IO;
using System.Reflection;
using System.Data;
using System.Collections;
using System.Xml.Serialization;
using System.Xml;
using Newtonsoft.Json;
namespace HuizhongLibrary
{
public static class ListExtension
{
#region 复制
public static T Copy<T>(this Object obj)
{
var ss = JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(obj));
return ss;
}
#endregion
#region 转JSON文件
/// <summary>
/// 转JSON文件
/// </summary>
/// <param name="obj">扩展对象</param>
/// <param name="filePath">文件路径</param>
public static void ToJSON(this Object obj, string filePath)
{
//string jsonString = new JavaScriptSerializer().Serialize(obj);
string jsonString = JsonConvert.SerializeObject(obj);
string DirectoryName = Path.GetDirectoryName(filePath);
if (System.IO.Directory.Exists(DirectoryName) == false) System.IO.Directory.CreateDirectory(DirectoryName);
string fileName = Path.GetFileName(filePath);
File.WriteAllText(filePath, jsonString);
}
#endregion
#region 转JSON字符串
/// <summary>
/// 转JSON字符串
/// </summary>
/// <param name="obj">扩展对象</param>
public static string ToJsonString(this Object obj)
{
if (obj == null) return "";
string jsonString = JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.None);
//string jsonString = new JavaScriptSerializer().Serialize(obj);
return jsonString;
}
#endregion
#region 转JSON字符串
/// <summary>
/// 转JSON字符串
/// </summary>
/// <param name="obj">扩展对象</param>
public static string ToXmlString(this string obj)
{
if (obj == null) return "";
XmlSerializer mySerializer = new XmlSerializer(obj.GetType());
MemoryStream ms = new MemoryStream();
mySerializer.Serialize(ms, obj);
XmlDocument doc = new XmlDocument();
doc.LoadXml(Encoding.UTF8.GetString(ms.ToArray()));
if (doc.DocumentElement != null)
{
return doc.DocumentElement.InnerXml;
}
else
{
return obj.ToString();
}
}
#endregion
#region List转DataTable
/// <summary>
/// List转DataTable
/// </summary>
/// <typeparam name="TResult">对象</typeparam>
/// <param name="ListModel">扩展对象</param>
/// <returns></returns>
public static DataTable ToDataTable<TResult>(this IEnumerable<TResult> ListModel) where TResult : class
{
//创建属性的集合
List<PropertyInfo> pList = new List<PropertyInfo>();
//获得反射的入口
Type type = typeof(TResult);
DataTable dt = new DataTable();
//把所有的public属性加入到集合 并添加DataTable的列
Array.ForEach<PropertyInfo>(type.GetProperties(), item =>
{
pList.Add(item);
Type columnType = item.PropertyType;
if (item.PropertyType.IsGenericType && item.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
columnType = item.PropertyType.GetGenericArguments()[0];
}
dt.Columns.Add(new DataColumn(item.Name, columnType));
});
foreach (var model in ListModel)
{
//创建一个DataRow实例
DataRow row = dt.NewRow();
//给row 赋值
pList.ForEach(item =>
{
object value = item.GetValue(model, null);
if (value != null) row[item.Name] = value;
});
//加入到DataTable
dt.Rows.Add(row);
}
return dt;
}
#endregion
#region List序列化Json
public static string ToJson<TResult>(this IEnumerable<TResult> list, List<string> ListSerializePropertieName) where TResult : class
{
//创建属性的集合
List<PropertyInfo> pList = new List<PropertyInfo>();
//获得反射的入口
Type type = typeof(TResult);
DataTable dt = new DataTable();
//把所有的public属性加入到集合 并添加DataTable的列
Array.ForEach<PropertyInfo>(type.GetProperties(), item =>
{
pList.Add(item);
Type columnType = item.PropertyType;
if (item.PropertyType.IsGenericType && item.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
columnType = item.PropertyType.GetGenericArguments()[0];
}
dt.Columns.Add(new DataColumn(item.Name, columnType));
});
DateTime time = new DateTime(0x7b2, 1, 1, 0, 0, 0, DateTimeKind.Utc);
JavaScriptSerializer parseJSON = new JavaScriptSerializer();
long DatetimeMinTimeTicks = time.Ticks;
string JsonResult = "[{";
List<TResult> ListModel = new List<TResult>();
foreach (var model in ListModel)
{
foreach (var item in pList)
{
if (ListSerializePropertieName.Contains(item.Name) == false) continue;
object value = item.GetValue(model, null);
if (value == null)
{
JsonResult += "\"" + item.Name + "\":null,";
continue;
}
Type columnType = item.PropertyType;
if (item.PropertyType.IsGenericType && item.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
columnType = item.PropertyType.GetGenericArguments()[0];
}
if (columnType == typeof(string))
{
string vvv = value.ToString();
vvv = vvv.Replace("\r\n", "\\r\\n").Replace("\n", "\\n");
JsonResult += "\"" + item.Name + "\":\"" + vvv + "\",";
continue;
}
if (columnType == typeof(DateTime))
{
DateTime datetime = Convert.ToDateTime(value);
JsonResult += "\"" + item.Name + "\":\"\\/Date(" + (long)((datetime.ToUniversalTime().Ticks - DatetimeMinTimeTicks) / 0x2710) + ")\\/\",";
continue;
}
if (columnType == typeof(bool))
{
JsonResult += "\"" + item.Name + "\":" + value.ToString().ToLower() + ",";
continue;
}
if (columnType == typeof(Int64))
{
JsonResult += "\"" + item.Name + "\":\"" + value + "\",";
continue;
}
if (columnType == typeof(decimal))
{
JsonResult += "\"" + item.Name + "\":\"" + Convert.ToDecimal(value).ToString("0.#########") + "\",";
continue;
}
if (columnType == typeof(Int32) || columnType == typeof(Int16) || columnType == typeof(float) || columnType == typeof(short))
{
JsonResult += "\"" + item.Name + "\":" + value + ",";
continue;
}
JsonResult += "\"" + item.Name + "\":" + parseJSON.Serialize(value) + ",";
}
}
return JsonResult;
}
#endregion
}
}

@ -0,0 +1,36 @@
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script>
var aaa=
"<div id='DataGrid_PT_Page' style='width: 100%;'>"
+"<table cellspacing='0' cellpadding='0' border='0' align=''>"
+" <tbody>"
+" <tr> "
+" <td style='border-style: none;'>"
+" <select id='DataGrid_PT_Page_listPageSize' class='easyui-combobox combobox-f combo-f' editable='false' style='width: 50px; display: none;'></select><span class='combo'><input type='text' class='combo-text validatebox-text' autocomplete='off' readonly='' style='width: 30px;"><span><span class='combo-arrow'></span></span><input type='hidden' class='combo-value' value='60'></span></td>"
+" <td style='border-style: none;'><a id='DataGrid_PT_Page_FirstButton' href='#' class='easyui-linkbutton l-btn l-btn-plain' plain='true' iconcls='icon-first'><span class='l-btn-left'><span class='l-btn-text'><span class='l-btn-empty icon-first'>&nbsp;</span></span></span></a></td>"
+" <td style='border-style: none;'><a id='DataGrid_PT_Page_PrevButton' href='#' class='easyui-linkbutton l-btn l-btn-plain' plain='true' iconcls='icon-prev'><span class='l-btn-left'><span class='l-btn-text'><span class='l-btn-empty icon-prev'>&nbsp;</span></span></span></a></td>"
+" <td style='border-style: none;'><a id='DataGrid_PT_Page_NextButton' href='#' class='easyui-linkbutton l-btn l-btn-plain' plain='true' iconcls='icon-next'><span class='l-btn-left'><span class='l-btn-text'><span class='l-btn-empty icon-next'>&nbsp;</span></span></span></a></td>"
+" <td style='border-style: none;'><a id='DataGrid_PT_Page_LastButton' href='#' class='easyui-linkbutton l-btn l-btn-plain' plain='true' iconcls='icon-last'><span class='l-btn-left'><span class='l-btn-text'><span class='l-btn-empty icon-last'>&nbsp;</span></span></span></a></td>"
+" <td style='border-style: none;'><span></span></td>"
+" <td style='border-style: none;'>"
+" <input id='DataGrid_PT_Page_PageIndex' style='width: 50px; text-align: center;' class='easyui-numberbox validatebox-text' min='1' max='1' precision='0' value='1'></td>"
+" <td style='border-style: none;'><span id='DataGrid_PT_Page_PageTitle'>共0页,0条记录</span></td>"
+" </tr>"
+" </tbody>"
+" </table>"
+"</div>"
</script>
</head>
<body>
</body>
</html>

@ -0,0 +1,136 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Runtime.InteropServices.ComTypes;
using System.Windows.Forms;
using System.IO;
namespace HuizhongLibrary
{
public class HtmlCapture
{
#region html转图片
public static void ConverUrl(string url, string imgSavePath, int Width, int Height)
{
string ImagePath = string.Empty;
WebBrowser web = new WebBrowser();
web.Navigate(url);
while (web.ReadyState != WebBrowserReadyState.Complete)
{
System.Windows.Forms.Application.DoEvents();
}
Rectangle screen = Screen.PrimaryScreen.Bounds;
Size? imgsize = null;
//set the webbrowser width and hight
if (Width == 0)
{
web.Width = screen.Width;
web.Height = screen.Height;
}
else
{
web.Width = Width;
web.Height = Height;
}
//suppress script errors and hide scroll bars
web.ScriptErrorsSuppressed = true;
web.ScrollBarsEnabled = false;
Rectangle body = web.Document.Body.ScrollRectangle;
//check if the document width/height is greater than screen width/height
Rectangle docRectangle = new Rectangle()
{
Location = new Point(0, 0),
Size = new Size(body.Width > web.Width ? body.Width : web.Width,
body.Height > web.Height ? body.Height : web.Height)
};
//set the width and height of the WebBrowser object
web.Width = docRectangle.Width;
web.Height = docRectangle.Height;
//if the imgsize is null, the size of the image will
//be the same as the size of webbrowser object
//otherwise set the image size to imgsize
Rectangle imgRectangle;
if (imgsize == null)
imgRectangle = docRectangle;
else
imgRectangle = new Rectangle()
{
Location = new Point(0, 0),
Size = imgsize.Value
};
//create a bitmap object
Bitmap bitmap = new Bitmap(imgRectangle.Width - 24, imgRectangle.Height);
//get the viewobject of the WebBrowser
IViewObject ivo = web.Document.DomDocument as IViewObject;
using (Graphics g = Graphics.FromImage(bitmap))
{
//get the handle to the device context and draw
IntPtr hdc = g.GetHdc();
ivo.Draw(1, -1, IntPtr.Zero, IntPtr.Zero,
IntPtr.Zero, hdc, ref imgRectangle,
ref docRectangle, IntPtr.Zero, 0);
g.ReleaseHdc(hdc);
}
bitmap.Save(imgSavePath, System.Drawing.Imaging.ImageFormat.Jpeg);
bitmap.Dispose();
web.Dispose();
}
#endregion
#region html文档转图片
public static void ConverHTML(string html, string imgSavePath, int Width, int Height)
{
string dir = AppDomain.CurrentDomain.BaseDirectory + "ServerCookies";
if (Directory.Exists(dir) == false) Directory.CreateDirectory(dir);
string tempPath = dir + "/" + Guid.NewGuid().ToString() + ".html";
if (File.Exists(tempPath) == false) File.Create(tempPath).Close();
File.AppendAllText(tempPath, html);
ConverUrl(tempPath, imgSavePath, Width, Height);
File.Delete(tempPath);
}
#endregion
}
#region==========IViewObje【实现接口类】================
[ComVisible(true), ComImport()]
[GuidAttribute("0000010d-0000-0000-C000-000000000046")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
public interface IViewObject
{
[return: MarshalAs(UnmanagedType.I4)]
[PreserveSig]
int Draw(
[MarshalAs(UnmanagedType.U4)] UInt32 dwDrawAspect,
int lindex,
IntPtr pvAspect,
[In] IntPtr ptd,
IntPtr hdcTargetDev,
IntPtr hdcDraw,
[MarshalAs(UnmanagedType.Struct)] ref Rectangle lprcBounds,
[MarshalAs(UnmanagedType.Struct)] ref Rectangle lprcWBounds,
IntPtr pfnContinue,
[MarshalAs(UnmanagedType.U4)] UInt32 dwContinue);
[PreserveSig]
int GetColorSet([In, MarshalAs(UnmanagedType.U4)] int dwDrawAspect,
int lindex, IntPtr pvAspect, [In] IntPtr ptd,
IntPtr hicTargetDev, [Out] IntPtr ppColorSet);
[PreserveSig]
int Freeze([In, MarshalAs(UnmanagedType.U4)] int dwDrawAspect,
int lindex, IntPtr pvAspect, [Out] IntPtr pdwFreeze);
[PreserveSig]
int Unfreeze([In, MarshalAs(UnmanagedType.U4)] int dwFreeze);
void SetAdvise([In, MarshalAs(UnmanagedType.U4)] int aspects,
[In, MarshalAs(UnmanagedType.U4)] int advf,
[In, MarshalAs(UnmanagedType.Interface)] IAdviseSink pAdvSink);
void GetAdvise([In, Out, MarshalAs(UnmanagedType.LPArray)] int[] paspects,
[In, Out, MarshalAs(UnmanagedType.LPArray)] int[] advf,
[In, Out, MarshalAs(UnmanagedType.LPArray)] IAdviseSink[] pAdvSink);
}
#endregion
}

@ -0,0 +1,369 @@

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
namespace HuizhongLibrary
{
/// <summary>
/// 表单数据项
/// </summary>
public class FormItemModel
{
/// <summary>
/// 表单键request["key"]
/// </summary>
public string Key { set; get; }
/// <summary>
/// 表单值,上传文件时忽略request["key"].value
/// </summary>
public string Value { set; get; }
/// <summary>
/// 是否是文件
/// </summary>
public bool IsFile
{
get
{
if (FileContent == null || FileContent.Length == 0)
return false;
if (FileContent != null && FileContent.Length > 0 && string.IsNullOrWhiteSpace(FileName))
throw new Exception("上传文件时 FileName 属性值不能为空");
return true;
}
}
/// <summary>
/// 上传的文件名
/// </summary>
public string FileName { set; get; }
/// <summary>
/// 上传的文件内容
/// </summary>
public Stream FileContent { set; get; }
}
public class HttpFormData
{
// https
private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true; //总是接受
}
/// <summary>
/// 使用Post方法获取字符串结果
/// </summary>
/// <param name="url"></param>
/// <param name="formItems">Post表单内容</param>
/// <param name="cookieContainer"></param>
/// <param name="timeOut">默认20秒</param>
/// <param name="encoding">响应内容的编码类型默认utf-8</param>
/// <returns></returns>
public static string PostForm(string url, string Head, List<FormItemModel> formItems, CookieContainer cookieContainer = null, string refererUrl = null, Encoding encoding = null, int timeOut = 20000)
{
HttpWebRequest request = null;
//HTTPSQ请求
if (url.Substring(0, 8) == "https://")
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
}
request = WebRequest.Create(url) as HttpWebRequest;
request.ProtocolVersion = HttpVersion.Version10;
#region 初始化请求对象
request.Method = "POST";
request.Timeout = timeOut;
if (Head != null && Head != "")
request.Headers.Add(Head);
//request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
request.KeepAlive = true;
//request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36";
if (!string.IsNullOrEmpty(refererUrl))
request.Referer = refererUrl;
if (cookieContainer != null)
request.CookieContainer = cookieContainer;
#endregion
string boundary = "----" + DateTime.Now.Ticks.ToString("x");//分隔符
request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
//请求流
var postStream = new MemoryStream();
#region 处理Form表单请求内容
//是否用Form上传文件
var formUploadFile = formItems != null && formItems.Count > 0;
if (formUploadFile)
{
//文件数据模板
string fileFormdataTemplate =
"\r\n--" + boundary +
"\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"" +
"\r\nContent-Type: multipart/form-data" +
"\r\n\r\n";
//文本数据模板
string dataFormdataTemplate =
"\r\n--" + boundary +
"\r\nContent-Disposition: form-data; name=\"{0}\"" +
"\r\n\r\n{1}";
foreach (var item in formItems)
{
string formdata = null;
if (item.IsFile)
{
//上传文件
formdata = string.Format(
fileFormdataTemplate,
item.Key, //表单键
item.FileName);
}
else
{
//上传文本
formdata = string.Format(
dataFormdataTemplate,
item.Key,
item.Value);
}
//统一处理
byte[] formdataBytes = null;
//第一行不需要换行
if (postStream.Length == 0)
formdataBytes = Encoding.UTF8.GetBytes(formdata.Substring(2, formdata.Length - 2));
else
formdataBytes = Encoding.UTF8.GetBytes(formdata);
postStream.Write(formdataBytes, 0, formdataBytes.Length);
//写入文件内容
if (item.FileContent != null && item.FileContent.Length > 0)
{
using (var stream = item.FileContent)
{
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
{
postStream.Write(buffer, 0, bytesRead);
}
}
}
}
//结尾
var footer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
postStream.Write(footer, 0, footer.Length);
}
else
{
request.ContentType = "application/json;charset=UTF-8";
}
#endregion
request.ContentLength = postStream.Length;
#region 输入二进制流
if (postStream != null)
{
postStream.Position = 0;
//直接写入流
Stream requestStream = request.GetRequestStream();
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = postStream.Read(buffer, 0, buffer.Length)) != 0)
{
requestStream.Write(buffer, 0, bytesRead);
}
////debug
//postStream.Seek(0, SeekOrigin.Begin);
//StreamReader sr = new StreamReader(postStream);
//var postStr = sr.ReadToEnd();
postStream.Close();//关闭文件访问
}
#endregion
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (cookieContainer != null)
{
response.Cookies = cookieContainer.GetCookies(response.ResponseUri);
}
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader myStreamReader = new StreamReader(responseStream, encoding ?? Encoding.UTF8))
{
string retString = myStreamReader.ReadToEnd();
return retString;
}
}
}
/// <summary>
/// 使用Post方法获取字符串结果
/// </summary>
/// <param name="url"></param>
/// <param name="formItems">Post表单内容</param>
/// <param name="cookieContainer"></param>
/// <param name="timeOut">默认20秒</param>
/// <param name="encoding">响应内容的编码类型默认utf-8</param>
/// <returns></returns>
public static string PostForm(string url,List<string> Head, List<FormItemModel> formItems, CookieContainer cookieContainer = null, string refererUrl = null, Encoding encoding = null, int timeOut = 20000)
{
HttpWebRequest request = null;
//HTTPSQ请求
if (url.Substring(0, 8) == "https://")
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
}
request = WebRequest.Create(url) as HttpWebRequest;
request.ProtocolVersion = HttpVersion.Version10;
#region 初始化请求对象
request.Method = "POST";
request.Timeout = timeOut;
//if(Head!=null&& Head!="")
//request.Headers.Add(Head);
if (Head != null)
{
foreach (string strHead in Head)
{
request.Headers.Add(strHead);
}
}
//request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
request.KeepAlive = true;
//request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36";
if (!string.IsNullOrEmpty(refererUrl))
request.Referer = refererUrl;
if (cookieContainer != null)
request.CookieContainer = cookieContainer;
#endregion
string boundary = "----" + DateTime.Now.Ticks.ToString("x");//分隔符
request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
//请求流
var postStream = new MemoryStream();
#region 处理Form表单请求内容
//是否用Form上传文件
var formUploadFile = formItems != null && formItems.Count > 0;
if (formUploadFile)
{
//文件数据模板
string fileFormdataTemplate =
"\r\n--" + boundary +
"\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"" +
"\r\nContent-Type: multipart/form-data" +
"\r\n\r\n";
//文本数据模板
string dataFormdataTemplate =
"\r\n--" + boundary +
"\r\nContent-Disposition: form-data; name=\"{0}\"" +
"\r\n\r\n{1}";
foreach (var item in formItems)
{
string formdata = null;
if (item.IsFile)
{
//上传文件
formdata = string.Format(
fileFormdataTemplate,
item.Key, //表单键
item.FileName);
}
else
{
//上传文本
formdata = string.Format(
dataFormdataTemplate,
item.Key,
item.Value);
}
//统一处理
byte[] formdataBytes = null;
//第一行不需要换行
if (postStream.Length == 0)
formdataBytes = Encoding.UTF8.GetBytes(formdata.Substring(2, formdata.Length - 2));
else
formdataBytes = Encoding.UTF8.GetBytes(formdata);
postStream.Write(formdataBytes, 0, formdataBytes.Length);
//写入文件内容
if (item.FileContent != null && item.FileContent.Length > 0)
{
using (var stream = item.FileContent)
{
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
{
postStream.Write(buffer, 0, bytesRead);
}
}
}
}
//结尾
var footer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
postStream.Write(footer, 0, footer.Length);
}
else
{
request.ContentType = "application/json;charset=UTF-8";
}
#endregion
request.ContentLength = postStream.Length;
#region 输入二进制流
if (postStream != null)
{
postStream.Position = 0;
//直接写入流
Stream requestStream = request.GetRequestStream();
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = postStream.Read(buffer, 0, buffer.Length)) != 0)
{
requestStream.Write(buffer, 0, bytesRead);
}
////debug
//postStream.Seek(0, SeekOrigin.Begin);
//StreamReader sr = new StreamReader(postStream);
//var postStr = sr.ReadToEnd();
postStream.Close();//关闭文件访问
}
#endregion
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (cookieContainer != null)
{
response.Cookies = cookieContainer.GetCookies(response.ResponseUri);
}
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader myStreamReader = new StreamReader(responseStream, encoding ?? Encoding.UTF8))
{
string retString = myStreamReader.ReadToEnd();
return retString;
}
}
}
}
}

@ -0,0 +1,317 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{DB915A85-C567-4084-A3F2-A47E4A3291B7}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>HuizhongLibrary</RootNamespace>
<AssemblyName>HuizhongLibrary</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<SccProjectName>SAK</SccProjectName>
<SccLocalPath>SAK</SccLocalPath>
<SccAuxPath>SAK</SccAuxPath>
<SccProvider>SAK</SccProvider>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<DocumentationFile>bin\Debug\HuizhongLibrary.XML</DocumentationFile>
<PlatformTarget>x86</PlatformTarget>
<NoWarn>
</NoWarn>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Aspose.Words, Version=9.7.0.0, Culture=neutral, PublicKeyToken=586edb5723016262, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>UsingDll\Aspose.Words.dll</HintPath>
</Reference>
<Reference Include="BarcodeLib">
<HintPath>UsingDll\BarcodeLib.dll</HintPath>
</Reference>
<Reference Include="bouncycastle.crypto, Version=1.7.4114.6375, Culture=neutral, PublicKeyToken=0e99375e54769942">
<SpecificVersion>False</SpecificVersion>
<HintPath>bin\Debug\bouncycastle.crypto.dll</HintPath>
</Reference>
<Reference Include="DirectShowLib-2005, Version=2.1.0.0, Culture=neutral, PublicKeyToken=67e7b740cdfc2d3f, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>.\DirectShowLib-2005.dll</HintPath>
</Reference>
<Reference Include="LitJson, Version=0.7.0.0, Culture=neutral, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>UsingDll\LitJson.dll</HintPath>
</Reference>
<Reference Include="MySql.Data, Version=5.2.3.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>bin\Debug\MySql.Data.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=10.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL" />
<Reference Include="NPOI, Version=1.2.4.0, Culture=neutral, PublicKeyToken=0df73ec7942b34e1, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>UsingDll\NPOI.dll</HintPath>
</Reference>
<Reference Include="NPOI.OOXML">
<HintPath>UsingDll\NPOI.OOXML.dll</HintPath>
</Reference>
<Reference Include="NPOI.OpenXml4Net">
<HintPath>UsingDll\NPOI.OpenXml4Net.dll</HintPath>
</Reference>
<Reference Include="O2S.Components.PDFRender4NET">
<HintPath>UsingDll\O2S.Components.PDFRender4NET.dll</HintPath>
</Reference>
<Reference Include="Oracle.ManagedDataAccess, Version=4.122.19.1, Culture=neutral, PublicKeyToken=89b483f429c47342, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>UsingDll\Oracle.ManagedDataAccess.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration.Install" />
<Reference Include="System.Core" />
<Reference Include="System.Drawing" />
<Reference Include="System.EnterpriseServices" />
<Reference Include="System.Management" />
<Reference Include="System.ServiceProcess" />
<Reference Include="System.Speech" />
<Reference Include="System.Web" />
<Reference Include="System.Web.Extensions" />
<Reference Include="System.Web.Services" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
<Reference Include="ThoughtWorks.QRCode">
<HintPath>UsingDll\ThoughtWorks.QRCode.dll</HintPath>
</Reference>
<Reference Include="websocket-sharp">
<HintPath>UsingDll\websocket-sharp.dll</HintPath>
</Reference>
<Reference Include="WindowsBase" />
<Reference Include="zxing.ce2.0">
<HintPath>UsingDll\zxing.ce2.0.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="ActivityKeyHook.cs" />
<Compile Include="AesGcm.cs" />
<Compile Include="Camera.cs" />
<Compile Include="CDmSoft.cs" />
<Compile Include="Config.cs" />
<Compile Include="ConfigurationSourceSection.cs" />
<Compile Include="CustomIO.cs" />
<Compile Include="Database.cs" />
<Compile Include="DatabaseConnect.cs" />
<Compile Include="DatabaseFactory.cs" />
<Compile Include="DataCache.cs" />
<Compile Include="DataConvert.cs" />
<Compile Include="DataEventArgs.cs" />
<Compile Include="DataGridRadioButton.cs" />
<Compile Include="DataRegex.cs" />
<Compile Include="DataTableReport.cs" />
<Compile Include="DateUtils.cs" />
<Compile Include="Dingtalk\DingtalkModel.cs" />
<Compile Include="Dingtalk\DingtalkService.cs" />
<Compile Include="DllInvoke.cs" />
<Compile Include="EcanConvertToCh.cs" />
<Compile Include="ErrorFollow.cs" />
<Compile Include="Extension\DataTableExtension.cs" />
<Compile Include="Extension\ListExtension.cs" />
<Compile Include="HtmlCapture.cs" />
<Compile Include="HttpFormData.cs" />
<Compile Include="LocalIpAddress.cs" />
<Compile Include="JavaScriptConstant.cs" />
<Compile Include="LedLibrary.cs" />
<Compile Include="ListGridView.cs" />
<Compile Include="MaskedTextBox.cs" />
<Compile Include="MicrosoftExcel.cs" />
<Compile Include="MicrosoftWord.cs" />
<Compile Include="Models\JavaDataTable.cs" />
<Compile Include="Models\JsonModel.cs" />
<Compile Include="Models\PostDateClass.cs" />
<Compile Include="Models\TableCell.cs" />
<Compile Include="MyAlphaControl\AlphaLabel.cs">
<SubType>UserControl</SubType>
</Compile>
<Compile Include="MyAlphaControl\AlphaLabel.Designer.cs">
<DependentUpon>AlphaLabel.cs</DependentUpon>
</Compile>
<Compile Include="MyAlphaControl\ControlInfoExtend.cs" />
<Compile Include="MyAlphaControl\MyImageList.cs" />
<Compile Include="MyAlphaControl\MyPanel.cs">
<SubType>UserControl</SubType>
</Compile>
<Compile Include="MyAlphaControl\MyPanel.Designer.cs">
<DependentUpon>MyPanel.cs</DependentUpon>
</Compile>
<Compile Include="MyAlphaControl\StringPool.cs" />
<Compile Include="MyImage.cs" />
<Compile Include="MyKeyDemon.cs" />
<Compile Include="Network\DataEventArgs.cs" />
<Compile Include="Network\ExtensionMethods\ExtensionMethods.cs" />
<Compile Include="Network\SendSocket.cs" />
<Compile Include="Network\SocketEventArgs.cs" />
<Compile Include="Network\SocketMessage.cs" />
<Compile Include="Network\SocketServer\BufferPool.cs" />
<Compile Include="Network\SocketServer\ServerConnection.cs" />
<Compile Include="Network\SocketServer\ServerConnectionPool.cs" />
<Compile Include="Network\SocketServer\SocketArgsPool.cs" />
<Compile Include="Network\SocketServer\TcpSocketListener.cs" />
<Compile Include="Network\UdpSocket.cs" />
<Compile Include="PageMessageBox.cs" />
<Compile Include="PhonePay\AliPay.cs" />
<Compile Include="PhonePay\business\DownloadBill.cs" />
<Compile Include="PhonePay\business\JsApiPay.cs" />
<Compile Include="PhonePay\business\MicroPay.cs" />
<Compile Include="PhonePay\business\NativeNotify.cs" />
<Compile Include="PhonePay\business\NativePay.cs" />
<Compile Include="PhonePay\business\OrderQuery.cs" />
<Compile Include="PhonePay\business\Refund.cs" />
<Compile Include="PhonePay\business\RefundQuery.cs" />
<Compile Include="PhonePay\business\ResultNotify.cs" />
<Compile Include="PhonePay\lib\Config.cs" />
<Compile Include="PhonePay\lib\Data.cs" />
<Compile Include="PhonePay\lib\Exception.cs" />
<Compile Include="PhonePay\lib\HttpService.cs" />
<Compile Include="PhonePay\lib\Log.cs" />
<Compile Include="PhonePay\lib\Notify.cs" />
<Compile Include="PhonePay\lib\WxPayApi.cs" />
<Compile Include="PhonePay\WeiXinPay.cs" />
<Compile Include="PrintSetup.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="PrintSetup.Designer.cs">
<DependentUpon>PrintSetup.cs</DependentUpon>
</Compile>
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
<DependentUpon>Settings.settings</DependentUpon>
</Compile>
<Compile Include="Safety.cs" />
<Compile Include="SerialPortService.cs" />
<Compile Include="SoundVoice.cs" />
<Compile Include="SqlSelectService\QueryService.cs" />
<Compile Include="SqlSelectService\RefParameter.cs" />
<Compile Include="SqlSelectService\SelectParameter.cs" />
<Compile Include="SystemInfo.cs" />
<Compile Include="Network\TcpSocket.cs" />
<Compile Include="TimeTask.cs" />
<Compile Include="UFace\UfaceModel.cs" />
<Compile Include="UFace\UfaceService.cs" />
<Compile Include="VoicePortSound.cs" />
<Compile Include="Web References\US\Reference.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Reference.map</DependentUpon>
</Compile>
<Compile Include="Weixin\WeixinDepartMent.cs" />
<Compile Include="Weixin\WeixinMenu.cs" />
<Compile Include="Weixin\WeixinMessage.cs" />
<Compile Include="Weixin\WeixinService.cs" />
<Compile Include="Weixin\WeixinUser.cs" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="MyAlphaControl\AlphaLabel.resx">
<DependentUpon>AlphaLabel.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="MyAlphaControl\MyPanel.resx">
<DependentUpon>MyPanel.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="PrintSetup.resx">
<DependentUpon>PrintSetup.cs</DependentUpon>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<Content Include="HTMLPage1.html" />
<Content Include="UsingDll\AipSdk.dll" />
<Content Include="UsingDll\AopSdk.dll" />
<Content Include="UsingDll\Aspose.Words.dll" />
<Content Include="UsingDll\bouncycastle.crypto.dll" />
<Content Include="UsingDll\DirectShowLib-2005.dll" />
<Content Include="UsingDll\Gma.QrCodeNet.Encoding.dll" />
<Content Include="UsingDll\ICSharpCode.SharpZipLib.dll" />
<Content Include="UsingDll\LitJson.dll" />
<Content Include="UsingDll\MySql.Data.dll" />
<Content Include="UsingDll\Newtonsoft.Json.dll" />
<Content Include="UsingDll\NPOI.dll" />
<Content Include="UsingDll\NPOI.OOXML.dll" />
<Content Include="UsingDll\NPOI.OpenXml4Net.dll" />
<Content Include="UsingDll\NPOI.OpenXmlFormats.dll" />
<Content Include="UsingDll\oci.dll" />
<Content Include="UsingDll\Oracle.ManagedDataAccess.dll" />
<Content Include="UsingDll\orannzsbb11.dll" />
<Content Include="UsingDll\oraociei11.dll" />
<Content Include="UsingDll\OraOps11w.dll" />
<Content Include="UsingDll\Spire.Doc.dll" />
<Content Include="UsingDll\Spire.License.dll" />
<Content Include="UsingDll\Spire.Pdf.dll" />
<Content Include="UsingDll\System.Speech.dll" />
<Content Include="UsingDll\ThoughtWorks.QRCode.dll" />
<Content Include="UsingDll\zxing.ce2.0.dll" />
<None Include="app.config" />
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<None Include="Web References\US\FileModel.datasource">
<DependentUpon>Reference.map</DependentUpon>
</None>
<None Include="Web References\US\Reference.map">
<Generator>MSDiscoCodeGenerator</Generator>
<LastGenOutput>Reference.cs</LastGenOutput>
</None>
<None Include="Web References\US\UpdateService.disco" />
</ItemGroup>
<ItemGroup>
<WCFMetadata Include="Service References\" />
</ItemGroup>
<ItemGroup>
<WebReferences Include="Web References\" />
</ItemGroup>
<ItemGroup>
<WebReferenceUrl Include="http://47.114.82.162:7000/UpdateService.asmx">
<UrlBehavior>Dynamic</UrlBehavior>
<RelPath>Web References\US\</RelPath>
<UpdateFromURL>http://47.114.82.162:7000/UpdateService.asmx</UpdateFromURL>
<ServiceLocationURL>
</ServiceLocationURL>
<CachedDynamicPropName>
</CachedDynamicPropName>
<CachedAppSettingsObjectName>Settings</CachedAppSettingsObjectName>
<CachedSettingsPropName>HuizhongLibrary_US_UpdateService</CachedSettingsPropName>
</WebReferenceUrl>
</ItemGroup>
<ItemGroup>
<None Include="Web References\US\UpdateService.wsdl" />
</ItemGroup>
<ItemGroup>
<Folder Include="Safety\" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

@ -0,0 +1,28 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2012
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HuizhongLibrary", "HuizhongLibrary.csproj", "{DB915A85-C567-4084-A3F2-A47E4A3291B7}"
EndProject
Global
GlobalSection(TeamFoundationVersionControl) = preSolution
SccNumberOfProjects = 2
SccEnterpriseProvider = {4CA58AB2-18FA-4F8D-95D4-32DDF27D184C}
SccTeamFoundationServer = http://192.168.1.157:8080/tfs/defaultcollection
SccLocalPath0 = .
SccProjectUniqueName1 = HuizhongLibrary.csproj
SccLocalPath1 = .
EndGlobalSection
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{DB915A85-C567-4084-A3F2-A47E4A3291B7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{DB915A85-C567-4084-A3F2-A47E4A3291B7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DB915A85-C567-4084-A3F2-A47E4A3291B7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DB915A85-C567-4084-A3F2-A47E4A3291B7}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

@ -0,0 +1,814 @@
using System;
namespace HuizhongLibrary.Control
{
/// <summary>
/// JavaScriptConstant 的摘要说明。
/// </summary>
public class JavaScriptConstant
{
#region 复选框全选的脚本
public static string jsCheckAll = @"<script type=""text/javascript"">
//function select_deselectAll(chkval,GridID,CheckBoxID)
function select_deselectAll(chkval,idval)
{
var table1=document.getElementById(idval);
for (var i=1;i<=table1.rows.length+3;i++)
{
var rowid=idval+'_ctl0'+i;
if (i>9)rowid=idval+'_ctl'+i;
var v1=document.getElementById(rowid+'_CheckBoxSelect_123456789');
if (v1==null)continue;
if(chkval==true)
{
v1.checked=true;
}
else
{
v1.checked=false;
}
}
// var frm=document.forms[0];
// var re = new RegExp(GridID+'.{1,}'+CheckBoxID,'i');
// for(i=0;i<frm.length;i++)
// {
// var val= frm.elements[i].id.match(re);
// if (val==null || val.length==0)continue;
// if (frm.elements[i].disabled==true)continue;
// if(chkval==true)
// {
// frm.elements[i].checked=true;
// }
// else
// {
// frm.elements[i].checked=false;
// }
// }
}
</script>";
#endregion
#region 层移动脚本
public static string divMove=@"<script language=""JavaScript"" for=""document"" type=""text/javascript"">
var orgMouseX;
var orgMouseY;
var orgObjX;
var orgObjY;
var bk=0;
function doDrag(HeadID,ContentID)
{
if (bk==0)return;
var myObject=document.getElementById(HeadID);
var myObject1=document.getElementById(ContentID);
var x=event.clientX;
var y=event.clientY;
myObject.style.left=x-(orgMouseX-orgObjX);
myObject.style.top=y-(orgMouseY-orgObjY);
// myObject1.style.top=myObject.style.top+myObject.style.height;
myObject1.style.left=myObject.style.left;
if (document.getElementById(HeadID+'Header_top')!=null)document.getElementById(HeadID+'Header_top').value=myObject.style.top
if (document.getElementById(HeadID+'Header_left')!=null)document.getElementById(HeadID+'Header_left').value=myObject.style.left
}
function doMouseDown(HeadID)
{
orgMouseX=event.clientX;
orgMouseY=event.clientY;
orgObjX=parseInt(document.getElementById(HeadID).style.left);
orgObjY=parseInt(document.getElementById(HeadID).style.top);
bk=1;
}
function doMouseUp()
{
bk=0;
}
</script>";
#endregion
#region 回车移动焦点脚本
public static string EnterMoveFocus= @"<script language=""javascript"" event=""onkeydown"" for=""document"">
if(event.keyCode==13 && event.srcElement.type!='button' && event.srcElement.type!='submit' && event.srcElement.type!='reset' && event.srcElement.type!='' && event.srcElement.type!='textarea')
event.keyCode=9;
</script>";
#endregion
#region 日期控件脚本
public static string DateMonth = @"<script language=""JavaScript"" for=""document"" type=""text/javascript"">
/*************************************************************
*
*
*<INPUT class=clsText onfocus=setday(this) maxLength=16 size=30 name=CSNY c_type=""date"" c_mes="""">
**************************************************************/
//==================================================== 参数设定部分 =======================================================
var bMoveable=true; //设置日历是否可以拖动
var _VersionInfo=""Version:2.0&#13;2.0:walkingpoison&#13;1.0: F.R.Huang(meizz)&#13;MAIL: meizz@hzcnc.com"" //版本信息
//==================================================== WEB 页面显示部分 =====================================================
var strFrame; //存放日历层的HTML代码
document.writeln('<iframe id=MaskedTextBox_meizzDateLayer Author=wayx frameborder=0 style=""position: absolute; width: 144; height: 208; z-index: 9998; display: none""></iframe>');
strFrame='<style>';
strFrame+='select.editTextbox{color:#2A2D60; border-right: #7f9db9 1px solid; border-top: #7f9db9 1px solid; font-size: 12px; ';
strFrame+='border-left: #7f9db9 1px solid; border-bottom: #7f9db9 1px solid; padding-left:1; padding-right:1;}';
strFrame+='INPUT.button{border-right: #D0D0D0 1px solid; border-top: #D0D0D0 1px none; font-size: 12px; border-left: #D0D0D0 1px none; border-bottom: #D0D0D0 1px solid;';
strFrame+='vertical-align:middle; background-image:url(../images/button.gif);background-repeat:repeat; cursor: hand; ';
strFrame+='color:#2A2D60; height:24px; margin:0; padding-top:0px; padding-left:1px; padding-bottom:0px; padding-right:1px;background-color:#D0D0D0;}';
strFrame+='TD{FONT-SIZE: 9pt;font-family:;color:#2A2D60;}';
strFrame+='</style>';
strFrame+='<scr' + 'ipt>';
strFrame+='var datelayerx,datelayery; /*存放日历控件的鼠标位置*/';
strFrame+='var bDrag; /*标记是否开始拖动*/';
strFrame+='document.onmousemove=function()';
strFrame+='{if(bDrag && window.event.button==1)';
strFrame+=' {var DateLayer=parent.document.all.MaskedTextBox_meizzDateLayer.style;';
strFrame+=' DateLayer.posLeft += window.event.clientX-datelayerx;/*由于每次移动以后鼠标位置都恢复为初始的位置因此写法与div中不同*/';
strFrame += ' DateLayer.posTop += window.event.clientY-datelayery;}';
strFrame += '}\n';
strFrame+='function DragStart() /*开始日历拖动*/';
strFrame+='{var DateLayer=parent.document.all.MaskedTextBox_meizzDateLayer.style;';
strFrame+=' datelayerx=window.event.clientX;';
strFrame+=' datelayery=window.event.clientY;';
strFrame+=' bDrag=true;}';
strFrame+='function DragEnd(){ /*结束日历拖动*/';
strFrame+=' bDrag=false;}';
strFrame+='</scr' + 'ipt>';
strFrame+='<div style=""z-index:9999;position: absolute; left:0; top:0;"" onselectstart=""return false""><span id=tmpSelectYearLayer Author=wayx style=""z-index: 9999;position: absolute;top: 3; left: 19;display: none""></span>';
strFrame+='<span id=tmpSelectMonthLayer Author=wayx style=""z-index: 9999;position: absolute;top: 3; left: 78;display: none""></span>';
strFrame+='<table border=1 cellspacing=0 cellpadding=0 width=142 height=160 bordercolor=#5F9FD1 bgcolor=#5F9FD1 Author=""wayx"">';
strFrame+=' <tr Author=""wayx""><td width=142 height=23 Author=""wayx"" bgcolor=#FFFFFF><table border=0 cellspacing=2 cellpadding=0 width=140 Author=""wayx"" height=23>';
strFrame+=' <tr align=center Author=""wayx""><td width=16 align=center bgcolor=#5F9FD1 style=""font-size:12px;cursor: hand;color: #ffffff"" ';
strFrame+=' onclick=""parent.meizzPrevM()"" title="" 1 "" Author=meizz><b Author=meizz>&lt;</b>';
strFrame+=' </td><td width=60 align=center style=""font-size:12px;cursor:default"" Author=meizz ';
strFrame+='onmouseover=""style.backgroundColor=\'#FFD700\'"" onmouseout=""style.backgroundColor=\'white\'"" ';
strFrame+='onclick=""parent.tmpSelectYearInnerHTML(this.innerText.substring(0,4))"" title=""""><span Author=meizz id=meizzYearHead></span></td>';
strFrame+='<td width=48 align=center style=""font-size:12px;cursor:default"" Author=meizz onmouseover=""style.backgroundColor=\'#FFD700\'"" ';
strFrame+=' onmouseout=""style.backgroundColor=\'white\'"" onclick=""parent.tmpSelectMonthInnerHTML(this.innerText.length==3?this.innerText.substring(0,1):this.innerText.substring(0,2))""';
strFrame+=' title=""""><span id=meizzMonthHead Author=meizz></span></td>';
strFrame+=' <td width=16 bgcolor=#5F9FD1 align=center style=""font-size:12px;cursor: hand;color: #ffffff"" ';
strFrame+=' onclick=""parent.meizzNextM()"" title="" 1 "" Author=meizz><b Author=meizz>&gt;</b></td></tr>';
strFrame+=' </table></td></tr>';
strFrame+=' <tr Author=""wayx""><td width=142 height=18 Author=""wayx"">';
strFrame+='<table border=1 cellspacing=2 cellpadding=0 bgcolor=#5F9FD1 ' + (bMoveable? 'onmousedown=""DragStart()"" onmouseup=""DragEnd()""':'');
strFrame+=' BORDERCOLORLIGHT=#E8E5D2 BORDERCOLORDARK=#FFFFFF width=140 height=20 Author=""wayx"" style=""cursor:' + (bMoveable ? 'move':'default') + '"">';
strFrame+='<tr Author=""wayx"" align=center valign=bottom><td style=""font-size:12px;color:#FFFFFF"" Author=meizz></td>';
strFrame+='<td style=""font-size:12px;color:#FFFFFF"" Author=meizz></td><td style=""font-size:12px;color:#FFFFFF"" Author=meizz></td>';
strFrame+='<td style=""font-size:12px;color:#FFFFFF"" Author=meizz></td><td style=""font-size:12px;color:#FFFFFF"" Author=meizz></td>';
strFrame+='<td style=""font-size:12px;color:#FFFFFF"" Author=meizz></td><td style=""font-size:12px;color:#FFFFFF"" Author=meizz></td></tr>';
strFrame+='</table></td></tr><!-- Author:F.R.Huang(meizz) http://www.meizz.com/ mail: meizz@hzcnc.com 2002-10-8 -->';
strFrame+=' <tr Author=""wayx""><td width=142 height=120 Author=""wayx"">';
strFrame+=' <table border=1 cellspacing=1 cellpadding=0 BORDERCOLORLIGHT=#E8E5D2 BORDERCOLORDARK=#FFFFFF bgcolor=#E4F8F9 width=140 height=120 Author=""wayx"">';
var n=0; for (j=0;j<5;j++){ strFrame+= ' <tr align=center Author=""wayx"">'; for (i=0;i<7;i++){
strFrame+='<td width=20 height=20 id=meizzDay'+n+' style=""font-size:12px"" Author=meizz onclick=parent.meizzDayClick(this.innerText,0)></td>';n++;}
strFrame+='</tr>';}
strFrame+=' <tr align=center Author=""wayx"">';
for (i=35;i<39;i++)strFrame+='<td width=20 height=20 id=meizzDay'+i+' style=""font-size:12px"" Author=wayx onclick=""parent.meizzDayClick(this.innerText,0)""></td>';
strFrame+=' <td colspan=3 align=right Author=meizz><span onclick=parent.closeLayer() style=""font-size:12px;cursor: hand""';
strFrame+=' Author=meizz title=""' + _VersionInfo + '""><u></u></span>&nbsp;</td></tr>';
strFrame+=' </table></td></tr><tr Author=""wayx""><td Author=""wayx"">';
strFrame+=' <table border=0 cellspacing=1 cellpadding=0 width=100% Author=""wayx"" bgcolor=#E4F8F9>';
strFrame+=' <tr Author=""wayx""><td Author=meizz align=left><input Author=meizz type=button class=button value=""<<"" title="" 1 "" onclick=""parent.meizzPrevY()"" ';
strFrame+=' onfocus=""this.blur()"" style=""font-size: 12px; height: 20px""><input Author=meizz class=button title="" 1 "" type=button ';
strFrame+=' value=""< "" onclick=""parent.meizzPrevM()"" onfocus=""this.blur()"" style=""font-size: 12px; height: 20px""></td><td ';
strFrame+=' Author=meizz align=center><input Author=meizz type=button class=button value="""" onclick=""parent.meizzToday()"" ';
strFrame+=' onfocus=""this.blur()"" title="""" style=""font-size: 12px; height: 20px; cursor:hand""></td><td ';
strFrame+=' Author=meizz align=right><input Author=meizz type=button class=button value="" >"" onclick=""parent.meizzNextM()"" ';
strFrame+=' onfocus=""this.blur()"" title="" 1 "" class=button style=""font-size: 12px; height: 20px""><input ';
strFrame+=' Author=meizz type=button class=button value="">>"" title="" 1 "" onclick=""parent.meizzNextY()""';
strFrame+=' onfocus=""this.blur()"" style=""font-size: 12px; height: 20px""></td>';
strFrame+='</tr></table></td></tr></table></div>';
window.frames.MaskedTextBox_meizzDateLayer.document.writeln(strFrame);
window.frames.MaskedTextBox_meizzDateLayer.document.close(); //解决ie进度条不结束的问题
//==================================================== WEB 页面显示部分 ======================================================
var outObject;
var outButton; //点击的按钮
var outDate=""""; //存放对象的日期
var odatelayer=window.frames.MaskedTextBox_meizzDateLayer.document.all; //存放日历对象
function setday(tt,obj) //主调函数
{
if (arguments.length > 2){alert("""");return;}
if (arguments.length == 0){alert("""");return;}
var dads = document.all.MaskedTextBox_meizzDateLayer.style;
var th = tt;
var ttop = tt.offsetTop; //TT控件的定位点高
var thei = tt.clientHeight; //TT控件本身的高
var tleft = tt.offsetLeft; //TT控件的定位点宽
var ttyp = tt.type; //TT控件的类型
while (tt = tt.offsetParent){ttop+=tt.offsetTop; tleft+=tt.offsetLeft;}
dads.top = (ttyp==""image"")? ttop+thei : ttop+thei+6;
dads.left = tleft;
outObject = (arguments.length == 1) ? th : obj;
outButton = (arguments.length == 1) ? null : th; //设定外部点击的按钮
//根据当前输入框的日期显示日历的年月
var reg = /^(\d+)-(\d{1,2})-(\d{1,2})$/;
var r = outObject.value.match(reg);
if(r!=null){
r[2]=r[2]-1;
var d= new Date(r[1], r[2],r[3]);
if(d.getFullYear()==r[1] && d.getMonth()==r[2] && d.getDate()==r[3]){
outDate=d; //保存外部传入的日期
}
else outDate="""";
meizzSetDay(r[1],r[2]+1);
}
else{
outDate="""";
meizzSetDay(new Date().getFullYear(), new Date().getMonth() + 1);
}
dads.display = '';
event.returnValue=false;
}
var MonHead = new Array(12); //定义阳历中每个月的最大天数
MonHead[0] = 31; MonHead[1] = 28; MonHead[2] = 31; MonHead[3] = 30; MonHead[4] = 31; MonHead[5] = 30;
MonHead[6] = 31; MonHead[7] = 31; MonHead[8] = 30; MonHead[9] = 31; MonHead[10] = 30; MonHead[11] = 31;
var meizzTheYear=new Date().getFullYear(); //定义年的变量的初始值
var meizzTheMonth=new Date().getMonth()+1; //定义月的变量的初始值
var meizzWDay=new Array(39); //定义写日期的数组
document.onclick=function() //任意点击时关闭该控件 //ie6的情况可以由下面的切换焦点处理代替
{
with(window.event)
{ if (srcElement.getAttribute(""Author"")==null && srcElement != outObject && srcElement != outButton)
closeLayer();
}
}
document.onkeyup = function () //按Esc键关闭切换焦点关闭
{
if (window.event.keyCode==27){
if(outObject)outObject.blur();
closeLayer();
}
else if(document.activeElement)
if(document.activeElement.getAttribute(""Author"")==null && document.activeElement != outObject && document.activeElement != outButton)
{
closeLayer();
}
}
function meizzWriteHead(yy,mm) //往 head 中写入当前的年与月
{
odatelayer.meizzYearHead.innerText = yy + "" "";
odatelayer.meizzMonthHead.innerText = mm + "" "";
}
function tmpSelectYearInnerHTML(strYear) //年份的下拉框
{
if (strYear.match(/\D/)!=null){alert("""");return;}
var m = (strYear) ? strYear : new Date().getFullYear();
if (m < 1000 || m > 9999) {alert("" 1000 9999 "");return;}
var n = m - 10;
if (n < 1000) n = 1000;
if (n + 26 > 9999) n = 9974;
var s = ""<select Author=meizz name=tmpSelectYear style='font-size: 12px' ""
s += ""onblur='document.all.tmpSelectYearLayer.style.display=\""none\""' ""
s += ""onchange='document.all.tmpSelectYearLayer.style.display=\""none\"";""
s += ""parent.meizzTheYear = this.value; parent.meizzSetDay(parent.meizzTheYear,parent.meizzTheMonth)'>\r\n"";
var selectInnerHTML = s;
for (var i = n; i < n + 26; i++)
{
if (i == m)
{selectInnerHTML += ""<option Author=wayx value='"" + i + ""' selected>"" + i + """" + ""</option>\r\n"";}
else {selectInnerHTML += ""<option Author=wayx value='"" + i + ""'>"" + i + """" + ""</option>\r\n"";}
}
selectInnerHTML += ""</select>"";
odatelayer.tmpSelectYearLayer.style.display="""";
odatelayer.tmpSelectYearLayer.innerHTML = selectInnerHTML;
odatelayer.tmpSelectYear.focus();
}
function tmpSelectMonthInnerHTML(strMonth) //月份的下拉框
{
if (strMonth.match(/\D/)!=null){alert("""");return;}
var m = (strMonth) ? strMonth : new Date().getMonth() + 1;
var s = ""<select Author=meizz name=tmpSelectMonth style='font-size: 12px' ""
s += ""onblur='document.all.tmpSelectMonthLayer.style.display=\""none\""' ""
s += ""onchange='document.all.tmpSelectMonthLayer.style.display=\""none\"";""
s += ""parent.meizzTheMonth = this.value; parent.meizzSetDay(parent.meizzTheYear,parent.meizzTheMonth)'>\r\n"";
var selectInnerHTML = s;
for (var i = 1; i < 13; i++)
{
if (i == m)
{selectInnerHTML += ""<option Author=wayx value='""+i+""' selected>""+i+""""+""</option>\r\n"";}
else {selectInnerHTML += ""<option Author=wayx value='""+i+""'>""+i+""""+""</option>\r\n"";}
}
selectInnerHTML += ""</select>"";
odatelayer.tmpSelectMonthLayer.style.display="""";
odatelayer.tmpSelectMonthLayer.innerHTML = selectInnerHTML;
odatelayer.tmpSelectMonth.focus();
}
function closeLayer() //这个层的关闭
{
document.all.MaskedTextBox_meizzDateLayer.style.display=""none"";
}
function IsPinYear(year) //判断是否闰平年
{
if (0==year%4&&((year%100!=0)||(year%400==0))) return true;else return false;
}
function GetMonthCount(year,month) //闰年二月为29天
{
var c=MonHead[month-1];if((month==2)&&IsPinYear(year)) c++;return c;
}
function GetDOW(day,month,year) //求某天的星期几
{
var dt=new Date(year,month-1,day).getDay()/7; return dt;
}
function meizzPrevY() //往前翻 Year
{
if(meizzTheYear > 999 && meizzTheYear <10000){meizzTheYear--;}
else{alert(""1000-9999"");}
meizzSetDay(meizzTheYear,meizzTheMonth);
}
function meizzNextY() //往后翻 Year
{
if(meizzTheYear > 999 && meizzTheYear <10000){meizzTheYear++;}
else{alert(""1000-9999"");}
meizzSetDay(meizzTheYear,meizzTheMonth);
}
function meizzToday() //Today Button
{
var today;
meizzTheYear = new Date().getFullYear();
meizzTheMonth = new Date().getMonth()+1;
today=new Date().getDate();
if(meizzTheMonth.toString().length<2) meizzTheMonth = ""0"" + meizzTheMonth;
if(today.toString().length<2) today = ""0"" + today;
//meizzSetDay(meizzTheYear,meizzTheMonth);
if(outObject){
outObject.value=meizzTheYear + ""-"" + meizzTheMonth + ""-"" + today;
}
closeLayer();
}
function meizzPrevM() //往前翻月份
{
if(meizzTheMonth>1){meizzTheMonth--}else{meizzTheYear--;meizzTheMonth=12;}
meizzSetDay(meizzTheYear,meizzTheMonth);
}
function meizzNextM() //往后翻月份
{
if(meizzTheMonth==12){meizzTheYear++;meizzTheMonth=1}else{meizzTheMonth++}
meizzSetDay(meizzTheYear,meizzTheMonth);
}
function meizzSetDay(yy,mm) //主要的写程序**********
{
meizzWriteHead(yy,mm);
//设置当前年月的公共变量为传入值
meizzTheYear=yy;
meizzTheMonth=mm;
for (var i = 0; i < 39; i++){meizzWDay[i]=""""}; //将显示框的内容全部清空
var day1 = 1,day2=1,firstday = new Date(yy,mm-1,1).getDay(); //某月第一天的星期几
for (i=0;i<firstday;i++)meizzWDay[i]=GetMonthCount(mm==1?yy-1:yy,mm==1?12:mm-1)-firstday+i+1 //上个月的最后几天
for (i = firstday; day1 < GetMonthCount(yy,mm)+1; i++){meizzWDay[i]=day1;day1++;}
for (i=firstday+GetMonthCount(yy,mm);i<39;i++){meizzWDay[i]=day2;day2++}
for (i = 0; i < 39; i++)
{ var da = eval(""odatelayer.meizzDay""+i) //书写新的一个月的日期星期排列
if (meizzWDay[i]!="""")
{
//初始化边框
da.borderColorLight=""#E8E5D2"";
da.borderColorDark=""#FFFFFF"";
if(i<firstday) //上个月的部分
{
da.innerHTML=""<b><font color=gray>"" + meizzWDay[i] + ""</font></b>"";
da.title=(mm==1?12:mm-1) +"""" + meizzWDay[i] + """";
da.onclick=Function(""meizzDayClick(this.innerText,-1)"");
if(!outDate)
da.style.backgroundColor = ((mm==1?yy-1:yy) == new Date().getFullYear() &&
(mm==1?12:mm-1) == new Date().getMonth()+1 && meizzWDay[i] == new Date().getDate()) ?
""#FFD700"":""#e0e0e0"";
else
{
da.style.backgroundColor =((mm==1?yy-1:yy)==outDate.getFullYear() && (mm==1?12:mm-1)== outDate.getMonth() + 1 &&
meizzWDay[i]==outDate.getDate())? ""#00ffff"" :
(((mm==1?yy-1:yy) == new Date().getFullYear() && (mm==1?12:mm-1) == new Date().getMonth()+1 &&
meizzWDay[i] == new Date().getDate()) ? ""#FFD700"":""#e0e0e0"");
//将选中的日期显示为凹下去
if((mm==1?yy-1:yy)==outDate.getFullYear() && (mm==1?12:mm-1)== outDate.getMonth() + 1 &&
meizzWDay[i]==outDate.getDate())
{
da.borderColorLight=""#FFFFFF"";
da.borderColorDark=""#E8E5D2"";
}
}
}
else if (i>=firstday+GetMonthCount(yy,mm)) //下个月的部分
{
da.innerHTML=""<b><font color=gray>"" + meizzWDay[i] + ""</font></b>"";
da.title=(mm==12?1:mm+1) +"""" + meizzWDay[i] + """";
da.onclick=Function(""meizzDayClick(this.innerText,1)"");
if(!outDate)
da.style.backgroundColor = ((mm==12?yy+1:yy) == new Date().getFullYear() &&
(mm==12?1:mm+1) == new Date().getMonth()+1 && meizzWDay[i] == new Date().getDate()) ?
""#FFD700"":""#e0e0e0"";
else
{
da.style.backgroundColor =((mm==12?yy+1:yy)==outDate.getFullYear() && (mm==12?1:mm+1)== outDate.getMonth() + 1 &&
meizzWDay[i]==outDate.getDate())? ""#00ffff"" :
(((mm==12?yy+1:yy) == new Date().getFullYear() && (mm==12?1:mm+1) == new Date().getMonth()+1 &&
meizzWDay[i] == new Date().getDate()) ? ""#FFD700"":""#e0e0e0"");
//将选中的日期显示为凹下去
if((mm==12?yy+1:yy)==outDate.getFullYear() && (mm==12?1:mm+1)== outDate.getMonth() + 1 &&
meizzWDay[i]==outDate.getDate())
{
da.borderColorLight=""#FFFFFF"";
da.borderColorDark=""#E8E5D2"";
}
}
}
else //本月的部分
{
da.innerHTML=""<b>"" + meizzWDay[i] + ""</b>"";
da.title=mm +"""" + meizzWDay[i] + """";
da.onclick=Function(""meizzDayClick(this.innerText,0)""); //给td赋予onclick事件的处理
//如果是当前选择的日期,则显示亮蓝色的背景;如果是当前日期,则显示暗黄色背景
if(!outDate)
da.style.backgroundColor = (yy == new Date().getFullYear() && mm == new Date().getMonth()+1 && meizzWDay[i] == new Date().getDate())?
""#FFD700"":""#e0e0e0"";
else
{
da.style.backgroundColor =(yy==outDate.getFullYear() && mm== outDate.getMonth() + 1 && meizzWDay[i]==outDate.getDate())?
""#00ffff"":((yy == new Date().getFullYear() && mm == new Date().getMonth()+1 && meizzWDay[i] == new Date().getDate())?
""#FFD700"":""#e0e0e0"");
//将选中的日期显示为凹下去
if(yy==outDate.getFullYear() && mm== outDate.getMonth() + 1 && meizzWDay[i]==outDate.getDate())
{
da.borderColorLight=""#FFFFFF"";
da.borderColorDark=""#E8E5D2"";
}
}
}
da.style.cursor=""hand""
}
else{da.innerHTML="""";da.style.backgroundColor="""";da.style.cursor=""default""}
}
}
function meizzDayClick(n,ex) //点击显示框选取日期,主输入函数*************
{
var yy=meizzTheYear;
var mm = parseInt(meizzTheMonth)+ex; //ex表示偏移量用于选择上个月份和下个月份的日期
//判断月份,并进行对应的处理
if(mm<1){
yy--;
mm=12+mm;
}
else if(mm>12){
yy++;
mm=mm-12;
}
if (mm < 10){mm = ""0"" + mm;}
if (outObject)
{
if (!n) {//outObject.value="""";
return;}
if ( n < 10){n = ""0"" + n;}
outObject.value= yy + ""-"" + mm + ""-"" + n ; //注:在这里你可以输出改成你想要的格式
closeLayer();
}
else {closeLayer(); alert("""");}
}
</script>";
#endregion
#region 打印脚本
public static string DoPrint = @"<script language=""JavaScript"" type=""text/javascript"">
function DoPrint() {
var bdhtml=window.document.body.innerHTML;
sprnstr=""<!--startprint-->"";
eprnstr=""<!--endprint-->"";
prnhtml=bdhtml.substr(bdhtml.indexOf(sprnstr)+17);
prnhtml=prnhtml.substring(0,prnhtml.indexOf(eprnstr));
window.document.body.innerHTML=prnhtml;
window.print();
}
</script>";
#endregion
#region 限制只能输入浮点数的脚本
/*
ascii
8退
46delete
37-40
48-57
96-105
110190
189109
13
9 Tab
*/
public static string KeyDown_float = @"<script type=""text/javascript"">
function KeyDown_float(obj,min)
{
var k=window.event.keyCode;
var val=obj.value;
if (k==110 || k==190)
{
var a=val.match(/\./ig);
if (a!=null && a.length>0)window.event.returnValue = false;
}
if (k==189 || k==109)
{
var minval = parseFloat(min);
if (minval==null)window.event.returnValue = false;
if (minval>=0)window.event.returnValue = false;
var b=val.match(/\-/ig);
if (b!=null && b.length>0)window.event.returnValue = false;
}
if (window.event.ctrlKey==true && (k==86 || k==118 || k==67 || k==99))return;
if ((k==46) ||(k==189)||(k==109)||(k==8)||(k==190)||(k==110)|| (k>=48 && k<=57)||(k>=96 && k<=105)||(k>=37 && k<=40))
{}
else if(k==13){
window.event.keyCode = 9;}
else{
window.event.returnValue = false;}
}
</script>";
#endregion
#region 限制只能输入整数的脚本
/*
ascii
8退
46delete
37-40
48-57
96-105
110190
189109
13
9 Tab
*/
public static string KeyDown_int = @"<script type=""text/javascript"">
function KeyDown_int(obj,min)
{
var k=window.event.keyCode;
var val=obj.value;
if (k==189 || k==109)
{
var minval = parseFloat(min);
if (minval==null)window.event.returnValue = false;
if (minval>=0)window.event.returnValue = false;
var b=val.match(/\-/ig);
if (b!=null && b.length>0)window.event.returnValue = false;
}
if (window.event.ctrlKey==true && (k==86 || k==118 || k==67 || k==99))return;
if ((k==46) ||(k==189)||(k==109)||(k==8) || (k>=48 && k<=57)||(k>=96 && k<=105)||(k>=37 && k<=40))
{}
else if(k==13){
window.event.keyCode = 9;}
else{
window.event.returnValue = false;}
}
</script>";
#endregion
#region 客户端回传脚本
public static string doPostBack = @"<script type=""text/javascript"">
function doPostBack(eventTarget, eventArgument)
{
var theform=document.forms[0];
theform.__EVENTTARGET.value = eventTarget.split('$').join(':');
theform.__EVENTARGUMENT.value = eventArgument;
theform.submit();
}
</script>";
#endregion
#region 验证日期的脚本
public static string CheckDateTime= @"<script type=""text/javascript"">
function CheckDateTime(obj)//检验日期型数据是否正确
{
var errorDiv=document.getElementById(obj.id+'Error');
errorDiv.style.cssText=errorStyle;
if (obj.value.length == 0){
return true;
}
var str,temp,jump="";
str=obj.value;
temp=str.split('-');
if((temp[1]==null)||(temp[2]==null))
{
flag = 1;
return false;
}
if(!(isMadeOf(temp[0],intStr)&&isMadeOf(temp[1],intStr)&&isMadeOf(temp[2],intStr)))
{
flag = 1;
return false;
}
var Vyear,Vmonth,Vday;
Vyear=parseInt(getRidOfZero(temp[0]));
Vmonth=parseInt(getRidOfZero(temp[1]));
Vday=parseInt(getRidOfZero(temp[2]));
if(Vyear>2100||Vyear<1900)
jump='20002100';
if(Vmonth>12||Vmonth<1)
jump='';
if(Vday>31||Vday<1)
jump='';
if(jump!="")
{
flag = 1;
return false;
}
if(!forDate1(Vyear,Vmonth,Vday))
{
flag=1;
}
return true;
}
function getRidOfZero(v)//一个数字字符串前的0删除
{
var s="";
for(var i=0;i<v.length;i++)
{
if(v.charAt(i)!='0')
break;
}
for(var t=i;t<v.length;t++)
{
s+=v.charAt(t);
}
return s;
}
function forDate1(useryear,usermonth,userday)
{
var myyear;
var mymonth;
var myday;
//myyear=parseInt(useryear);
//mymonth=parseInt(usermonth);
//myday=parseInt(userday);
myyear=useryear;
mymonth=usermonth;
myday=userday;
if (myyear < 1950 || myyear > 2050 ||mymonth < 1 ||mymonth > 12 || myday < 1 || myday > 31)
return (false);
if(mymonth==4 || mymonth==6 || mymonth==9 || mymonth==11)
{
if(myday>30)
return (false);
}
if(myyear%4==0)
{
if((myyear%100==0 && myyear%400==0) || myyear%100!=0)
{
if(mymonth==2 && myday>29)
return (false);
else
return (true);
}
}
else
{
if(mymonth==2 && myday>28)
return (false);
else
return (true);
}
}
</script>";
#endregion
#region 验证值大小
public static string CheckSize = @"<script type=""text/javascript"">
//判断value的大小是否由符合标准
function CheckSize(obj,min,max)
{
var val=obj.value;
if (val=='' || min=='' || max=='' ||val=='-')return;
var a=val.match(/\./ig);
if (a!=null && a.length>1)document.getElementById(obj.id).value='';
var b=val.match(/\-/ig);
if (b!=null && b.length>1)document.getElementById(obj.id).value='';
if (b!=null && b.length==1 && val.substring(0,1)!='-')document.getElementById(obj.id).value=obj.value.replace('-','');
var maxval = parseFloat(max);
var minval = parseFloat(min);
var selval = parseFloat(val);
if (minval>maxval)return;
if (isNaN(selval)){
alert(','+selval);
obj.value='';
}
if (!isNaN(maxval)){
if (selval > maxval){
alert(','+maxval);
document.getElementById(obj.id).value='';
}
}
}
function CheckMinSize(obj,min)
{
var val=obj.value;
if (val=='' || min=='')return;
var a=val.match(/\./ig);
if (a!=null && a.length>1)document.getElementById(obj.id).value='';
var b=val.match(/\-/ig);
if (b!=null && b.length>1)document.getElementById(obj.id).value='';
if (b!=null && b.length==1 && val.substring(0,1)!='-')document.getElementById(obj.id).value='';
var minval = parseFloat(min);
var selval = parseFloat(val);
if (isNaN(selval)){
alert(','+selval);
obj.value='';
}
if (!isNaN(minval)){
if (selval < minval){
alert(','+minval);
document.getElementById(obj.id).value='';
}
}
}
function CheckDate(obj,minDate,maxDate,defaultDate)
{
var val=obj.value;
if (maxDate=='' || minDate=='' || val=='')return;
var minval = Date.parse(minDate);
var maxval = Date.parse(maxDate);
var selval = Date.parse(val);
if (isNaN(selval))
{
obj.value=defaultDate;
return;
}
if (!isNaN(maxval))
{
if (selval > maxval)
{
obj.value=defaultDate;
}
}
if (!isNaN(minval)){
if (selval < minval){
obj.value=defaultDate;
}
}
}
</script>";
#endregion
#region 格式化数值
public static string FormatNumber = @"<script language=""JavaScript"" type=""text/javascript"">
function FormatNumber(srcStr,nAfterDot) //nAfterDot小数位数
{
   var srcStr,nAfterDot;
   var resultStr,nTen;
if (isNaN(srcStr)==true)return 0;
   srcStr = ''+srcStr+'';
   strLen = srcStr.length;
   dotPos = srcStr.indexOf('.',0);
   if (dotPos == -1){
     resultStr = srcStr+'.';
     for (i=0;i<nAfterDot;i++){
       resultStr = resultStr+'0';
     }
     return resultStr;
   }
   else{
     if ((strLen - dotPos - 1) >= nAfterDot){
       nAfter = dotPos + nAfterDot + 1;
       nTen =1;
       for(j=0;j<nAfterDot;j++){
         nTen = nTen*10;
       }
       resultStr = Math.round(parseFloat(srcStr)*nTen)/nTen;
       return resultStr;
     }
     else{
       resultStr = srcStr;
       for (i=0;i<(nAfterDot - strLen + dotPos + 1);i++){
         resultStr = resultStr+'0';
       }
       return resultStr;
     }
   }
}
</script>";
#endregion
#region 权限设置
public static string PopedomSetting = @"<script language=""JavaScript"" type=""text/javascript"">
function PopedomSetting(ControlName)
{
var frm = document.forms[0].getElementsByTagName('input');
var re = new RegExp(ControlName);
for (i = 0; i < frm.length; i++) {
if (frm[i].type!='Button' && frm[i].type!='image' && frm[i].type!='reset' && frm[i].type!='submit')continue;
if (frm[i].id.length>=10 && frm[i].id.substring(0,10)=='btn_Select')continue; //排除查询按钮
var val = frm[i].id.match(re);
if (val == null || val.length == 0) continue;
frm[i].disabled = true;
}
}
</script>";
#endregion
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

@ -0,0 +1,69 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
namespace HuizhongLibrary
{
public class LocalIpAddress
{
public static string GetIPAddress
{
get
{
string result = String.Empty;
result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (result != null && result != String.Empty)
{
//可能有代理
if (result.IndexOf(".") == -1) //没有“.”肯定是非IPv4格式
result = null;
else
{
if (result.IndexOf(",") != -1)
{
//有“,”估计多个代理。取第一个不是内网的IP。
result = result.Replace(" ", "").Replace("'", "");
string[] temparyip = result.Split(",;".ToCharArray());
for (int i = 0; i < temparyip.Length; i++)
{
if (IsIPAddress(temparyip[i]) && temparyip[i].Substring(0, 3) != "10." && temparyip[i].Substring(0, 7) != "192.168" && temparyip[i].Substring(0, 7) != "172.16.")
{
return temparyip[i]; //找到不是内网的地址
}
}
}
else if (IsIPAddress(result)) //代理即是IP格式
return result;
else
result = null; //代理中的内容 非IP取IP
}
}
string IpAddress = (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null && HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != String.Empty) ? HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] : HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
if (null == result || result == String.Empty)
result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
if (result == null || result == String.Empty)
result = HttpContext.Current.Request.UserHostAddress;
return result;
}
}
#region bool IsIPAddress(str1) 判断是否是IP格式
/**//// <summary>
/// 判断是否是IP地址格式 0.0.0.0
/// </summary>
/// <param name="str1">待判断的IP地址</param>
/// <returns>true or false</returns>
public static bool IsIPAddress(string str1)
{
if (str1 == null || str1 == string.Empty || str1.Length < 7 || str1.Length > 15) return false;
string regformat = @"^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$";
Regex regex = new Regex(regformat, RegexOptions.IgnoreCase);
return regex.IsMatch(str1);
}
#endregion
}
}

@ -0,0 +1,164 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
namespace HuizhongLibrary.Control
{
[DefaultProperty("Text")]
[ToolboxData("<{0}:MaskedTextBox runat=server></{0}:MaskedTextBox>")]
public class MaskedTextBox : TextBox
{
// private InputMode m_InputMode = InputMode.None;
/// <summary>
/// 输入模式
/// </summary>
[Description("输入模式"), DefaultValue("None"), Category("扩展"), NotifyParentProperty(true)]
public virtual InputMode InputMode
{
get
{
if (this.ViewState["InputMode"]==null){return InputMode.None;}
else{return (InputMode)this.ViewState["InputMode"]; }
}
set
{
this.ViewState["InputMode"] = value;
}
}
// private float m_MinValue=0;
/// <summary>
/// 最小值
/// </summary>
[Description("最小值"), DefaultValue("0"), Category("扩展"), NotifyParentProperty(true)]
public virtual float MinValue
{
get
{
if (this.ViewState["MinValue"]==null){return 0;}
else{return (float)this.ViewState["MinValue"]; }
}
set
{
this.ViewState["MinValue"] = value;
}
}
// private float m_MaxValue=float.MaxValue;
/// <summary>
/// 最大值
/// </summary>
[Description("最大值"), DefaultValue("0"), Category("扩展"), NotifyParentProperty(true)]
public virtual float MaxValue
{
get
{
if (this.ViewState["MaxValue"]==null){return float.MaxValue;}
else{return (float)this.ViewState["MaxValue"]; }
}
set
{
this.ViewState["MaxValue"] = value;
}
}
public MaskedTextBox()
{
//this.PreRender += new EventHandler(MaskedTextBox_PreRender);
this.Init += new EventHandler(MaskedTextBox_Init);
}
void MaskedTextBox_Init(object sender, EventArgs e)
{
if (this.ReadOnly == true)
{
this.ReadOnly = false;
Attributes.Add("readOnly", "true");
}
Attributes.Add("autocomplete", "off");
if (this.InputMode == InputMode.DateTime) Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "TextCalendar", JavaScriptConstant.DateMonth);
if (this.InputMode == InputMode.Float) Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "KeyDown_float", JavaScriptConstant.KeyDown_float);
if (this.InputMode == InputMode.Int) Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "KeyDown_int", JavaScriptConstant.KeyDown_int);
if (this.InputMode == InputMode.Float || this.InputMode == InputMode.Int || this.InputMode == InputMode.MyFloat) Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "CheckSize", JavaScriptConstant.CheckSize);
Registeronkeyup();
}
void MaskedTextBox_PreRender(object sender, EventArgs e)
{
if (this.ReadOnly == true)
{
this.ReadOnly = false;
Attributes.Add("readOnly", "true");
}
Attributes.Add("autocomplete", "off");
if (this.InputMode==InputMode.DateTime)Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "TextCalendar", JavaScriptConstant.DateMonth);
if (this.InputMode == InputMode.Float) Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "KeyDown_float", JavaScriptConstant.KeyDown_float);
if (this.InputMode == InputMode.Int) Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "KeyDown_int", JavaScriptConstant.KeyDown_int);
if (this.InputMode == InputMode.Float || this.InputMode == InputMode.Int||this.InputMode==InputMode.MyFloat) Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "CheckSize", JavaScriptConstant.CheckSize);
Registeronkeyup();
}
#region 注册判断脚本
private void Registeronkeyup()
{
if (this.Attributes["MinValue"] == null)
{
this.Attributes.Add("MinValue", this.MinValue.ToString());
this.Attributes.Add("MaxValue", this.MaxValue.ToString());
}
else
{
this.Attributes["MinValue"]=this.MinValue.ToString();
this.Attributes["MaxValue"] = this.MaxValue.ToString();
}
//onkeyup
switch (this.InputMode)
{
case InputMode.DateTime:
if (this.Attributes["onfocus"] == null) { this.Attributes.Add("onfocus", "setday(this);"); }
else { this.Attributes["onfocus"] = "setday(this);" + this.Attributes["onfocus"].ToString(); }
break;
case InputMode.Int:
if (this.Attributes["onkeydown"] == null) { this.Attributes.Add("onkeydown", "KeyDown_int(this,this.MinValue);"); }
if (this.Attributes["onkeyup"] == null) { this.Attributes.Add("onkeyup", "CheckSize(this,this.MinValue,this.MaxValue);"); }
if (this.Attributes["onblur"] == null) { this.Attributes.Add("onblur", "CheckMinSize(this,this.MinValue);"); }
break;
case InputMode.Float:
if (this.Attributes["onkeydown"] == null) { this.Attributes.Add("onkeydown", "KeyDown_float(this,this.MinValue);"); }
if (this.Attributes["onkeyup"] == null) { this.Attributes.Add("onkeyup", "CheckSize(this,this.MinValue,this.MaxValue);"); }
if (this.Attributes["onblur"] == null) { this.Attributes.Add("onblur", "CheckMinSize(this,this.MinValue);"); }
break;
default:
break;
}
if (this.InputMode == InputMode.None) return;
if (this.Attributes["style"] == null) { this.Attributes.Add("style", "ime-mode: disabled;"); }
else
{
if (Regex.IsMatch(this.Attributes["style"].ToString(), "ime-mode.{1}") == false) this.Attributes["style"] = "ime-mode: disabled;" + this.Attributes["style"].ToString();
}
}
#endregion
}
public enum InputMode
{
None = 0,
DateTime = 1,
Int = 2,
Float = 3,
MyFloat = 4
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

@ -0,0 +1,55 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HuizhongLibrary
{
#region JavaDataTable用于JavaScript对象交互
public class JavaDataTable
{
public JavaDataTableColumns Columns { get; set; }
public JavaDataTableRows Rows { get; set; }
public JavaDataTable()
{
Columns = new JavaDataTableColumns();
Rows = new JavaDataTableRows();
}
}
public class JavaDataTableColumn
{
public string ColumnName { get; set; }
}
public class JavaDataTableColumns : List<JavaDataTableColumn>
{
public int IndexOf(string ColumnName)
{
foreach (var item in this)
{
if (item.ColumnName == ColumnName) return this.IndexOf(item);
}
return -1;
}
}
public class JavaDataTableRow
{
public List<object> ItemArray { get; set; }
public JavaDataTableRow()
{
ItemArray = new List<object>();
}
}
public class JavaDataTableRows : List<JavaDataTableRow>
{
}
#endregion
}

@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HuizhongLibrary.Data
{
/// <summary>
/// JSON对象
/// </summary>
/// <typeparam name="T"></typeparam>
public class JsonModel<T>
{
/// <summary>
/// 数据集
/// </summary>
public T DataSource { get; set; }
public T DataSource2 { get; set; }
/// <summary>
/// 行数量
/// </summary>
public int RowCount { get; set; }
public int RowCount2 { get; set; }
/// <summary>
/// 错误信息
/// </summary>
public string ErrorMsg { get; set; }
public int allnum { get; set; }
public JsonModel()
{
RowCount = 0;
ErrorMsg = "";
}
}
}

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HuizhongLibrary.Models
{
public class PostDateClass
{
public string Key { get; set; }
public string Value { get; set; }
public int Type { get; set; }
}
}

@ -0,0 +1,331 @@
using HuizhongLibrary.ReportPrint;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
namespace HuizhongLibrary.Models
{
public class JsonTable
{
public int ColumnNumber { get; set; }
public int RowCount { get; set; }
//不要使用
public List<JsonCell> Cells { get; set; }
public List<List<JsonCell>> Rows { get; set; }
public JsonTable()
{
Cells = new List<JsonCell>();
Rows = new List<List<JsonCell>>();
}
public string ExportExcel()
{
MicrosoftExcel obj = new MicrosoftExcel();
return obj.Export("",this);
}
#region 导入DataTable
public void ImportDataTable(DataTable tb)
{
this.ColumnNumber = tb.Columns.Count;
this.RowCount= tb.Rows.Count;
foreach (DataColumn col in tb.Columns)
{
JsonCell cell = new JsonCell();
cell.IsHader = true;
cell.CellText = col.ColumnName;
this.Cells.Add(cell);
}
foreach (DataRow row in tb.Rows)
{
foreach (DataColumn col in tb.Columns)
{
JsonCell cell = new JsonCell();
cell.IsHader = false;
if (row.IsNull(col.ColumnName) == false)
{
if (col.DataType == typeof(decimal))
{
cell.CellText = Convert.ToDecimal(row[col.ColumnName]).ToString("0.########");
}
else
{
cell.CellText = Convert.ToString(row[col.ColumnName]);
}
}
this.Cells.Add(cell);
}
}
}
#endregion
#region 导入DataTable_Rows
public void ImportDataTable_ForRows(DataTable tb)
{
this.ColumnNumber = tb.Columns.Count;
this.RowCount = tb.Rows.Count;
List<JsonCell> jsonRow = new List<JsonCell>();
this.Rows.Add(jsonRow);
foreach (DataColumn col in tb.Columns)
{
JsonCell cell = new JsonCell();
cell.IsHader = true;
cell.CellText = col.ColumnName;
jsonRow.Add(cell);
}
foreach (DataRow row in tb.Rows)
{
jsonRow = new List<JsonCell>();
this.Rows.Add(jsonRow);
foreach (DataColumn col in tb.Columns)
{
JsonCell cell = new JsonCell();
cell.IsHader = false;
if (row.IsNull(col.ColumnName) == false)
{
if (col.DataType == typeof(decimal))
{
cell.CellText = Convert.ToDecimal(row[col.ColumnName]).ToString("0.########");
}
else
{
cell.CellText = Convert.ToString(row[col.ColumnName]);
}
}
jsonRow.Add(cell);
}
}
}
#endregion
#region 计算单元格合并
public void MathMerge()
{
foreach (List<JsonCell> row in this.Rows)
{
int rowIndex = this.Rows.IndexOf(row);
for (int i = 0; i < row.Count; i++)
{
JsonCell cell = row[i];
if (cell.RowSpan > 1)
{
//如果跨行数等于>1,那么添加,计算本单元格所需高度
for (int ii = 1; ii < cell.RowSpan; ii++)
{
this.Rows[rowIndex + ii][i].ColSpan = 0;
this.Rows[rowIndex + ii][i].RowSpan = 0;
}
}
if (cell.ColSpan > 1)
{ //如果跨列数大于1那么计算本单元格所需宽度
for (int ii = 1; ii < cell.ColSpan; ii++)
{
row[i + ii].ColSpan = 0;
row[i + ii].RowSpan = 0;
//cell.Width += row[i + ii].Width;
}
}
//如果不是第一行,并且左边与上边的单元格属性为隐藏,那么隐藏单元格
if (rowIndex > 0 && i > 0)
{
if (row[i - 1].RowSpan == 0 && this.Rows[rowIndex - 1][i].RowSpan !=1)
{
cell.RowSpan = 0;
}
}
}
}
}
#endregion
#region 交换列
public void ColumnExchange(int Column,int Column2)
{
foreach (var item in this.Cells)
{
}
}
#endregion
}
public class JsonCell
{
public bool IsHader { get; set; }
public string CellText { get; set; }
public int ColSpan { get; set; }
public int RowSpan { get; set; }
public JsonCell()
{
CellText = "";
ColSpan = 1;
RowSpan = 1;
}
public JsonCell(string CellText, int ColSpan,int RowSpan,bool IsHader)
{
this.CellText = CellText;
this.ColSpan = ColSpan;
this.RowSpan = RowSpan;
this.IsHader = IsHader;
}
}
public class JsonTable<T>
{
public int ColumnNumber { get; set; }
public int RowCount { get; set; }
public List<JsonCell<T>> Cells { get; set; }
public List<List<JsonCell<T>>> Rows { get; set; }
public JsonTable()
{
Cells = new List<JsonCell<T>>();
Rows = new List<List<JsonCell<T>>>();
}
#region 导入DataTable
public void ImportDataTable(DataTable tb)
{
this.ColumnNumber = tb.Columns.Count;
this.RowCount = tb.Rows.Count;
foreach (DataColumn col in tb.Columns)
{
JsonCell<T> cell = new JsonCell<T>();
cell.IsHader = true;
cell.CellText = col.ColumnName;
this.Cells.Add(cell);
}
foreach (DataRow row in tb.Rows)
{
foreach (DataColumn col in tb.Columns)
{
JsonCell<T> cell = new JsonCell<T>();
cell.IsHader = false;
if (row.IsNull(col.ColumnName) == false)
{
if (col.DataType == typeof(decimal))
{
cell.CellText = Convert.ToDecimal(row[col.ColumnName]).ToString("0.########");
}
else
{
cell.CellText = Convert.ToString(row[col.ColumnName]);
}
}
this.Cells.Add(cell);
}
}
}
#endregion
#region 导入DataTable_Rows
public void ImportDataTable_ForRows(DataTable tb)
{
this.ColumnNumber = tb.Columns.Count;
this.RowCount = tb.Rows.Count;
List<JsonCell<T>> jsonRow = new List<JsonCell<T>>();
this.Rows.Add(jsonRow);
foreach (DataColumn col in tb.Columns)
{
JsonCell<T> cell = new JsonCell<T>();
cell.IsHader = true;
cell.CellText = col.ColumnName;
jsonRow.Add(cell);
}
foreach (DataRow row in tb.Rows)
{
jsonRow = new List<JsonCell<T>>();
this.Rows.Add(jsonRow);
foreach (DataColumn col in tb.Columns)
{
JsonCell<T> cell = new JsonCell<T>();
cell.IsHader = false;
if (row.IsNull(col.ColumnName) == false)
{
if (col.DataType == typeof(decimal))
{
cell.CellText = Convert.ToDecimal(row[col.ColumnName]).ToString("0.########");
}
else
{
cell.CellText = Convert.ToString(row[col.ColumnName]);
}
}
jsonRow.Add(cell);
}
}
}
#endregion
#region 计算单元格合并
public void MathMerge()
{
foreach (List<JsonCell<T>> row in this.Rows)
{
int rowIndex = this.Rows.IndexOf(row);
for (int i = 0; i < row.Count; i++)
{
JsonCell<T> cell = row[i];
if (cell.RowSpan > 1)
{
//如果跨行数等于>1,那么添加,计算本单元格所需高度
for (int ii = 1; ii < cell.RowSpan; ii++)
{
this.Rows[rowIndex + ii][i].ColSpan = 0;
this.Rows[rowIndex + ii][i].RowSpan = 0;
}
}
if (cell.ColSpan > 1)
{ //如果跨列数大于1那么计算本单元格所需宽度
for (int ii = 1; ii < cell.ColSpan; ii++)
{
row[i + ii].ColSpan = 0;
row[i + ii].RowSpan = 0;
//cell.Width += row[i + ii].Width;
}
}
//如果不是第一行,并且左边与上边的单元格属性为隐藏,那么隐藏单元格
if (rowIndex > 0 && i > 0)
{
if (row[i - 1].RowSpan == 0 && this.Rows[rowIndex - 1][i].RowSpan !=1)
{
cell.RowSpan = 0;
}
}
}
}
}
#endregion
}
public class JsonCell<T>
{
public bool IsHader { get; set; }
public string CellText { get; set; }
public int ColSpan { get; set; }
public int RowSpan { get; set; }
public T ExtModel { get; set; }
public JsonCell()
{
CellText = "";
ColSpan = 1;
RowSpan = 1;
}
public JsonCell(string CellText, int ColSpan, int RowSpan, bool IsHader)
{
this.CellText = CellText;
this.ColSpan = ColSpan;
this.RowSpan = RowSpan;
this.IsHader = IsHader;
}
public JsonCell(string CellText, int ColSpan, int RowSpan, bool IsHader,T model)
{
this.CellText = CellText;
this.ColSpan = ColSpan;
this.RowSpan = RowSpan;
this.IsHader = IsHader;
this.ExtModel = model;
}
}
}

@ -0,0 +1,56 @@
namespace HuizhongLibrary.MyAlphaControl
{
partial class AlphaLabel
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region 组件设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.SuspendLayout();
//
// pictureBox1
//
this.pictureBox1.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBox1.Location = new System.Drawing.Point(0, 0);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(150, 150);
//
// AlphaLabel
//
this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.Controls.Add(this.pictureBox1);
this.Name = "AlphaLabel";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.PictureBox pictureBox1;
}
}

@ -0,0 +1,440 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
namespace HuizhongLibrary.MyAlphaControl
{
public partial class AlphaLabel : UserControl
{
private Bitmap m_BackgroundImage;
/// <summary>
/// 背景图片
/// </summary>
public new Bitmap BackgroundImage
{
get { return m_BackgroundImage; }
set
{
m_BackgroundImage = value;
}
}
private StringPool m_ScrollText = new StringPool();
/// <summary>
/// 滚动文字列表
/// </summary>
public StringPool ScrollText
{
get { return m_ScrollText; }
set { m_ScrollText = value; }
}
private int m_ScrollTop = 0;
public int ScrollTop
{
get { return m_ScrollTop; }
set { m_ScrollTop = value; }
}
private int m_ScrollLeft = 0;
public int ScrollLeft
{
get { return m_ScrollLeft; }
set { m_ScrollLeft = value; }
}
private string m_MoveDirection = "None";
/// <summary>
/// 移动方向(None,Left,Right,Top,Boottom)
/// </summary>
public string MoveDirection
{
get { return m_MoveDirection; }
set { m_MoveDirection = value; }
}
private int m_DurationStep = 5;
/// <summary>
/// 每次移动多少个像素(默认一个像素,最慢的移动速度)
/// </summary>
public int DurationStep
{
get { return m_DurationStep; }
set { m_DurationStep = value; }
}
private StringFormat m_TextAlign = new StringFormat();
/// <summary>
/// 文本对齐
/// </summary>
public StringFormat TextAlign
{
get { return m_TextAlign; }
set { m_TextAlign = value; }
}
private int m_Interval = 1;
public int Interval
{
get { return m_Interval; }
set { m_Interval = value; }
}
private int m_TimeOut = 30;
public int TimeOut
{
get { return m_TimeOut; }
set { m_TimeOut = value; }
}
private bool m_TickEnable = false;
/// <summary>
/// 是否启用倒计时
/// </summary>
public bool TickEnable
{
get { return m_TickEnable; }
set
{
m_TickEnable = value;
if (value == true) { StartTimeer(); }
else { StopTimeer(); }
}
}
private Color m_BorderColor = Color.Black;
/// <summary>
/// 边框粗细
/// </summary>
public Color BorderColor
{
get { return m_BorderColor; }
set { m_BorderColor = value; }
}
private bool m_Visible = true;
public new bool Visible
{
get { return m_Visible; }
set
{
m_Visible = value;
base.Visible = value;
}
}
private string m_NullText = "";
/// <summary>
/// 空时显示的文本
/// </summary>
public string NullText
{
get { return m_NullText; }
set { m_NullText = value; }
}
public bool ShowDateTime = false; //是否显示时间
public string DateTimeFormat = "yyyy年M月d日HH:mm:ss";
public int MaxRowNumber = 1;
/// <summary>
/// 当倒计时正常终止时触发
/// </summary>
public event Action<AlphaLabel> TimeTick;
private int ScrollTextWidth = 0;
private int SRCCOPY = 13369376;
private Graphics G1;
private Graphics G2;
private IntPtr hdc1;
private IntPtr hdc2;
public AlphaLabel()
{
TextAlign.LineAlignment = StringAlignment.Near;
TextAlign.Alignment = StringAlignment.Near;
InitializeComponent();
}
#region 画背景图片(用于假透明显示)
public void SetBackground(Bitmap bmp)
{
if (bmp == null) return;
BackgroundImage = new Bitmap(this.Bounds.Width, this.Bounds.Height);
Graphics G2 = Graphics.FromImage(BackgroundImage);
G2.DrawImage(bmp, new Rectangle(0, 0, this.Bounds.Width, this.Bounds.Height), new Rectangle(this.Left, this.Top, this.Bounds.Width, this.Bounds.Height), GraphicsUnit.Pixel);
G2.Dispose();
//this.BorderStyle = BorderStyle.None;
//this.BackColor=Color.Transparent;
}
#endregion
#region 重画文字
//private byte[] CacheImage = null;
public void DrawString(int x, int y, string s)
{
Bitmap bmp = null;
if (BackgroundImage == null)
{
bmp = new Bitmap(this.Bounds.Width, this.Bounds.Height);
}
else
{
//复制图片
//CacheImage = CustomIO.GetPhoto(this.BackgroundImage);
bmp = (Bitmap)BackgroundImage.Clone();
}
G1 = this.CreateGraphics();
G2 = Graphics.FromImage(bmp);
hdc1 = G1.GetHdc();
hdc2 = G2.GetHdc();
if (BackgroundImage == null) G2.Clear(this.BackColor);
Brush backBrush = new SolidBrush(this.ForeColor);
G2.DrawString(s, this.Font, backBrush, x, y);
backBrush.Dispose();
SystemInfo.BitBlt(hdc1, 0, 0, Width, Height, hdc2, 0, 0, SRCCOPY);
G1.ReleaseHdc(hdc1);
G2.ReleaseHdc(hdc2);
G1.Dispose();
G2.Dispose();
bmp.Dispose();
//if (pictureBox1.Image != null) pictureBox1.Image.Dispose();
//pictureBox1.Image = bmp;
//GC.Collect();
}
#endregion
#region 移动文字
public void MoveText()
{
if (this.MoveDirection == "Left")
{
if (this.ScrollLeft <= -this.ScrollTextWidth) { this.ScrollLeft = this.Width; AddScrollTextIndex(); }
this.ScrollLeft -= this.DurationStep;
}
if (this.MoveDirection == "Right")
{
if (this.ScrollLeft >= this.Width) { this.ScrollLeft = -this.ScrollTextWidth; AddScrollTextIndex(); }
this.ScrollLeft += this.DurationStep;
}
if (this.MoveDirection == "Top")
{
if (this.ScrollTop <= 0) { this.ScrollTop = this.Height; AddScrollTextIndex(); }
this.ScrollTop -= this.DurationStep;
}
if (this.MoveDirection == "Bottom")
{
if (this.ScrollTop >= this.Height) { this.ScrollTop = 0; AddScrollTextIndex(); }
this.ScrollTop += this.DurationStep;
}
this.DrawString(this.ScrollLeft, this.ScrollTop, this.Text);
}
#endregion
#region 增加索引
void AddScrollTextIndex()
{
if (string.IsNullOrEmpty(this.Text) == false) ScrollText.CheckIn(this.Text);
if (ScrollText.Available == 0) this.Text = this.NullText;
this.Text = ScrollText.CheckOut();
InitScrollTextSize();
//ScrollTextIndex++;
//if (ScrollTextIndex >= this.ScrollText.Count)
//{
// ScrollTextIndex = 0;
//}
}
#endregion
#region 计算文字大小
private SizeF MeasureString(string Text, Font font)
{
Bitmap bmp = new Bitmap(1, 1, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
Graphics g = Graphics.FromImage(bmp);
SizeF s = g.MeasureString(Text, font);
return s;
}
#endregion
#region 开始计时
Timer time1 = new Timer();
private int TimeNumber=0;
public void StartTimeer()
{
TimeNumber = this.TimeOut;
time1.Interval = this.Interval * 1000;
time1.Tick += time1_Tick;
time1.Enabled = true;
}
void time1_Tick(object sender, EventArgs e)
{
if (ShowDateTime == true)
{
this.Text = DateTime.Now.ToString(DateTimeFormat);
}
else
{
if (this.TimeNumber == 0)
{
StopTimeer();
TimeNumber = this.TimeOut;
if (this.TimeTick != null) this.TimeTick(this);
return;
}
this.Text = TimeNumber.ToString();
TimeNumber--;
}
this.Refresh();
}
#endregion
#region 停止计时
public void StopTimeer()
{
time1.Tick -= time1_Tick;
time1.Enabled = false;
}
#endregion
#region 刷新
public new void Refresh()
{
Bitmap bmp = null;
if (BackgroundImage == null)
{
bmp = new Bitmap(this.Bounds.Width, this.Bounds.Height);
}
else
{
bmp = (Bitmap)BackgroundImage.Clone();
}
//G1 = this.CreateGraphics();
G2 = Graphics.FromImage(bmp);
//hdc1 = G1.GetHdc();
//hdc2 = G2.GetHdc();
if (BackgroundImage == null) G2.Clear(this.BackColor);
Brush backBrush = new SolidBrush(this.ForeColor);
//if (this.Border > 0) g.DrawRectangle(new Pen(BorderColor, this.Border), this.Bounds);
//if (string.IsNullOrEmpty(this.Text) == false) g.DrawString(this.Text, this.Font, backBrush, new RectangleF(0, 0, this.Bounds.Width, this.Bounds.Height), TextAlign);
if (string.IsNullOrEmpty(this.Text) == false)
{
G2.DrawString(this.Text, this.Font, backBrush, new RectangleF(0, 0, this.Width, this.Height), this.TextAlign);
//if (TextAlign.Alignment == StringAlignment.Near)
//{
// G2.DrawString(this.Text, this.Font, backBrush, 0, 0);
//}
//if (TextAlign.Alignment == StringAlignment.Center)
//{
// float TextWidth = MeasureString(this.Text, this.Font).Width;
// float x = (this.Width - TextWidth) / 2;
// G2.DrawString(this.Text, this.Font, backBrush, x, 0);
//}
//if (TextAlign.Alignment == StringAlignment.Far)
//{
// float TextWidth = MeasureString(this.Text + "AA", this.Font).Width;
// float x = (this.Width - TextWidth);
// G2.DrawString(this.Text, this.Font, backBrush, x, 0);
//}
}
backBrush.Dispose();
//SystemInfo.BitBlt(hdc1, 0, 0, Width, Height, hdc2, 0, 0, SRCCOPY);
//G1.ReleaseHdc(hdc1);
//G2.ReleaseHdc(hdc2);
//G1.Dispose();
//G2.Dispose();
//bmp.Dispose();
if (pictureBox1.Image != null) pictureBox1.Image.Dispose();
pictureBox1.Image = bmp;
}
#endregion
#region 新增文本行
public void AddRowText(string Text)
{
if (this.ScrollText.Available == this.MaxRowNumber)
{
this.ScrollText.CheckOut();
}
this.ScrollText.CheckIn(Text);
string ss = "";
for (int i = 0; i < this.ScrollText.Available; i++)
{
ss+=this.ScrollText.Peek()+ "\n";
}
ss = ss.Substring(0, ss.Length - 1);
this.Text = ss;
}
#endregion
#region 清除文本
public void ClearRowText()
{
this.ScrollText.Clear();
this.Text = "";
}
#endregion
#region 移除滚动文字
public void Remove(string item)
{
this.ScrollText.Remove(item);
if (this.Text == item) this.Text = "";
if (ScrollText.Available == 0)
{
this.Text = this.NullText;
}
else
{
this.Text = this.ScrollText.CheckOut();
}
if (this.MoveDirection == "Left")
{
this.ScrollLeft = this.Width;
}
if (this.MoveDirection == "Right")
{
this.ScrollLeft = 0;
}
if (this.MoveDirection == "Top")
{
this.ScrollTop = this.Height;
}
if (this.MoveDirection == "Bottom")
{
this.ScrollTop = 0;
}
InitScrollTextSize();
}
#endregion
#region 初始化文字大小
public void InitScrollTextSize()
{
this.ScrollTextWidth =Convert.ToInt32(MeasureString(this.Text, this.Font).Width);
}
#endregion
#region 隐藏背景控件
public void VisiblePictureBox()
{
pictureBox1.Visible = false;
}
#endregion
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
}
}
}

@ -0,0 +1,123 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="$this.FormFactorShadowProperty" xml:space="preserve">
<value>WEBPAD</value>
</metadata>
</root>

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
namespace HuizhongLibrary.MyAlphaControl
{
public class ControlInfoExtend
{
public string TypeName = "";
public string Name = "";
public string SendText = "";
public string LogicName = "";
public string WindowName = "";
public bool SendCache = false;
public string SendKey = "";
public Image BackgroundImage = null;
}
}

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace HuizhongLibrary.MyAlphaControl
{
public class MyImageList
{
public string Name;
public string FilePath;
public DateTime? EndTime;
public int Interval;
}
}

@ -0,0 +1,57 @@
namespace HuizhongLibrary.MyAlphaControl
{
partial class MyPanel
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region 组件设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.SuspendLayout();
//
// pictureBox1
//
this.pictureBox1.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBox1.Location = new System.Drawing.Point(0, 0);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(311, 258);
//
// MyPanel
//
this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.Controls.Add(this.pictureBox1);
this.Name = "MyPanel";
this.Size = new System.Drawing.Size(311, 258);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.PictureBox pictureBox1;
}
}

@ -0,0 +1,363 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using HuizhongLibrary.Log;
using HuizhongLibrary;
namespace HuizhongLibrary.MyAlphaControl
{
public partial class MyPanel : UserControl
{
private Bitmap m_BackgroundImage;
/// <summary>
/// 背景图片
/// </summary>
public new Bitmap BackgroundImage
{
get { return m_BackgroundImage; }
set{ m_BackgroundImage = value; }
}
private PictureBoxSizeMode m_BackgroundSizeMode = PictureBoxSizeMode.Normal;
public PictureBoxSizeMode BackgroundSizeMode
{
get { return m_BackgroundSizeMode; }
set
{
m_BackgroundSizeMode = value;
pictureBox1.SizeMode = value;
}
}
private List<MyImageList> m_ImageArray = new List<MyImageList>();
public List<MyImageList> ImageArray
{
get { return m_ImageArray; }
set { m_ImageArray = value; }
}
private string m_ImageList = "";
public string ImageList
{
get { return m_ImageList; }
set { m_ImageList = value; }
}
private bool m_Visible = true;
public new bool Visible
{
get { return m_Visible; }
set
{
m_Visible = value;
base.Visible = value;
int index = 0;
//if (pictureBox1.Image == null && this.BackgroundImage != null) RefshImage();
pictureBox1.BringToFront();
foreach (System.Windows.Forms.Control ctrl in this.Controls)
{
index++;
if (index == 1) continue;
if (ctrl.Visible == true) ctrl.BringToFront();
}
//pictureBox1.SendToBack();
}
}
public bool IsRun = true;
public int MainTop = 0;
public int MainLeft = 0;
public int MainWidth = 0;
public int MainHeight = 0;
public int MaxWidth = 0;
public int MaxHeight = 0;
public int FlackMode = 0; //0全屏宣教1首页宣教
public event EventHandler FeelImage;
public event RemoveImageDelegate RemoveImage;
public delegate void RemoveImageDelegate(string ImageListName, string ImgName);
public event Action<string> RemoveScrollString;
public MyPanel()
{
InitializeComponent();
pictureBox1.Click += pictureBox1_Click;
}
void pictureBox1_Click(object sender, EventArgs e)
{
if (this.FeelImage != null) this.FeelImage(sender, e);
}
public int ImageIndex= 0;
#region 切换到上一页
public int PrevImage()
{
if (ImageArray.Count == 0)
{
this.BackgroundImage = null;
return 10;
}
ImageIndex--;
if (ImageIndex < 0) ImageIndex = ImageArray.Count - 1;
MyImageList model = CheckOut(ImageIndex);
if (model == null)
{
ImageIndex++;
return PrevImage();
}
try
{
DateTime dt = DateTime.Now;
if (File.Exists(model.FilePath) == false || (model.EndTime != null && dt > model.EndTime))
{
if (this.RemoveImage != null) this.RemoveImage(this.ImageList, model.Name);
RemoveAt(ImageIndex);
ImageIndex++;
return PrevImage();
}
this.BackgroundImage = CustomIO.GetBitmap(model.FilePath);
if (this.BackgroundImage == null)
{
if (this.RemoveImage != null) this.RemoveImage(this.ImageList, model.Name);
RemoveAt(ImageIndex);
ImageIndex++;
return PrevImage();
}
}
catch (Exception ex)
{
ErrorFollow.TraceWrite("NextImage", ex.StackTrace, ex.Message);
if (this.RemoveImage != null) this.RemoveImage(this.ImageList, model.Name);
RemoveAt(ImageIndex);
ImageIndex++;
return PrevImage();
}
return model.Interval;
}
#endregion
#region 切换到下一页
public int NextImage()
{
if (ImageArray.Count == 0)
{
this.BackgroundImage = null;
return 10;
}
ImageIndex++;
if (ImageIndex >= ImageArray.Count) ImageIndex = 0;
MyImageList model = CheckOut(ImageIndex);
if (model == null)
{
ImageIndex--;
return NextImage();
}
try
{
DateTime dt = DateTime.Now;
if (File.Exists(model.FilePath) == false || (model.EndTime != null && dt > model.EndTime))
{
if (this.RemoveImage != null) this.RemoveImage(this.ImageList, model.Name);
RemoveAt(ImageIndex);
ImageIndex--;
return NextImage();
}
this.BackgroundImage = CustomIO.GetBitmap(model.FilePath);
if (this.BackgroundImage == null)
{
if (this.RemoveImage != null) this.RemoveImage(this.ImageList, model.Name);
RemoveAt(ImageIndex);
ImageIndex--;
return NextImage();
}
}
catch (Exception ex)
{
ErrorFollow.TraceWrite("NextImage", ex.StackTrace, ex.Message);
if (this.RemoveImage != null) this.RemoveImage(this.ImageList, model.Name);
RemoveAt(ImageIndex);
ImageIndex--;
return NextImage();
}
return model.Interval;
}
#endregion
#region 刷新背景
public void RefshImage()
{
if (pictureBox1.Image != null) pictureBox1.Image.Dispose();
pictureBox1.Image = this.BackgroundImage;
GC.Collect();
}
#endregion
#region 新增图片
public void CheckIn(MyImageList item)
{
lock (ImageArray)
{
MyImageList Citem = null;
foreach (MyImageList item2 in ImageArray)
{
if (item2.Name == item.Name) Citem = item2;
}
if (Citem == null) { ImageArray.Add(item); }
else
{
Citem.EndTime = item.EndTime;
Citem.FilePath = item.FilePath;
Citem.Interval = item.Interval;
Citem.Name = item.Name;
}
}
if (ImageArray.Count == 1)
{
FirstImage();
RefshImage();
}
}
#endregion
#region 读取图片
public MyImageList CheckOut(int Index)
{
MyImageList model = null;
lock (ImageArray)
{
if (ImageArray.Count == 0) return null;
if (Index < 0 || Index > ImageArray.Count - 1)
{
Index = 0;
return null;
}
try
{
model=ImageArray[Index];
}
catch { }
}
return model;
}
#endregion
#region 清除全部图片
public void Clear()
{
lock (ImageArray)
{
ImageArray.Clear();
}
}
#endregion
#region 清除图片
public void RemoveAt(int Index)
{
lock (ImageArray)
{
if (ImageArray.Count == 0) return;
if (Index < 0 || Index > ImageArray.Count - 1) return;
ImageArray.RemoveAt(Index);
}
}
#endregion
#region 清除图片
public void Remove(string Name)
{
lock (ImageArray)
{
for (int i = 0; i < ImageArray.Count; i++)
{
if (ImageArray[i].Name != Name) continue;
ImageArray.RemoveAt(i);
break;
}
}
NextImage();
}
#endregion
#region 切换到首张图片
public void FirstImage()
{
ImageIndex = 0;
MyImageList model = CheckOut(ImageIndex);
if (model == null) { this.BackgroundImage = null; }
else { this.BackgroundImage = CustomIO.GetBitmap(model.FilePath); }
}
#endregion
#region 切换到最后一张图片
public void LastImage()
{
ImageIndex = ImageArray.Count-1;
MyImageList model = CheckOut(ImageIndex);
if (model == null) { this.BackgroundImage = null; }
else { this.BackgroundImage = CustomIO.GetBitmap(model.FilePath); }
}
#endregion
#region 缩放
public void Zoom()
{
if (FlackMode == 0 || ImageArray.Count == 0) return;
if (this.Width == MaxWidth)
{
this.Left = MainLeft;
this.Top = MainTop;
this.Width = MainWidth;
this.Height = MainHeight;
}
else
{
this.Left = 0;
this.Top = 0;
this.Width = MaxWidth;
this.Height = MaxHeight;
}
RefshImage();
}
#endregion
#region 计算文字大小
private SizeF MeasureString(string Text, Font font)
{
Bitmap bmp = new Bitmap(1, 1, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
Graphics g = Graphics.FromImage(bmp);
SizeF s = g.MeasureString(Text, font);
return s;
}
#endregion
#region 是否有需要播报的消息
public bool IsPlay()
{
if (this.IsRun == false) return false;
if (ImageArray.Count > 0) return true;
return false;
}
#endregion
#region 引发移除滚动文本事件
public void OnRemoveScrollString(string Name)
{
if (this.RemoveScrollString != null) this.RemoveScrollString(Name);
}
#endregion
}
}

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

@ -0,0 +1,143 @@
using HuizhongLibrary.Log;
using System;
using System.Collections.Generic;
using System.Text;
namespace HuizhongLibrary
{
#region 消息缓存池
public class StringPool
{
Queue<string> argsPool;
public StringPool()
{
argsPool = new Queue<string>();
}
#region 新增对象
public void CheckIn(string item)
{
if (this.Contains(item) == true) return;
lock (argsPool)
{
try
{
argsPool.Enqueue(item);
}
catch (Exception ex)
{
ErrorFollow.TraceWrite("StringPool.CheckIn", ex.StackTrace, ex.Message);
}
}
}
#endregion
#region 返回对象
public string CheckOut()
{
lock (argsPool)
{
try
{
if (argsPool.Count == 0) return null;
return argsPool.Dequeue();
}
catch (Exception ex)
{
ErrorFollow.TraceWrite("StringPool.CheckOut", ex.StackTrace, ex.Message);
}
return null;
}
}
#endregion
#region 返回缓存数量
public int Available
{
get
{
lock (argsPool)
{
try
{
return argsPool.Count;
}
catch (Exception ex)
{
ErrorFollow.TraceWrite("StringPool.Available", ex.StackTrace, ex.Message);
}
return 0;
}
}
}
#endregion
#region 移除
public void Clear()
{
lock (argsPool)
{
try
{
argsPool.Clear();
}
catch (Exception ex)
{
ErrorFollow.TraceWrite("stringPool.Clear", ex.StackTrace, ex.Message);
}
}
}
#endregion
#region 返回但不移除对象
public string Peek()
{
lock (argsPool)
{
try
{
if (argsPool.Count == 0) return null;
return argsPool.Peek();
}
catch (Exception ex)
{
ErrorFollow.TraceWrite("StringPool.Peek", ex.StackTrace, ex.Message);
}
return null;
}
}
#endregion
#region 移除
public void Remove(string item)
{
for (int i = 0; i < argsPool.Count; i++)
{
string s=CheckOut();
if (s == item) continue;
CheckIn(s);
}
}
#endregion
#region 是否已经存在
public bool Contains(string item)
{
lock (argsPool)
{
try
{
for (int i = 0; i < argsPool.Count; i++)
{
string s = CheckOut();
if (s == item) return true;
CheckIn(s);
}
}
catch (Exception ex)
{
ErrorFollow.TraceWrite("stringPool.Clear", ex.StackTrace, ex.Message);
}
}
return false;
}
#endregion
}
#endregion
}

@ -0,0 +1,382 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace HuizhongLibrary.Drawing2D
{
#region 我的图片
public class MyBitmap
{
private Bitmap BackgroundImage = null;
private Graphics MyGraphics = null;
private string FilePath = "";
public MyBitmap(string FilePath)
{
BackgroundImage=CustomIO.GetBitmap(FilePath);
MyGraphics = CreateGraphics();
}
public MyBitmap(byte[] images)
{
BackgroundImage = CustomIO.GetPhoto(images);
MyGraphics = CreateGraphics();
}
#region 创建画布
private Graphics CreateGraphics()
{
Graphics gp = Graphics.FromImage(BackgroundImage);
gp.PageUnit = GraphicsUnit.Pixel;
gp.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
gp.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
gp.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
gp.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver;
gp.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
gp.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
return gp;
}
#endregion
#region 去除内存
public void Dispose()
{
MyGraphics.Dispose();
BackgroundImage = null;
MyGraphics = null;
}
#endregion
#region 画表格
public void DrawTable(MyTable tb)
{
FormatGroups(tb);
int Left = tb.Left;
int Top = tb.Top;
Color TextColor = Color.FromName(tb.FontColor);
string BackColor = "";
foreach (var row in tb.Rows)
{
BackColor = row.BackColor;
for (int i = 0; i < tb.Columns.Count; i++)
{
MyCell cell = row.Cells[i];
if (cell.Visible == true)
{
if (string.IsNullOrEmpty(cell.FontColor) == false) { TextColor = Color.FromName(cell.FontColor); }
else { TextColor = Color.FromName(tb.FontColor); }
if (string.IsNullOrEmpty(cell.BackColor) == false) { BackColor = cell.BackColor; }
else { BackColor = row.BackColor; }
Rectangle rect = new Rectangle(Left, Top, tb.Columns[i].Width * cell.ColumnSpan, row.Height * cell.RowSpan);
if (string.IsNullOrEmpty(BackColor) == false)
{
SolidBrush br = new SolidBrush(Color.FromName(BackColor));
MyGraphics.FillRectangle(br, rect);
br.Dispose();
}
if (tb.ShowLine == true) MyGraphics.DrawRectangle(new Pen(Color.Black, tb.BorderWidth), rect);
if (cell.Img == null)
{
TextFormatFlags flags = TextFormatFlags.TextBoxControl | TextFormatFlags.WordBreak | TextFormatFlags.NoPadding;
if (cell.TextAlign == "Center") flags = flags | TextFormatFlags.HorizontalCenter;
if (cell.TextAlign == "Right") flags = flags | TextFormatFlags.Right;
if (cell.VerticalAlign == "Center") flags = flags | TextFormatFlags.VerticalCenter;
if (cell.VerticalAlign == "Bottom") flags = flags | TextFormatFlags.Bottom;
TextRenderer.DrawText(MyGraphics, cell.Text, cell.font, rect, TextColor, flags);
}
else
{
Bitmap bmp = CustomIO.GetBitmap(cell.Img.FilePath);
int TextTop = 0;
int TextLeft = 0;
int ImgTop = 0;
int ImgLeft = 0;
SizeF fs = GetFontSize(cell.font, cell.Text);
int TextHeight = Convert.ToInt32(fs.Height);
int TextWidth = Convert.ToInt32(fs.Width);
if (cell.TextAlign == "Center")
{
TextLeft = Left + ((tb.Columns[i].Width * cell.ColumnSpan - TextWidth - cell.Img.Width) / 2);
}
if (cell.TextAlign == "Right")
{
TextLeft = Left + (tb.Columns[i].Width * cell.ColumnSpan - TextWidth - cell.Img.Width);
}
if (string.IsNullOrEmpty(cell.TextAlign) == true || cell.TextAlign == "Left")
{
TextLeft = Left;
}
if (cell.VerticalAlign == "Center")
{
TextTop = Top + ((row.Height * cell.RowSpan - TextHeight) / 2);
ImgTop = Top + ((row.Height * cell.RowSpan - cell.Img.Height) / 2);
}
if (cell.VerticalAlign == "Bottom")
{
TextTop = Top + (row.Height * cell.RowSpan - TextHeight);
ImgTop = Top + (row.Height * cell.RowSpan - cell.Img.Height);
}
if (string.IsNullOrEmpty(cell.VerticalAlign) == true || cell.VerticalAlign == "Top")
{
TextTop = Top;
ImgTop = Top;
}
ImgLeft = TextLeft + TextWidth;
MyGraphics.DrawString(cell.Text, cell.font, new SolidBrush(TextColor), TextLeft, TextTop);
MyGraphics.DrawImage(bmp, ImgLeft, ImgTop, cell.Img.Width, cell.Img.Height);
}
}
Left += tb.Columns[i].Width;
}
Left = tb.Left;
Top += row.Height;
}
}
#endregion
#region 画文字
public void DrawString(MyString item)
{
FontStyle style = FontStyle.Regular;
if (item.IsBold == true) style = style | FontStyle.Bold;
if (item.IsItalic == true) style = style | FontStyle.Italic;
Font f = new Font(item.FontName, item.FontSize, style);
TextFormatFlags flags = TextFormatFlags.TextBoxControl | TextFormatFlags.WordBreak | TextFormatFlags.NoPadding;
if (item.TextAlign == "Center") flags = flags | TextFormatFlags.HorizontalCenter;
if (item.TextAlign == "Right") flags = flags | TextFormatFlags.Right;
if (item.VerticalAlign == "Center") flags = flags | TextFormatFlags.VerticalCenter;
if (item.VerticalAlign == "Bottom") flags = flags | TextFormatFlags.Bottom;
Color TextColor = Color.FromName(item.FontColor);
Rectangle rect = new Rectangle(item.Left, item.Top, item.Width, item.Height);
TextRenderer.DrawText(MyGraphics, item.Text, f, rect, TextColor, flags);
}
#endregion
#region 画图片
public void DrawImage(MyImage item)
{
Bitmap bmp = CustomIO.GetBitmap(item.FilePath);
//第一个柜形为要画的图片大小和坐标,第二个为要截取的图片坐标和大小
MyGraphics.DrawImage(bmp, new Rectangle(0, 0, item.Width, item.Height), new Rectangle(0, 0, bmp.Width, bmp.Height), GraphicsUnit.Pixel);
}
#endregion
#region 保存图片
public void Save(ImageFormat imgFormat)
{
if (string.IsNullOrEmpty(this.FilePath) == false) throw new Exception("保存文件路径不存在");
BackgroundImage.Save(this.FilePath,imgFormat);
}
#endregion
#region 另存为图片
public void SaveAs(string filePath, ImageFormat imgFormat)
{
if (File.Exists(filePath) == true) File.Delete(filePath);
BackgroundImage.Save(filePath, imgFormat);
}
#endregion
#region 返回行高
public int GetFontHeight(Font f)
{
return TextRenderer.MeasureText("测试", f).Height;
}
#endregion
#region 返回字体大小
public SizeF GetFontSize(Font f,string Text)
{
// return TextRenderer.MeasureText(Text, f);
return MyGraphics.MeasureString(Text, f);
}
#endregion
#region 合并单元格
void FormatGroups(MyTable tb)
{
FontStyle style = FontStyle.Regular;
if (tb.IsBold == true) style = style | FontStyle.Bold;
if (tb.IsItalic == true) style = style | FontStyle.Italic;
Font CurrentFont = new Font(tb.FontName, tb.FontSize * 72 / BackgroundImage.HorizontalResolution, style);
foreach (MyRow row in tb.Rows)
{
int rowIndex = tb.Rows.IndexOf(row);
for (int i = 0; i < tb.Columns.Count; i++)
{
MyCell cell = row.Cells[i];
if (string.IsNullOrEmpty(cell.FontName) == true)
{
cell.font = CurrentFont;
}
else
{
style = FontStyle.Regular;
if (cell.IsBold == true) style = style | FontStyle.Bold;
if (cell.IsItalic == true) style = style | FontStyle.Italic;
cell.font = new Font(cell.FontName, cell.FontSize * 72 / BackgroundImage.HorizontalResolution, style);
}
if (cell.RowSpan > 1)
{
//如果跨行数等于>1,那么添加,计算本单元格所需高度
//cell.Height = cell.Height * cell.RowSpan;
for (int ii = 1; ii < cell.RowSpan; ii++)
{
tb.Rows[rowIndex + ii].Cells[i].Visible = false;
tb.Rows[rowIndex + ii].Cells[i].VisibleState = false;
}
}
if (cell.ColumnSpan > 1)
{
//如果跨列数大于1那么计算本单元格所需宽度
//cell.Width = cell.Width * cell.ColumnSpan;
for (int ii = 1; ii < cell.ColumnSpan; ii++)
{
row.Cells[i + ii].Visible = false;
row.Cells[i + ii].VisibleState = true;
}
}
//如果不是第一行,并且左边与上边的单元格属性为隐藏,那么隐藏单元格
if (rowIndex != 0 && i > 0)
{
if (row.Cells[i - 1].Visible == false && row.Cells[i - 1].VisibleState == false && tb.Rows[rowIndex - 1].Cells[i].Visible == false && tb.Rows[rowIndex - 1].Cells[i].VisibleState == true)
{
cell.Visible = false;
}
}
}
}
}
#endregion
}
#endregion
#region 表对象
public class MyTable
{
public int Top { get; set; }
public int Left { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public bool ShowLine { get; set; }
public string FontColor { get; set; }
public string FontName { get; set; }
public float FontSize { get; set; }
public bool IsItalic { get; set; } //是否倾斜
public bool IsBold { get; set; } //是否加粗
public float BorderWidth { get; set; }
public List<MyRow> Rows { get; set; }
public List<MyColumn> Columns { get; set; }
public MyTable()
{
Rows = new List<MyRow>();
Columns = new List<MyColumn>();
BorderWidth = 1;
ShowLine = true;
FontName = "宋体";
FontColor = "Black";
FontSize = 12;
}
}
#endregion
#region 表格中的行
public class MyRow
{
public List<MyCell> Cells { get; set; }
public int Height { get; set; }
public string BackColor { get; set; }
public MyRow()
{
Cells = new List<MyCell>();
BackColor = "";
}
}
#endregion
#region 表格中的单元格
public class MyCell
{
public int Width { get; set; }
public int Height { get; set; }
public string FontColor { get; set; }
public string FontName { get; set; }
public float FontSize { get; set; }
public bool IsItalic { get; set; } //是否倾斜
public bool IsBold { get; set; } //是否加粗
public string Text { get; set; }
public string TextAlign { get; set; }
public string VerticalAlign { get; set; }
public bool Visible { get; set; }
public string BackColor { get; set; }
public MyImage Img { get; set; }
public int ColumnSpan { get; set; }
public int RowSpan { get; set; }
public Font font { get; set; }
/// <summary>
/// true为列隐藏,false为行隐藏
/// </summary>
public bool VisibleState { get; set; }
public MyCell()
{
FontColor = "";
BackColor = "";
FontName = "";
FontSize = 0;
TextAlign = "Center"; //文本方向,Left,Right,Center
VerticalAlign = "Center"; //Top,Center,Bottom
Text = "";
Visible = true;
ColumnSpan = 1;
RowSpan = 1;
}
}
#endregion
#region 表格中的列
public class MyColumn
{
public int Width { get; set; }
}
#endregion
#region 我的文字
public class MyString
{
public int Top { get; set; }
public int Left { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public string FontColor { get; set; }
public string FontName { get; set; }
public float FontSize { get; set; }
public bool IsItalic { get; set; } //是否倾斜
public bool IsBold { get; set; } //是否加粗
public string Text { get; set; }
public string TextAlign { get; set; }
public string VerticalAlign { get; set; }
public MyString()
{
FontName = "宋体";
FontColor = "Black";
FontSize = 12;
TextAlign = "Left"; //文本方向,Left,Right,Center
VerticalAlign = "Top"; //Top,Center,Bottom
}
}
#endregion
#region 我的图片
public class MyImage
{
public int Top { get; set; }
public int Left { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public string FilePath { get; set; }
}
#endregion
}

@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace HuizhongLibrary
{
public class MyKeyDemon
{
[DllImport("User32.dll", EntryPoint = "FindWindow")]
public static extern IntPtr FindWindow(string lpClassName,
string lpWindowName);
[DllImport("user32.dll", EntryPoint = "FindWindowEx")]
public static extern IntPtr FindWindowEx(IntPtr hwndParent,
IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
[DllImport("User32.dll", EntryPoint = "SendMessage")]
public static extern int SendMessage(IntPtr hWnd,
int Msg, IntPtr wParam, string lParam);
public const int WM_GETTEXT = 0x000D;
public const int WM_SETTEXT = 0x000C;
public const int WM_CLICK = 0x00F5;
}
}

@ -0,0 +1,16 @@
using System;
using System.Net;
namespace HuizhongLibrary.Network
{
/// <summary>
/// EventArgs class holding a Byte[].
/// </summary>
public class DataEventArgs : EventArgs
{
public IPEndPoint RemoteEndPoint { get; set; }
public Byte[] Data { get; set; }
public Int32 Offset { get; set; }
public Int32 Length { get; set; }
}
}

@ -0,0 +1,35 @@
using System;
using System.Net.Sockets;
namespace HuizhongLibrary.Network
{
/// <summary>
/// Represents one of the new Socket xxxAsync methods in .NET 3.5.
/// </summary>
/// <param name="args">The SocketAsyncEventArgs for use with the method.</param>
/// <returns>Returns true if the operation completed asynchronously, false otherwise.</returns>
public delegate Boolean SocketAsyncMethod(SocketAsyncEventArgs args);
/// <summary>
/// Holds helper methods for working with the new Socket xxxAsync methods in .NET 3.5.
/// </summary>
public static class ExtensionMethods
{
/// <summary>
/// Extension method to simplyfiy the pattern required by the new Socket xxxAsync methods in .NET 3.5.
/// See http://www.flawlesscode.com/post/2007/12/Extension-Methods-and-SocketAsyncEventArgs.aspx
/// </summary>
/// <param name="socket">The socket this method acts on.</param>
/// <param name="method">The xxxAsync method to be invoked.</param>
/// <param name="callback">The callback for the method. Note: The Completed event must already have been attached to the same.</param>
/// <param name="args">The SocketAsyncEventArgs to be used with this call.</param>
public static void InvokeAsyncMethod(this Socket socket, SocketAsyncMethod method, EventHandler<SocketAsyncEventArgs> callback, SocketAsyncEventArgs args)
{
if (!method(args))
{
callback(socket, args);
}
}
}
}

@ -0,0 +1,290 @@
using HuizhongLibrary.Log;
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;
namespace HuizhongLibrary.Network
{
public class SendSocket
{
public string IpAddress = "127.0.0.1";
public int Port = 20000;
public static int OutTime = 10; //默认超时
Socket socket = null;
AutoResetEvent AutoReset = new AutoResetEvent(false);
string error = "";
System.Threading.Timer time1 = null;
public byte[] Data = null;
public byte[] RevData = null;
bool IsRun = false;
#region 发送
public void Send(byte[] buffer)
{
IsRun = true;
Data = buffer;
RevData = null;
time1 = new System.Threading.Timer(new System.Threading.TimerCallback(Timer_SocketConnect), null, 2000, 0);
Action hand = new Action(this.Connect);
hand.BeginInvoke(null, null);
AutoReset.WaitOne(SendSocket.OutTime * 1000, false);
}
#endregion
#region 发送
public void BeginSend(byte[] buffer)
{
IsRun = true;
Data = buffer;
RevData = null;
time1 = new System.Threading.Timer(new System.Threading.TimerCallback(Timer_SocketConnect), null, 2000, 0);
Action hand = new Action(this.BeginConnect);
hand.BeginInvoke(null, null);
}
#endregion
#region 连接
void Connect()
{
try
{
IPAddress broadcast = IPAddress.Parse(this.IpAddress);
IPEndPoint ep = new IPEndPoint(broadcast,this.Port);
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.LingerState = new LingerOption(true, 0);
socket.SendTimeout = 5000;
socket.ReceiveBufferSize = 4096 * 1024;
//ErrorFollow.TraceWrite("连接金唐服务", "", "Ip:"+ IpAddress+";Port:"+Port);
socket.Connect(ep);
//ErrorFollow.TraceWrite("连接金唐服务", "成功", "Ip:" + IpAddress + ";Port:" + Port);
time1.Dispose();
int i=socket.Send(Data, 0, Data.Length, SocketFlags.None);
if (i == 0) { error = "发送数据失败"; }
while (IsRun)
{
if (socket.Available > 0)
{
RevData = new byte[socket.Available];
socket.Receive(RevData);
break;
}
else
{
//ErrorFollow.TraceWrite("金唐服务", "", "未接收到数据,等待100毫秒后重新接收");
Thread.Sleep(100);
}
}
Stop();
}
catch (Exception ex)
{
error = ex.Message;
}
}
#endregion
#region 连接
void BeginConnect()
{
try
{
IPAddress broadcast = IPAddress.Parse(this.IpAddress);
IPEndPoint ep = new IPEndPoint(broadcast, this.Port);
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.LingerState = new LingerOption(true, 0);
socket.SendTimeout = 5000;
socket.Connect(ep);
time1.Dispose();
socket.Send(Data, 0, Data.Length, SocketFlags.None);
int index = 1;
int CountNum = SendSocket.OutTime * 1000 / 100;
while (IsRun)
{
if (socket.Available > 0)
{
RevData = new byte[socket.Available];
socket.Receive(RevData);
break;
}
else
{
Thread.Sleep(100);
index++;
if (index > CountNum) break;
}
}
Stop();
}
catch (Exception ex)
{
error = ex.Message;
}
}
#endregion
#region 关闭
public void Stop()
{
AutoReset.Set();
IsRun = false;
try
{
socket.Shutdown(SocketShutdown.Both);
}
catch
{ }
try
{
socket.Close();
}
catch
{ }
}
#endregion
#region 检测连接是否成功
void Timer_SocketConnect(object state)
{
try
{
time1.Dispose();
if (socket.Connected == false)
{
error = "连接服务器失败";
Stop();
}
}
catch
{}
}
#endregion
#region 发送数据
public static int KTSendRcv(string ip, int port, string sendbuf, out string recvbuf)
{
byte[] buffer = System.Text.Encoding.GetEncoding("GB2312").GetBytes(sendbuf);
SendSocket model = new SendSocket();
model.IpAddress = ip;
model.Port = port;
model.Send(buffer);
recvbuf = "";
if (string.IsNullOrEmpty(model.error) == false) { recvbuf = model.error; return 1; }
if (model.RevData == null)
{
recvbuf = model.error;
model.Stop();
return 2;
}
recvbuf = System.Text.Encoding.GetEncoding("GB2312").GetString(model.RevData, 0, model.RevData.Length);
return 0;
}
#endregion
#region 异步发送数据
public static void BeginKTSendRcv(string ip, int port, string sendbuf)
{
byte[] buffer = System.Text.Encoding.GetEncoding("GB2312").GetBytes(sendbuf);
SendSocket model = new SendSocket();
model.IpAddress = ip;
model.Port = port;
model.BeginSend(buffer);
}
#endregion
#region 发送数据
public static int KTSendRcv(string ip,int port,byte[] sendbuf, out byte[] recvbuf)
{
SendSocket model = new SendSocket();
model.IpAddress = ip;
model.Port = port;
model.Send(sendbuf);
recvbuf = null;
if (string.IsNullOrEmpty(model.error) == false) return 1;
if (model.RevData == null)
{
model.Stop();
return 2;
}
recvbuf = model.RevData;
return 0;
}
#endregion
#region 异步发送数据
public static void BeginKTSendRcv(string ip, int port, byte[] sendbuf)
{
SendSocket model = new SendSocket();
model.IpAddress = ip;
model.Port = port;
model.BeginSend(sendbuf);
}
#endregion
#region 文件发送
public static void SendFile(string IpAddress,int Port,string FilePath,Action<string,int> ActionProgress)
{
Action<string, int, string, Action<string,int>> act = new Action<string, int, string, Action<string,int>>(BeginSendFile);
act.BeginInvoke(IpAddress, Port, FilePath, ActionProgress, null, null);
}
public static void BeginSendFile(string IpAddress, int Port, string FilePath, Action<string,int> ActionProgress)
{
try
{
IPAddress broadcast = IPAddress.Parse(IpAddress);
IPEndPoint ep = new IPEndPoint(broadcast, Port);
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.LingerState = new LingerOption(true, 0);
socket.SendTimeout = 5000;
socket.ReceiveBufferSize = 50 * 1024;
socket.Connect(ep);
NetworkStream ns = new NetworkStream(socket);
FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
fs.Position = 0;
byte[] fileBuffer = new byte[1024 * 32]; // 每次传4KB
int bytesRead;
int totalBytes = 0;
int index = 0;
do
{
bytesRead = fs.Read(fileBuffer, 0, fileBuffer.Length);
if (bytesRead == 0) break;
ns.Write(fileBuffer, 0, bytesRead);
totalBytes += bytesRead; // 发送了的字节数
double Percent = Convert.ToDouble(totalBytes) / Convert.ToDouble(fs.Length) * 100;
ActionProgress.Invoke(IpAddress,Convert.ToInt32(Percent));
//Thread.Sleep(10);
index++;
//if (index == 10)
//{
// Thread.Sleep(10);
// index = 0;
//}
} while (bytesRead > 0);
ns.Close(5000);
socket.Close(5000);
fs.Close();
fs = null;
ns = null;
socket = null;
}
catch (Exception ex)
{
ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message);
ActionProgress.Invoke(IpAddress,-1);
}
}
#endregion
}
}

@ -0,0 +1,13 @@
using System;
using System.Net.Sockets;
namespace HuizhongLibrary.Network
{
/// <summary>
/// EventArgs class holding a Socket.
/// </summary>
public class SocketEventArgs : EventArgs
{
public Socket Socket { get; set; }
}
}

@ -0,0 +1,580 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HuizhongLibrary.Log;
namespace HuizhongLibrary.Network
{
#region 消息对象
public class SocketMessage
{
private int m_MessageID;
public int MessageID
{
get { return m_MessageID; }
set { m_MessageID = value; }
}
private string m_SequenceID;
public string SequenceID
{
get { return m_SequenceID; }
set { m_SequenceID = value; }
}
private byte[] m_Bytes;
public byte[] Bytes
{
get { return m_Bytes; }
set { m_Bytes = value; }
}
public string Data { get; set; }
private int m_SendLength = 0;
public int SendLength
{
get { return m_SendLength; }
set { m_SendLength = value; }
}
private DateTime m_SendTime;
public DateTime SendTime
{
get { return m_SendTime; }
set { m_SendTime = value; }
}
private string m_IpAddress;
public string IpAddress
{
get { return m_IpAddress; }
set { m_IpAddress = value; }
}
private string m_DeviceNo;
public string DeviceNo
{
get { return m_DeviceNo; }
set { m_DeviceNo = value; }
}
private string m_FunNo;
public string FunNo
{
get { return m_FunNo; }
set { m_FunNo = value; }
}
private int m_SendNumber;
public int SendNumber
{
get { return m_SendNumber; }
set { m_SendNumber = value; }
}
private bool m_IsRevert;
/// <summary>
/// 是否要求回复
/// </summary>
public bool IsRevert
{
get { return m_IsRevert; }
set { m_IsRevert = value; }
}
private bool m_Enabled;
public bool Enabled
{
get { return m_Enabled; }
set { m_Enabled = value; }
}
private bool m_IsLock;
public bool IsLock
{
get { return m_IsLock; }
set { m_IsLock = value; }
}
public SocketMessage()
{
MessageID = 0;
SendNumber = 0;
SendTime = DateTime.Now.AddMinutes(-1);
Enabled = true;
DeviceNo = "";
IpAddress = "";
Data = "";
IsRevert = true;
IsLock = false;
}
public SocketMessage Copy()
{
SocketMessage Model = new SocketMessage();
Model.MessageID = MessageID;
Model.Bytes = Bytes;
Model.Data = Data;
Model.SendTime = SendTime;
Model.FunNo = FunNo;
Model.SequenceID = SequenceID;
Model.DeviceNo = DeviceNo;
Model.IpAddress = IpAddress;
Model.SendNumber = SendNumber;
Model.Enabled = Enabled;
Model.IsRevert = IsRevert;
Model.IsLock = IsLock;
Model.SendLength = SendLength;
return Model;
}
}
#endregion
#region 消息对象列表
public class SocketMessages
{
public List<SocketMessage> ListModel = new List<SocketMessage>();
public bool IsEmployMessages = false;
#region 消息数
public int Count
{
get
{
lock (ListModel)
{
try
{
return ListModel.Count;
}
catch (Exception ex)
{
ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message);
}
}
return 0;
}
}
#endregion
#region 新增消息
public void Add(SocketMessage item)
{
if (item == null) return;
lock (ListModel)
{
try
{
ListModel.Add(item);
}
catch (Exception ex)
{
ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message);
}
}
}
#endregion
#region 使消息无效
public int Employ(string SequenceID)
{
lock (ListModel)
{
try
{
for (int i = 0; i < ListModel.Count; i++)
{
var model = ListModel[i];
if (model == null) continue;
if (model.SequenceID == SequenceID)
{
IsEmployMessages = true;
model.Enabled = false;
return model.MessageID;
}
}
}
catch (Exception ex)
{
ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message);
}
}
return 0;
}
#endregion
#region 移除无效的消息
public void RemoveEmploy()
{
lock (ListModel)
{
try
{
ListModel.RemoveAll(m => m.Enabled == false);
IsEmployMessages = false;
}
catch (Exception ex)
{
ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message);
}
}
}
#endregion
#region 返回要发送的消息
public SocketMessage GetNextSocketMessage(int RefshSecond)
{
lock (ListModel)
{
try
{
SocketMessage model = null;
for (int i = 0; i < ListModel.Count; i++)
{
model = ListModel[i];
if (model.Enabled == false) continue;
if (model.IsLock == true && i > 0)
{
return null;
}
if (model.SendTime.AddSeconds(RefshSecond) <= DateTime.Now)
{
return model;
}
else
{
if (model.IsLock == true && i == 0) return null;
}
}
}
catch (Exception ex)
{
ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message);
}
}
return null;
}
#endregion
#region 根据流水号返回消息
public SocketMessage GetSocketMessage(string SequenceID)
{
lock (ListModel)
{
try
{
SocketMessage model = null;
SocketMessage model2 = null;
for (int i = 0; i < this.ListModel.Count; i++)
{
model2 = this.ListModel[i];
if (model2.SequenceID == SequenceID) { model = model2; break; }
}
return model;
}
catch (Exception ex)
{
ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message);
}
}
return null;
}
#endregion
#region 清除全部消息
public void Clear()
{
lock (ListModel)
{
try
{
ListModel.Clear();
}
catch (Exception ex)
{
ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message);
}
}
}
#endregion
#region 移除并返回一个对象
public SocketMessage CheckOut(string SequenceID)
{
lock (ListModel)
{
try
{
SocketMessage model = null;
for (int i = 0; i < this.ListModel.Count; i++)
{
if (this.ListModel[i].SequenceID == SequenceID)
{
model = this.ListModel[i];
this.ListModel.RemoveAt(i);
break;
}
}
return model;
}
catch (Exception ex)
{
ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message);
}
}
return null;
}
#endregion
#region 返回顶部的消息延迟时间
public int PeekInterval(int RefshSecond)
{
lock (ListModel)
{
try
{
TimeSpan ts = ListModel[0].SendTime.AddSeconds(RefshSecond) - DateTime.Now;
return Convert.ToInt32(ts.TotalMilliseconds);
}
catch (Exception ex)
{
ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message);
}
}
return 0;
}
#endregion
#region 移除并返回一个对象
public SocketMessage CheckOut()
{
lock (ListModel)
{
try
{
if (ListModel.Count == 0) return null;
SocketMessage model = ListModel[0];
ListModel.RemoveAt(0);
return model;
}
catch (Exception ex)
{
ErrorFollow.TraceWrite("SocketMessages.CheckOut", ex.StackTrace, ex.Message);
}
}
return null;
}
#endregion
#region 移除并返回一个对象
public void Remove(string FunNo)
{
lock (ListModel)
{
try
{
this.ListModel.RemoveAll(m => m.FunNo == FunNo);
//for (int i = this.ListModel.Count - 1; i >= 0; i--)
//{
// if (this.ListModel[i].FunNo == FunNo)
// {
// this.ListModel.RemoveAt(i);
// }
//}
}
catch (Exception ex)
{
ErrorFollow.TraceWrite("SocketMessages.Remove", ex.StackTrace, ex.Message);
}
}
}
#endregion
#region 移除设备消息
public void Clear(string DeviceNo)
{
if (string.IsNullOrEmpty(DeviceNo) == true) return;
lock (ListModel)
{
try
{
ListModel.RemoveAll(m => m.DeviceNo == DeviceNo);
}
catch (Exception ex)
{
ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message);
}
}
}
#endregion
}
#endregion
#region 消息缓存池
public class SocketMessagePool
{
Queue<SocketMessage> argsPool;
public bool IsRead = false;
public SocketMessagePool()
{
argsPool = new Queue<SocketMessage>();
IsRead = true;
}
#region 新增对象
public void CheckIn(SocketMessage item)
{
lock (argsPool)
{
try
{
argsPool.Enqueue(item);
}
catch (Exception ex)
{
ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message);
}
}
}
#endregion
#region 返回对象
public SocketMessage CheckOut()
{
lock (argsPool)
{
try
{
if (argsPool.Count == 0) return null;
return argsPool.Dequeue();
}
catch (Exception ex)
{
ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message);
}
return null;
}
}
#endregion
#region 返回缓存数量
public int Available
{
get
{
lock (argsPool)
{
try
{
return argsPool.Count;
}
catch (Exception ex)
{
ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message);
}
return 0;
}
}
}
#endregion
#region 移除
public void Clear()
{
lock (argsPool)
{
try
{
argsPool.Clear();
}
catch (Exception ex)
{
ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message);
}
}
}
#endregion
}
#endregion
#region 设备缓存
public class ServerConnectionPools
{
Dictionary<string, ServerConnection> argsPool=new Dictionary<string, ServerConnection>();
#region 新增对象
public void CheckIn(string DeviceNo,ServerConnection item)
{
lock (argsPool)
{
try
{
if (argsPool.ContainsKey(DeviceNo) == true)
{
argsPool[DeviceNo] = item;
return;
}
argsPool.Add(DeviceNo,item);
}
catch (Exception ex)
{
ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message);
}
}
}
#endregion
#region 返回对象
public ServerConnection CheckOut(string DeviceNo)
{
lock (argsPool)
{
try
{
if (argsPool.Count == 0) return null;
ServerConnection model=null;
bool bk= argsPool.TryGetValue(DeviceNo,out model);
if (bk == true && model != null) return model;
}
catch (Exception ex)
{
ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message);
}
return null;
}
}
#endregion
#region 移除
public void Remove(string DeviceNo)
{
lock (argsPool)
{
try
{
argsPool.Remove(DeviceNo);
}
catch (Exception ex)
{
ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message);
}
}
}
#endregion
#region 移除
public void Clear()
{
lock (argsPool)
{
try
{
argsPool.Clear();
}
catch (Exception ex)
{
ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message);
}
}
}
#endregion
#region 清除已断开连接
public void RemoveEnabled()
{
lock (argsPool)
{
try
{
var argsPool2 = new Dictionary<string, ServerConnection>();
foreach (var item in argsPool.Values)
{
if (item.Enabled == false) continue;
if (argsPool2.ContainsKey(item.DeviceNo + ":" + item.Port) == true) continue;
argsPool2.Add(item.DeviceNo + ":" + item.Port, item);
}
argsPool = argsPool2;
}
catch (Exception ex)
{
ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message);
}
}
}
#endregion
}
#endregion
}

@ -0,0 +1,58 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
namespace HuizhongLibrary.Network
{
#region 缓存管理BufferPool
public class BufferPool
{
int m_numBytes; // 未知
byte[] m_buffer; //
Stack<int> m_freeIndexPool; //
int m_currentIndex;       //未知   
int m_bufferSize; //缓存大小
public BufferPool(int totalBytes, int bufferSize)
{
m_numBytes = totalBytes;
m_currentIndex = 0;
m_bufferSize = bufferSize;
m_freeIndexPool = new Stack<int>();
}
public void InitBuffer()
{
m_buffer = new byte[m_numBytes];
}
public bool SetBuffer(SocketAsyncEventArgs args)
{
if (m_freeIndexPool.Count > 0)
{
args.SetBuffer(m_buffer, m_freeIndexPool.Pop(), m_bufferSize);
}
else
{
if ((m_numBytes - m_bufferSize) < m_currentIndex)
{
return false;
}
args.SetBuffer(m_buffer, m_currentIndex, m_bufferSize);
m_currentIndex += m_bufferSize;
}
return true;
}
public void FreeBuffer(SocketAsyncEventArgs args)
{
m_freeIndexPool.Push(args.Offset);
args.SetBuffer(null, 0, 0);
}
}
#endregion
}

@ -0,0 +1,493 @@
using System;
using System.Net.Sockets;
using System.Net;
using System.Collections.Generic;
using System.Collections;
using System.Threading;
using HuizhongLibrary.Log;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
namespace HuizhongLibrary.Network
{
/// <summary>
/// Represents a callback used to inform a listener that a ServerConnection has received data.
/// </summary>
/// <param name="sender">The sender of the callback.</param>
/// <param name="e">The DataEventArgs object containging the received data.</param>
public delegate void DataReceivedCallback(ServerConnection sender, DataEventArgs e);
/// <summary>
/// Represents a callback used to inform a listener that a ServerConnection has disconnected.
/// </summary>
/// <param name="sender">The sender of the callback.</param>
/// <param name="e">The SocketAsyncEventArgs object used by the ServerConnection.</param>
public delegate void DisconnectedCallback(ServerConnection sender, SocketAsyncEventArgs e);
/// <summary>
/// A connection to our server.
/// </summary>
public class ServerConnection
{
public string IpAddress { get; set; }
public int Port { get; set; }
public string DeviceNo { get; set; }
public DateTime PrevTime { get; set; }
public List<byte> SocketBuffer { get; set; }
public SocketMessages ListMessage { get; set; }
public bool Enabled { get; set; }
public bool IsLogin { get; set; }
public string ConnectIp { get; set; }
public int ConnectPort { get; set; }
public int FileLength { get; set; }
public int ReceiveLen { get; set; }
public Byte[] Data { get; set; }
public string BuffData { get; set; }
public int RefshSecond { get; set; }
public bool IsSyncSend { get; set; }
public int CheckConnectNumber { get; set; } //连接状态验证次数
public int WaitMsgNumber = 0;
public bool IsWebSocket = false; //WebSocket握手协议是否完成
public FileStream fs = null;
private int MaxSendNumber = 0;
private int MaxWaitMsgNumber = 0;
private DateTime CacheDataTime = DateTime.Now;
public SocketAsyncEventArgs eventArgs;
public Socket socket;
public event Action<ServerConnection> SendCompleted;
public event Action<ServerConnection, DataEventArgs> DataReceived;
public event Action<ServerConnection, SocketAsyncEventArgs> CloseSocketed;
#region 初始化
public ServerConnection()
{
CheckConnectNumber = 3;
FileLength = 0;
IsLogin = false;
PrevTime = DateTime.Now;
WaitMsgNumber = 0;
SocketBuffer = new List<byte>();
ListMessage = new SocketMessages();
//Data = new byte[2048];
}
public ServerConnection(Socket socket, SocketAsyncEventArgs args)
{
//Data = new byte[2048];
FileLength = 0;
IsLogin = false;
PrevTime = DateTime.Now;
WaitMsgNumber = 0;
SocketBuffer = new List<byte>();
ListMessage = new SocketMessages();
if (socket.AddressFamily == AddressFamily.InterNetwork || socket.AddressFamily == AddressFamily.Unspecified)
{
string[] RemoteEndPoint = socket.RemoteEndPoint.ToString().Split(':');
this.IpAddress = RemoteEndPoint[0];
this.Port = Convert.ToInt32(RemoteEndPoint[1]);
ErrorFollow.TraceWrite("请求连接", "", IpAddress);
//this.DeviceNo = this.IpAddress.Split(Convert.ToChar("."))[3];
}
else
{
this.IpAddress = "";
}
this.Enabled = true;
this.socket = socket;
eventArgs = args;
eventArgs.Completed += ReceivedCompleted;
ListenForData(eventArgs);
}
#endregion
#region 连接
public void Start(Socket socket, SocketAsyncEventArgs args)
{
if (socket.AddressFamily == AddressFamily.InterNetwork || socket.AddressFamily == AddressFamily.Unspecified)
{
string[] RemoteEndPoint = socket.RemoteEndPoint.ToString().Split(':');
this.IpAddress = RemoteEndPoint[0];
this.Port = Convert.ToInt32(RemoteEndPoint[1]);
}
else
{
this.IpAddress = "";
}
this.Enabled = true;
if (this.socket != null) this.socket = null;
if (this.eventArgs != null)
{
eventArgs.Dispose();
eventArgs = null;
}
this.socket = socket;
eventArgs = args;
eventArgs.Completed += ReceivedCompleted;
ListenForData(eventArgs);
}
#endregion
#region 返回要发送的消息
public SocketMessage GetNextSocketMessage(int RefshSecond)
{
var item=ListMessage.GetNextSocketMessage(RefshSecond);
if (item == null) return null;
if (item.SendNumber > 0)
{
ErrorFollow.TraceWrite("重发", "", item.FunNo);
DecrementWaitMsgNumber();
}
return item;
}
#endregion
#region 移除已发送消息
public void RemoveSocketMessage()
{
ListMessage.RemoveEmploy();
}
#endregion
#region 增加等待回复的消息数
public void IncrementWaitMsgNumber()
{
Interlocked.Increment(ref WaitMsgNumber);
}
#endregion
#region 减少等待回复的消息数
public void DecrementWaitMsgNumber()
{
Interlocked.Decrement(ref WaitMsgNumber);
//Interlocked.Exchange<string>(ref 变量,11);
}
#endregion、
#region 消除已回复消息
public SocketMessage EndWaitMsg(string SequenceID)
{
try
{
DecrementWaitMsgNumber();
SocketMessage msg = ListMessage.CheckOut(SequenceID);
return msg;
}
catch (Exception ex)
{
ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message);
}
return null;
}
#endregion
#region 消除已回复消息
public SocketMessage EndFirstWaitMsg()
{
try
{
DecrementWaitMsgNumber();
SocketMessage msg = ListMessage.CheckOut();
return msg;
}
catch (Exception ex)
{
ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message);
}
return null;
}
#endregion
#region 返回消息
public SocketMessage GetSocketMessage(string SequenceID)
{
return ListMessage.GetSocketMessage(SequenceID);
}
#endregion
#region 合并缓存数据
public void AddData(byte[] RevData, int Offset, int Len)
{
try
{
if (CacheDataTime.AddSeconds(15) < DateTime.Now)
{
SocketBuffer.Clear();
}
this.ReceiveLen = Len + SocketBuffer.Count;
if (Data.Length < this.ReceiveLen) Data = new byte[ReceiveLen];
for (int i = 0; i < SocketBuffer.Count; i++)
{
Data[i] = SocketBuffer[i];
}
Buffer.BlockCopy(RevData, Offset, Data, SocketBuffer.Count, Len);
SocketBuffer.Clear();
}
catch (Exception ex)
{
ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message);
}
}
#endregion
#region 新增缓存
public void AddBuff(byte[] SrcArray, int offset)
{
try
{
for (int i = offset; i < ReceiveLen; i++)
{
SocketBuffer.Add(SrcArray[i]);
}
CacheDataTime = DateTime.Now;
}
catch (Exception ex)
{
ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message);
}
}
#endregion
#region 清理内存
public void Dispose()
{
if (SocketBuffer != null) SocketBuffer.Clear();
SocketBuffer = null;
if (ListMessage!=null) ListMessage.Clear();
ListMessage = null;
}
#endregion
#region 打包服务器数据
/// <summary>
/// 打包服务器数据
/// </summary>
/// <param name="message">数据</param>
/// <returns>数据包</returns>
public static byte[] PackData(string message)
{
byte[] contentBytes = null;
byte[] temp = Encoding.UTF8.GetBytes(message);
if (temp.Length < 126)
{
contentBytes = new byte[temp.Length + 2];
contentBytes[0] = 0x81;
contentBytes[1] = (byte)temp.Length;
Array.Copy(temp, 0, contentBytes, 2, temp.Length);
}
else if (temp.Length < 0xFFFF)
{
contentBytes = new byte[temp.Length + 4];
contentBytes[0] = 0x81;
contentBytes[1] = 126;
contentBytes[2] = (byte)(temp.Length >> 8 & 0xFF);
contentBytes[3] = (byte)(temp.Length & 0xFF);
Array.Copy(temp, 0, contentBytes, 4, temp.Length);
}
else
{
// 暂不处理超长内容
}
return contentBytes;
}
#endregion
#region Public Methods
/// <summary>
/// Disconnects the client.
/// </summary>
public void Disconnect()
{
lock (this)
{
CloseConnection(eventArgs);
}
}
/// <summary>
/// Sends data to the client.
/// </summary>
/// <param name="data">The data to send.</param>
/// <param name="offset">The offset into the data.</param>
/// <param name="count">The ammount of data to send.</param>
public bool SendData(Byte[] data, Int32 offset, Int32 count)
{
try
{
lock (this)
{
if (socket.Connected == false) return false;
//bool bk=socket.Poll(-1, SelectMode.SelectWrite);
this.PrevTime = DateTime.Now;
int i = socket.Send(data, offset, count, SocketFlags.None);
if (i <= 0) return false;
}
}
catch (Exception ex)
{
return false;
}
return true;
}
#region WebSocket专用
public bool SendData(string data)
{
lock (this)
{
if (socket.Connected == false) return false;
//bool bk=socket.Poll(-1, SelectMode.SelectWrite);
this.PrevTime = DateTime.Now;
byte[] bytes = PackData(data);
int i = socket.Send(bytes, 0, bytes.Length, SocketFlags.None);
if (i <= 0) return false;
}
return true;
}
#endregion
#endregion
#region 获取Socket
public Socket GetSocket()
{
lock (this)
{
return socket;
}
}
#endregion
#region Private Methods
/// <summary>
/// Starts and asynchronous recieve.
/// </summary>
/// <param name="args">The SocketAsyncEventArgs to use.</param>
private void ListenForData(SocketAsyncEventArgs args)
{
lock (this)
{
if (socket == null) return;
if (socket.Connected)
{
socket.InvokeAsyncMethod(socket.ReceiveAsync,
ReceivedCompleted, args);
}
}
}
/// <summary>
/// Called when an asynchronous receive has completed.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="args">The SocketAsyncEventArgs for the operation.</param>
private void ReceivedCompleted(Object sender, SocketAsyncEventArgs args)
{
try
{
if (args.BytesTransferred == 0)
{
if (string.IsNullOrEmpty(this.DeviceNo)==false)Disconnect();
return;
}
if (args.SocketError != SocketError.Success)
{
if (string.IsNullOrEmpty(this.DeviceNo) == false) Disconnect();
return;
}
this.Data = new byte[args.BytesTransferred];
this.ReceiveLen = this.Data.Length;
Buffer.BlockCopy(args.Buffer, args.Offset, this.Data, args.Offset, args.BytesTransferred);
if (this.DataReceived!=null)this.DataReceived(this, new DataEventArgs() { Data = this.Data, Length = this.ReceiveLen });
ListenForData(args);
//if (state.socket.Available == 0)
//{
// ListenForData(args);
//}
}
catch (Exception ex)
{
ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message);
Disconnect();
}
}
#region 输出数据日志
string WaitData(byte[] bytes, int index, int Length)
{
try
{
return Encoding.UTF8.GetString(bytes, index, Length);
}
catch
{
string a = "";
foreach (var item in bytes)
{
a += item.ToString("X");
}
return a;
}
}
#endregion
/// <summary>
/// Closes the connection.
/// </summary>
/// <param name="args">The SocketAsyncEventArgs for the connection.</param>
private void CloseConnection(SocketAsyncEventArgs args)
{
if (this.Enabled == false)return;
this.Enabled = false;
this.WaitMsgNumber = 0;
if (socket == null) return;
try
{
socket.Shutdown(SocketShutdown.Both);
}
catch
{ }
try
{
socket.Close();
}
catch
{ }
try
{
Dispose();
args.Completed -= ReceivedCompleted; //MUST Remember This!
socket = null;
this.Data = null;
}
catch (Exception ex)
{
ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message);
}
if (this.CloseSocketed != null) this.CloseSocketed(this, args);
}
#endregion
#region Events
/// <summary>
/// Fires the DataReceivedCallback.
/// </summary>
/// <param name="data">The data which was received.</param>
/// <param name="remoteEndPoint">The address the data came from.</param>
/// <param name="callback">The callback.</param>
private void OnDataReceived(DataReceivedCallback callback)
{
callback(this, new DataEventArgs() { Data = this.Data, Length = this.ReceiveLen });
}
/// <summary>
/// Fires the DisconnectedCallback.
/// </summary>
/// <param name="args">The SocketAsyncEventArgs for this connection.</param>
/// <param name="callback">The callback.</param>
private void OnDisconnected(SocketAsyncEventArgs args, DisconnectedCallback callback)
{
callback(this, args);
}
#endregion
}
}

@ -0,0 +1,100 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HuizhongLibrary.Log;
namespace HuizhongLibrary.Network
{
public class ServerConnectionPool
{
Queue<ServerConnection> argsPool;
public ServerConnectionPool()
{
argsPool = new Queue<ServerConnection>();
}
#region 新增
public void CheckIn(ServerConnection item)
{
lock (argsPool)
{
try
{
argsPool.Enqueue(item);
}
catch (Exception ex)
{
ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message);
}
}
}
#endregion
#region 移除并返回开始对象
public ServerConnection CheckOut()
{
lock (argsPool)
{
try
{
if (argsPool.Count == 0) return null;
return argsPool.Dequeue();
}
catch (Exception ex)
{
ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message);
}
}
return null;
}
#endregion
#region 返回开始对象,但不移除
public ServerConnection Peek()
{
lock (argsPool)
{
try
{
if (argsPool.Count == 0) return null;
return argsPool.Peek();
}
catch (Exception ex)
{
ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message);
}
}
return null;
}
#endregion
#region 移除
public void Clear()
{
lock (argsPool)
{
try
{
argsPool.Clear();
}
catch (Exception ex)
{
ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message);
}
}
}
#endregion
#region 返回数量
public int Available
{
get
{
lock (argsPool)
{
return argsPool.Count;
}
}
}
#endregion
}
}

@ -0,0 +1,121 @@
using HuizhongLibrary.Log;
using System;
using System.Collections.Generic;
using System.Net.Sockets;
namespace HuizhongLibrary.Network
{
/// <summary>
/// Pools SocketAsyncEventArgs objects to avoid repeated allocations.
/// </summary>
public class SocketArgsPool : IDisposable
{
Queue<SocketAsyncEventArgs> argsPool;
public SocketArgsPool(Int32 capacity)
{
argsPool = new Queue<SocketAsyncEventArgs>(capacity);
}
public SocketArgsPool()
{
argsPool = new Queue<SocketAsyncEventArgs>();
}
#region 新增
public void CheckIn(SocketAsyncEventArgs item)
{
lock (argsPool)
{
try
{
argsPool.Enqueue(item);
}
catch (Exception ex)
{
ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message);
}
}
}
#endregion
#region 移除并返回开始对象
public SocketAsyncEventArgs CheckOut()
{
lock (argsPool)
{
try
{
if (argsPool.Count == 0) return null;
return argsPool.Dequeue();
}
catch (Exception ex)
{
ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message);
}
}
return null;
}
#endregion
#region 返回数量
public int Available
{
get
{
lock (argsPool)
{
return argsPool.Count;
}
}
}
#endregion
#region 移除
public void Clear()
{
lock (argsPool)
{
try
{
argsPool.Clear();
}
catch (Exception ex)
{
ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message);
}
}
}
#endregion
#region IDisposable Members
private Boolean disposed = false;
~SocketArgsPool()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
foreach (SocketAsyncEventArgs args in argsPool)
{
args.Dispose();
}
}
disposed = true;
}
}
#endregion
}
}

@ -0,0 +1,227 @@
using System;
using System.Net;
using System.Net.Sockets;
using HuizhongLibrary.Log;
namespace HuizhongLibrary.Network
{
/// <summary>
/// Listens for socket connection on a given address and port.
/// </summary>
public class TcpSocketListener : IDisposable
{
#region Fields
private Int32 connectionBacklog;
private IPEndPoint endPoint;
private AddressFamily family;
private Socket listenerSocket;
private SocketAsyncEventArgs args;
#endregion
#region Properties
/// <summary>
/// Length of the connection backlog.
/// </summary>
public Int32 ConnectionBacklog
{
get { return connectionBacklog; }
set
{
lock (this)
{
if (IsRunning)
throw new InvalidOperationException("Property cannot be changed while server running.");
else
connectionBacklog = value;
}
}
}
/// <summary>
/// The IPEndPoint to bind the listening socket to.
/// </summary>
public IPEndPoint EndPoint
{
get { return endPoint; }
set
{
lock (this)
{
if (IsRunning)
throw new InvalidOperationException("Property cannot be changed while server running.");
else
endPoint = value;
}
}
}
/// <summary>
/// Is the class currently listening.
/// </summary>
public Boolean IsRunning
{
get { return listenerSocket != null; }
}
#endregion
#region Constructors
/// <summary>
/// Listens for socket connection on a given address and port.
/// </summary>
/// <param name="address">The address to listen on.</param>
/// <param name="port">The port to listen on.</param>
/// <param name="connectionBacklog">The connection backlog.</param>
public TcpSocketListener(AddressFamily family, String address, Int32 port, Int32 connectionBacklog)
: this(family,IPAddress.Parse(address), port, connectionBacklog)
{ }
/// <summary>
/// Listens for socket connection on a given address and port.
/// </summary>
/// <param name="address">The address to listen on.</param>
/// <param name="port">The port to listen on.</param>
/// <param name="connectionBacklog">The connection backlog.</param>
public TcpSocketListener(AddressFamily family, IPAddress address, Int32 port, Int32 connectionBacklog)
: this(family,new IPEndPoint(address, port), connectionBacklog)
{ }
/// <summary>
/// Listens for socket connection on a given address and port.
/// </summary>
/// <param name="endPoint">The endpoint to listen on.</param>
/// <param name="connectionBacklog">The connection backlog.</param>
public TcpSocketListener(AddressFamily family, IPEndPoint endPoint, Int32 connectionBacklog)
{
this.connectionBacklog = connectionBacklog;
this.endPoint = endPoint;
this.family = family;
args = new SocketAsyncEventArgs();
args.Completed += SocketAccepted;
}
#endregion
#region Public Methods
/// <summary>
/// Start listening for socket connections.
/// </summary>
public void Start()
{
lock (this)
{
if (!IsRunning)
{
listenerSocket = new Socket(family , SocketType.Stream, ProtocolType.Tcp);
listenerSocket.Bind(endPoint);
listenerSocket.Listen(connectionBacklog);
ListenForConnection(args);
}
else
throw new InvalidOperationException("The Server is already running.");
}
}
/// <summary>
/// Stop listening for socket connections.
/// </summary>
public void Stop()
{
lock (this)
{
if (listenerSocket == null)
return;
listenerSocket.Close();
listenerSocket = null;
}
}
#endregion
#region Private Methods
/// <summary>
/// Asynchronously listens for new connections.
/// </summary>
/// <param name="args"></param>
private void ListenForConnection(SocketAsyncEventArgs args)
{
try
{
args.AcceptSocket = null;
if (listenerSocket == null) return;
listenerSocket.InvokeAsyncMethod(new SocketAsyncMethod(listenerSocket.AcceptAsync)
, SocketAccepted, args);
}
catch (Exception ex)
{
ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message);
}
}
/// <summary>
/// Invoked when an asynchrounous accept completes.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The SocketAsyncEventArgs for the operation.</param>
private void SocketAccepted(object sender, SocketAsyncEventArgs e)
{
//ErrorFollow.TraceWrite("客户端", "", SocketError.OperationAborted.ToString());
//SocketError error = e.SocketError;
//if (e.SocketError == SocketError.OperationAborted)
// return; //Server was stopped
if (e.SocketError == SocketError.Success)
{
Socket handler = e.AcceptSocket;
OnSocketConnected(handler);
}
lock (this)
{
ListenForConnection(e);
}
}
#endregion
#region Events
/// <summary>
/// Fired when a new connection is received.
/// </summary>
public event EventHandler<SocketEventArgs> SocketConnected;
/// <summary>
/// Fires the SocketConnected event.
/// </summary>
/// <param name="client">The new client socket.</param>
private void OnSocketConnected(Socket client)
{
if (SocketConnected != null)
SocketConnected(this, new SocketEventArgs() { Socket = client });
}
#endregion
#region IDisposable Members
private Boolean disposed = false;
~TcpSocketListener()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
Stop();
if (args != null)
args.Dispose();
}
disposed = true;
}
}
#endregion
}
}

File diff suppressed because it is too large Load Diff

@ -0,0 +1,545 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace HuizhongLibrary.Network
{
#region 服务器
public class UdpService
{
public int Port = 0;
public int RefshSecond = 30; //如果30秒没有收到回复,那么重发
public int MaxSendNumber = 3; //超出最大发送次数,那么认为已经断开
public int MaxWaitMsgNumber = 16; //最大消息等待回包数量(滑动窗口)
public int OutTime = 60 * 5; //断开多少秒后重连
public List<byte> SocketBuffer = new List<byte>(); //网络数据缓存
private AutoResetEvent AutoReset = new AutoResetEvent(false);
public event Action<UserSocket, byte[]> ReceiveDataEvent; //读取到数据时发生
public event Action<string> CloseEvent; //关闭时发生
public event Action<UserSocket> ConnectEvent; //连接客户端时发生
public List<SocketMessage> ListMessage = new List<SocketMessage>();
public List<UserSocket> ListUserSocket = new List<UserSocket>();
bool IsRun = false;
UdpClient udp = null;
IPEndPoint groupEP = null;
public UdpService()
{
}
#region 启动
public void Start(int Port)
{
this.Port = Port;
groupEP = new IPEndPoint(IPAddress.Any, Port);
udp = new UdpClient(Port);
udp.BeginReceive(ReceiveThread, null);
Thread t = new Thread(this.SendThread);
t.Start();
}
#endregion
#region 停止
public void Stop()
{
IsRun = false;
AutoReset.Set();
udp.Close();
lock (ListUserSocket)
{
ListUserSocket.Clear();
}
}
#endregion
#region 关闭连接
public void CloseSocket(string DeviceNo)
{
for (int i = ListUserSocket.Count - 1; i >= 0; i--)
{
if (ListUserSocket[i].DeviceNo != DeviceNo) continue;
ListUserSocket[i].IsLogin = false;
}
if (this.CloseEvent != null) this.CloseEvent(DeviceNo);
}
#endregion
#region 接收线程
void ReceiveThread(IAsyncResult ar)
{
byte[] data = udp.EndReceive(ar, ref groupEP);
string ip=groupEP.Address.ToString();
UserSocket model = GetUserSocket(ip);
if (model == null)
{
model = new UserSocket("", ip, groupEP.Port);
ListUserSocket.Add(model);
}
model.Port = groupEP.Port;
if (this.ReceiveDataEvent != null) this.ReceiveDataEvent(model, data);
udp.BeginReceive(ReceiveThread, null);
}
#endregion
#region 发送线程
void SendThread()
{
IsRun = true;
while (IsRun)
{
for (int i = ListUserSocket.Count - 1; i >= 0; i--)
{
UserSocket model = ListUserSocket[i];
if (model.IsLogin == false)
{
//如果状态是断开状态,并且超出连接时间,那么重连客户端
if (model.PrevTime.AddSeconds(OutTime) < DateTime.Now)
{
if (this.ConnectEvent != null) this.ConnectEvent(model);
}
continue;
}
else
{
while (model.WaitMsgNumber < this.MaxWaitMsgNumber)
{
SocketMessage Msg = model.GetNextSocketMessage(this.RefshSecond);
if (Msg == null) break;
//如果超出N次没回应,那么就算是断开连接
if (Msg.SendNumber > this.MaxSendNumber)
{
model.PrevTime = DateTime.Now;
model.IsLogin = false;
if (this.CloseEvent != null) this.CloseEvent(model.DeviceNo);
break;
}
try
{
Msg.SendNumber++;
Msg.SendTime = DateTime.Now;
int SendLength=udp.Send(Msg.Bytes, Msg.Bytes.Length, model.EndPoint);
if (SendLength != Msg.Bytes.Length)
{
//如果发送的数据长度不对,那么就算是断开连接
model.PrevTime = DateTime.Now;
model.IsLogin = false;
if (this.CloseEvent != null) this.CloseEvent(model.DeviceNo);
break;
}
}
catch
{
//如果发送出错,那么就算是断开连接
model.PrevTime = DateTime.Now;
model.IsLogin = false;
if (this.CloseEvent != null) this.CloseEvent(model.DeviceNo);
break;
}
}
if (ListMessage.Count == 0) continue;
bool IsRemoveMessage = false;
for (int ii = 0; ii < ListMessage.Count; ii++)
{
SocketMessage Model = ListMessage[ii];
if (Model.Enabled == false) { IsRemoveMessage = true; continue; }
//清理超过10分钟还没有发送的数据
if (Model.SendTime.AddMinutes(20) < DateTime.Now)
{
Model.Enabled = false;
IsRemoveMessage = true;
continue;
}
if (Model.DeviceNo != model.DeviceNo) continue;
model.ListMessage.Add(Model.Copy());
Model.Enabled = false;
IsRemoveMessage = true;
}
if (IsRemoveMessage == true) RemoveSocketMessage();
}
AutoReset.WaitOne(100);
}
AutoReset.WaitOne(1000);
}
}
#endregion
#region 移除已发送消息
public void RemoveSocketMessage()
{
lock (((ICollection)this.ListMessage).SyncRoot)
{
for (int i = ListMessage.Count - 1; i >= 0; i--)
{
if (ListMessage[i].Enabled == false) ListMessage.RemoveAt(i);
}
}
}
#endregion
#region 读取UserSocket
public UserSocket GetUserSocket(string ip)
{
for (int i =ListUserSocket.Count - 1; i >= 0; i--)
{
if (ListUserSocket[i].IpAddress == ip) return ListUserSocket[i];
}
return null;
}
#endregion
#region 发送数据
public void Send(byte[] bytes,IPEndPoint endPoint)
{
udp.Send(bytes, bytes.Length, endPoint);
}
#endregion
}
#endregion
#region 连接对象
public class UserSocket
{
public string DeviceNo = "";
public string IpAddress = "";
public int Port = 0;
public Byte[] Data = null;
public DateTime PrevTime = DateTime.Now;
public List<byte> SocketBuffer = new List<byte>();
public List<SocketMessage> ListMessage = new List<SocketMessage>();
public int WaitMsgNumber = 0;
public bool IsLogin = false;
private IPEndPoint m_EndPoint;
public IPEndPoint EndPoint
{
get { return m_EndPoint; }
}
private DateTime CacheDataTime = DateTime.Now;
public UserSocket(string DeviceNo, string IpAddress,int Port)
{
PrevTime = DateTime.Now;
WaitMsgNumber = 0;
IsLogin = false;
this.DeviceNo = DeviceNo;
this.IpAddress = IpAddress;
this.Port = Port;
m_EndPoint = new IPEndPoint(IPAddress.Parse(IpAddress), Port);
}
#region 返回要发送的消息
public SocketMessage GetNextSocketMessage(int RefshSecond)
{
SocketMessage model = null;
for (int i = 0; i < this.ListMessage.Count; i++)
{
model = this.ListMessage[i];
if (model.Enabled == false) continue;
if (model.IsLock == true && i > 0) return null;
if (model.SendTime.AddSeconds(RefshSecond) <= DateTime.Now)
{
if (model.SendNumber > 0) DecrementWaitMsgNumber();
return model;
}
else
{
if (model.IsLock == true && i == 0) return null;
}
}
return null;
}
#endregion
#region 移除已发送消息
public void RemoveSocketMessage()
{
lock (((ICollection)this.ListMessage).SyncRoot)
{
for (int i = ListMessage.Count - 1; i >= 0; i--)
{
if (ListMessage[i].Enabled == false) ListMessage.RemoveAt(i);
}
}
}
#endregion
#region 增加等待回复的消息数
public void IncrementWaitMsgNumber()
{
Interlocked.Increment(ref WaitMsgNumber);
}
#endregion
#region 减少等待回复的消息数
public void DecrementWaitMsgNumber()
{
Interlocked.Decrement(ref WaitMsgNumber);
}
#endregion、
#region 消除已回复消息
public int EndWaitMsg(string FunNo)
{
SocketMessage model = null;
System.Threading.Monitor.Enter(this);
for (int i = 0; i < this.ListMessage.Count; i++)
{
var model2 = this.ListMessage[i];
if (model2.FunNo == FunNo)
{
model = model2;
this.ListMessage.RemoveAt(i);
break;
}
}
DecrementWaitMsgNumber();
System.Threading.Monitor.Exit(this);
if (model == null) return 0;
return model.MessageID;
}
#endregion
#region 合并缓存数据
public void AddData(byte[] RevData, int Len)
{
if (CacheDataTime.AddSeconds(10) < DateTime.Now)
{
SocketBuffer.Clear();
}
Data = new byte[Len + SocketBuffer.Count];
for (int i = 0; i < SocketBuffer.Count; i++)
{
Data[i] = SocketBuffer[i];
}
Buffer.BlockCopy(RevData, 0, Data, SocketBuffer.Count, Len);
SocketBuffer.Clear();
}
#endregion
#region 新增缓存
public void AddBuff(byte[] SrcArray, int offset)
{
for (int i = offset; i < SrcArray.Length; i++)
{
SocketBuffer.Add(SrcArray[i]);
}
CacheDataTime = DateTime.Now;
}
#endregion
#region 返回消息
public SocketMessage GetSocketMessage(string FunNo)
{
SocketMessage model = null;
SocketMessage model2 = null;
for (int i = 0; i < this.ListMessage.Count; i++)
{
model2 = this.ListMessage[i];
if (model2.FunNo == FunNo) { model = model2; break; }
}
return model;
}
#endregion
}
#endregion
#region 客户端
public class UdpClientSocket
{
public int Port = 0;
public int RefshSecond = 30; //如果30秒没有收到回复,那么重发
public int MaxSendNumber = 3; //超出最大发送次数,那么认为已经断开
public string ServerIpAddress = ""; //服务器IP地址
public int ServerPort = 0; //服务器端口
public bool IsLogin = false; //是否已经登陆,必须登陆后才能发送数据
public int OutTime = 60*5; //如果多少时间内没有数据来住,那么发送心跳保持
public List<byte> SocketBuffer = new List<byte>(); //网络数据缓存
private AutoResetEvent AutoReset = new AutoResetEvent(false);
public event Action<byte[]> ReceiveDataEvent; //读取到数据时发生
public event ThreadStart LoginEvent; //要求登陆时发生
public List<SocketMessage> ListMessage = new List<SocketMessage>();
DateTime PrevTime = DateTime.Now.AddMinutes(-6);
DateTime CacheDataTime = DateTime.Now;
bool IsRun = false;
UdpClient udp = null;
IPEndPoint SerEP = null;
IPEndPoint groupEP = null;
public UdpClientSocket()
{
}
#region 启动
public void Start(int Port,string ServerIpAddress,int ServerPort)
{
this.Port = Port;
this.ServerIpAddress = ServerIpAddress;
this.ServerPort = ServerPort;
udp = new UdpClient(Port);
SerEP = new IPEndPoint(IPAddress.Parse(ServerIpAddress), ServerPort);
groupEP = new IPEndPoint(IPAddress.Any, Port);
Thread t = new Thread(this.OnStart);
t.Start();
}
#endregion
#region 停止
public void Stop()
{
IsRun = false;
AutoReset.Set();
udp.Close();
}
#endregion
#region 接收线程
void ReceiveThread(IAsyncResult ar)
{
byte[] data = udp.EndReceive(ar, ref groupEP);
if (this.ReceiveDataEvent != null) this.ReceiveDataEvent(data);
udp.BeginReceive(ReceiveThread, null);
}
#endregion
#region 接收和发送
private void OnStart()
{
IsRun = true;
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, Port);
while (IsRun)
{
try
{
if (this.IsLogin == false && PrevTime.AddSeconds(this.OutTime) < DateTime.Now)
{
//如果处于断线状态,并且连接不成功后XX秒,再进行第二次连接
if (this.LoginEvent != null)
{
this.LoginEvent();
PrevTime = DateTime.Now;
continue;
}
}
SocketMessage Msg = GetNextSocketMessage(this.RefshSecond);
if (Msg == null) break;
if (this.MaxSendNumber > 0 && Msg.SendNumber > this.MaxSendNumber)
{
//断开连接
IsLogin = false;
continue;
}
try
{
Msg.SendNumber++;
Msg.SendTime = DateTime.Now;
int SendLen = udp.Send(Msg.Bytes, Msg.Bytes.Length, SerEP);
if (SendLen != Msg.Bytes.Length)
{
//发送的长度不对,认为已经断开同,或者重发
IsLogin = false;
continue;
}
PrevTime = DateTime.Now;
}
catch
{
//远程已经关闭连接
IsLogin = false;
}
}
catch
{
IsLogin = false;
}
AutoReset.WaitOne(100, false);
}
}
#endregion
#region 发送
public void Send(byte[] bytes)
{
try
{
int SendLen = udp.Send(bytes, bytes.Length, SerEP);
if (SendLen != bytes.Length)
{
//发送的长度不对,认为已经断开同,或者重发
IsLogin = false;
return;
}
PrevTime = DateTime.Now;
}
catch
{
//远程已经关闭连接
IsLogin = false;
}
}
#endregion
#region 返回要发送的消息
public SocketMessage GetNextSocketMessage(int RefshSecond)
{
SocketMessage model = null;
for (int i = 0; i < this.ListMessage.Count; i++)
{
model = this.ListMessage[i];
if (model.Enabled == false) continue;
if (model.IsLock == true && i > 0) return null;
if (model.SendTime.AddSeconds(RefshSecond) <= DateTime.Now)
{
return model;
}
else
{
if (model.IsLock == true && i == 0) return null;
}
}
return null;
}
#endregion
#region 消除已回复消息
public int EndWaitMsg(string FunNo)
{
SocketMessage model = null;
System.Threading.Monitor.Enter(this);
for (int i = 0; i < this.ListMessage.Count; i++)
{
model = this.ListMessage[i];
if (model.FunNo == FunNo) { this.ListMessage.RemoveAt(i); break; }
}
System.Threading.Monitor.Exit(this);
if (model == null) return 0;
return model.MessageID;
}
#endregion
#region 合并缓存数据
public byte[] MergeData(byte[] RevData)
{
if (CacheDataTime.AddSeconds(10) < DateTime.Now)
{
SocketBuffer.Clear();
}
byte[] Data = new byte[RevData.Length + SocketBuffer.Count];
for (int i = 0; i < SocketBuffer.Count; i++)
{
Data[i] = SocketBuffer[i];
}
Buffer.BlockCopy(RevData, 0, Data, SocketBuffer.Count, RevData.Length);
SocketBuffer.Clear();
return Data;
}
#endregion
#region 新增缓存
public void AddBuff(byte[] SrcArray, int offset)
{
for (int i = offset; i < SrcArray.Length; i++)
{
SocketBuffer.Add(SrcArray[i]);
}
CacheDataTime = DateTime.Now;
}
#endregion
}
#endregion
}

@ -0,0 +1,366 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace HuizhongLibrary.PageBox
{
/// <summary>
/// 弹出窗口类
/// </summary>
public class MessageBox
{
/// <summary>
/// 弹出一个新窗体,Property参数功能[yes为启用,no为不启用](height=窗口高度,width=窗口宽度,top=窗口距离屏幕上方的象素值,left=窗口距离屏幕左侧的象素值,toolbar=是否显示工具栏,menubar=是否显示菜单栏,scrollbars=是否显示滚动条,resizable=是否允许改变窗口大小,location=是否显示地址栏,status=是否显示状态栏内的信息)
/// </summary>
/// <param name="page">需要输出的窗体</param>
/// <param name="FormFileName">要显示的窗体文件名</param>
/// <param name="FormName">窗体名称</param>
public static void OpenForm(Page page, string FormFileName, string FormName, string Property)
{
page.ClientScript.RegisterStartupScript(page.GetType(),"aa", "<script language=JavaScript> window.open('" + FormFileName + "','" + FormName + "','" + Property + "');</script>");
}
/// <summary>
///1.dialogHeight :对话框高度不小于px中dialogHeight 和 dialogWidth 默认的单位是em中是px为方便其见在定义modal方式的对话框时用px做单位。
///2.dialogWidth: 对话框宽度。
///3.dialogLeft: 离屏幕左的距离。
///4.dialogTop: 离屏幕上的距离。
///5.center: {yes | no | 1 | 0 }窗口是否居中默认yes但仍可以指定高度和宽度。
///6.help: {yes | no | 1 | 0 }是否显示帮助按钮默认yes。
///7.resizable: {yes | no | 1 | 0 } 是否可被改变大小。默认no。
///8.status: {yes | no | 1 | 0 } IE5+是否显示状态栏。默认为yes[ Modeless]或no[Modal]。
///9.scroll:{ yes | no | 1 | 0 | on | off }指明对话框是否显示滚动条。默认为yes。
///下面几个属性是用在HTA中的在一般的网页中一般不使用。
///10.dialogHide:{ yes | no | 1 | 0 | on | off }在打印或者打印预览时对话框是否隐藏。默认为no。
///11.edge:{ sunken | raised }指明对话框的边框样式。默认为raised。
///12.unadorned:{ yes | no | 1 | 0 | on | off }默认为no。
/// </summary>
/// <param name="page">需要输出的窗体</param>
/// <param name="FormFileName">要显示的窗体文件名</param>
/// <param name="Arguments">参数(对话框通过window.dialogArguments来取得传递进来的参数)</param>
/// <param name="Property">窗体属性</param>
public static void OpenDialog(Page page, string FormFileName, string Arguments, string Property)
{
page.ClientScript.RegisterStartupScript(page.GetType(), "aa", "<script language=JavaScript>window.showModalDialog('" + FormFileName + "','" + Arguments + "','" + Property + "');window.document.forms[0].submit();</script>");
}
/// <summary>
/// 弹出一个新窗体,Property参数功能[yes为启用,no为不启用](height=窗口高度,width=窗口宽度,top=窗口距离屏幕上方的象素值,left=窗口距离屏幕左侧的象素值,toolbar=是否显示工具栏,menubar=是否显示菜单栏,scrollbars=是否显示滚动条,resizable=是否允许改变窗口大小,location=是否显示地址栏,status=是否显示状态栏内的信息)
/// </summary>
/// <param name="page">需要输出的窗体</param>
/// <param name="FormFileName">要显示的窗体文件名</param>
/// <param name="FormName">窗体名称</param>
/// <param name="Property">窗体参数</param>
/// <param name="ValueName">要传递的变量名称</param>
/// <param name="Value">变量的值</param>
public static void OpenForm(Page page, string FormFileName, string FormName, string Property, string ValueName, string Value)
{
page.ClientScript.RegisterStartupScript(page.GetType(), "aa", "<script language=JavaScript> window.open('" + FormFileName + "?" + ValueName + "=" + page.Server.UrlEncode(Value) + "','" + FormName + "','" + Property + "');</script>");
}
/// <summary>
//1.dialogHeight :对话框高度不小于px中dialogHeight 和 dialogWidth 默认的单位是em中是px为方便其见在定义modal方式的对话框时用px做单位。
//2.dialogWidth: 对话框宽度。
//3.dialogLeft: 离屏幕左的距离。
//4.dialogTop: 离屏幕上的距离。
//5.center: {yes | no | 1 | 0 }窗口是否居中默认yes但仍可以指定高度和宽度。
//6.help: {yes | no | 1 | 0 }是否显示帮助按钮默认yes。
//7.resizable: {yes | no | 1 | 0 } 是否可被改变大小。默认no。
//8.status: {yes | no | 1 | 0 } IE5+是否显示状态栏。默认为yes[ Modeless]或no[Modal]。
//9.scroll:{ yes | no | 1 | 0 | on | off }指明对话框是否显示滚动条。默认为yes。
//下面几个属性是用在HTA中的在一般的网页中一般不使用。
//10.dialogHide:{ yes | no | 1 | 0 | on | off }在打印或者打印预览时对话框是否隐藏。默认为no。
//11.edge:{ sunken | raised }指明对话框的边框样式。默认为raised。
//12.unadorned:{ yes | no | 1 | 0 | on | off }默认为no。
/// </summary>
/// <param name="page">需要输出的窗体</param>
/// <param name="FormFileName">要显示的窗体文件名</param>
/// <param name="Arguments">参数(对话框通过window.dialogArguments来取得传递进来的参数)</param>
/// <param name="Property">窗体属性</param>
public static void OpenDialog(Page page, string FormFileName, string Arguments, string Property, string ValueName, string Value)
{
page.ClientScript.RegisterStartupScript(page.GetType(), "aa", "<script language=JavaScript>window.showModalDialog('" + FormFileName + "?" + ValueName + "=" + page.Server.UrlEncode(Value) + "','" + Arguments + "','" + Property + "');window.document.forms[0].submit();</script>");
}
/// <summary>
/// 弹出一个新窗体,Property参数功能[yes为启用,no为不启用](height=窗口高度,width=窗口宽度,top=窗口距离屏幕上方的象素值,left=窗口距离屏幕左侧的象素值,toolbar=是否显示工具栏,menubar=是否显示菜单栏,scrollbars=是否显示滚动条,resizable=是否允许改变窗口大小,location=是否显示地址栏,status=是否显示状态栏内的信息)
/// </summary>
/// <param name="page">需要输出的窗体</param>
/// <param name="FormFileName">要显示的窗体文件名</param>
/// <param name="FormName">窗体名称</param>
/// <param name="Property">窗体参数</param>
/// <param name="ValueName">要传递的变量名称</param>
/// <param name="Value">变量的值</param>
public static void OpenForm(Page page, string FormFileName, string FormName, string Property, string ValueName, string Value, string ValueNameA, string ValueA)
{
page.ClientScript.RegisterStartupScript(page.GetType(), "aa", "<script language=JavaScript> window.open('" + FormFileName + "?" + ValueName + "=" + page.Server.UrlEncode(Value) + "&" + ValueNameA + "=" + page.Server.UrlEncode(ValueA) + "','" + FormName + "','" + Property + "');</script>");
}
/// <summary>
//1.dialogHeight :对话框高度不小于px中dialogHeight 和 dialogWidth 默认的单位是em中是px为方便其见在定义modal方式的对话框时用px做单位。
//2.dialogWidth: 对话框宽度。
//3.dialogLeft: 离屏幕左的距离。
//4.dialogTop: 离屏幕上的距离。
//5.center: {yes | no | 1 | 0 }窗口是否居中默认yes但仍可以指定高度和宽度。
//6.help: {yes | no | 1 | 0 }是否显示帮助按钮默认yes。
//7.resizable: {yes | no | 1 | 0 } 是否可被改变大小。默认no。
//8.status: {yes | no | 1 | 0 } IE5+是否显示状态栏。默认为yes[ Modeless]或no[Modal]。
//9.scroll:{ yes | no | 1 | 0 | on | off }指明对话框是否显示滚动条。默认为yes。
//下面几个属性是用在HTA中的在一般的网页中一般不使用。
//10.dialogHide:{ yes | no | 1 | 0 | on | off }在打印或者打印预览时对话框是否隐藏。默认为no。
//11.edge:{ sunken | raised }指明对话框的边框样式。默认为raised。
//12.unadorned:{ yes | no | 1 | 0 | on | off }默认为no。
/// </summary>
/// <param name="page">需要输出的窗体</param>
/// <param name="FormFileName">要显示的窗体文件名</param>
/// <param name="Arguments">参数(对话框通过window.dialogArguments来取得传递进来的参数)</param>
/// <param name="Property">窗体属性</param>
public static void OpenDialog(Page page, string FormFileName, string Arguments, string Property, string ValueName, string Value, string ValueNameA, string ValueA)
{
page.ClientScript.RegisterStartupScript(page.GetType(), "aa", "<script language=JavaScript>window.showModalDialog('" + FormFileName + "?" + ValueName + "=" + page.Server.UrlEncode(Value) + "&" + ValueNameA + "=" + page.Server.UrlEncode(ValueA) + "','" + Arguments + "','" + Property + "');window.document.forms[0].submit();</script>");
}
/// <summary>
/// 弹出一个新窗体,Property参数功能[yes为启用,no为不启用](height=窗口高度,width=窗口宽度,top=窗口距离屏幕上方的象素值,left=窗口距离屏幕左侧的象素值,toolbar=是否显示工具栏,menubar=是否显示菜单栏,scrollbars=是否显示滚动条,resizable=是否允许改变窗口大小,location=是否显示地址栏,status=是否显示状态栏内的信息)
/// </summary>
/// <param name="page">需要输出的窗体</param>
/// <param name="FormFileName">要显示的窗体文件名</param>
/// <param name="FormName">窗体名称</param>
/// <param name="Property">窗体参数</param>
/// <param name="ValueName">要传递的变量名称</param>
/// <param name="Value">变量的值</param>
public static void OpenForm(Page page, string FormFileName, string FormName, string Property, string ValueName, string Value, string ValueNameA, string ValueA, string ValueNameB, string ValueB)
{
page.ClientScript.RegisterStartupScript(page.GetType(), "aa", "<script language=JavaScript> window.open('" + FormFileName + "?" + ValueName + "=" + page.Server.UrlEncode(Value) + "&" + ValueNameA + "=" + page.Server.UrlEncode(ValueA) + "&" + ValueNameB + "=" + page.Server.UrlEncode(ValueB) + "','" + FormName + "','" + Property + "');</script>");
}
/// <summary>
//1.dialogHeight :对话框高度不小于px中dialogHeight 和 dialogWidth 默认的单位是em中是px为方便其见在定义modal方式的对话框时用px做单位。
//2.dialogWidth: 对话框宽度。
//3.dialogLeft: 离屏幕左的距离。
//4.dialogTop: 离屏幕上的距离。
//5.center: {yes | no | 1 | 0 }窗口是否居中默认yes但仍可以指定高度和宽度。
//6.help: {yes | no | 1 | 0 }是否显示帮助按钮默认yes。
//7.resizable: {yes | no | 1 | 0 } 是否可被改变大小。默认no。
//8.status: {yes | no | 1 | 0 } IE5+是否显示状态栏。默认为yes[ Modeless]或no[Modal]。
//9.scroll:{ yes | no | 1 | 0 | on | off }指明对话框是否显示滚动条。默认为yes。
//下面几个属性是用在HTA中的在一般的网页中一般不使用。
//10.dialogHide:{ yes | no | 1 | 0 | on | off }在打印或者打印预览时对话框是否隐藏。默认为no。
//11.edge:{ sunken | raised }指明对话框的边框样式。默认为raised。
//12.unadorned:{ yes | no | 1 | 0 | on | off }默认为no。
/// </summary>
/// <param name="page">需要输出的窗体</param>
/// <param name="FormFileName">要显示的窗体文件名</param>
/// <param name="Arguments">参数(对话框通过window.dialogArguments来取得传递进来的参数)</param>
/// <param name="Property">窗体属性</param>
public static void OpenDialog(Page page, string FormFileName, string Arguments, string Property, string ValueName, string Value, string ValueNameA, string ValueA, string ValueNameB, string ValueB)
{
page.ClientScript.RegisterStartupScript(page.GetType(), "aa", "<script language=JavaScript>window.showModalDialog('" + FormFileName + "?" + ValueName + "=" + page.Server.UrlEncode(Value) + "&" + ValueNameA + "=" + page.Server.UrlEncode(ValueA) + "&" + ValueNameB + "=" + page.Server.UrlEncode(ValueB) + "','" + Arguments + "','" + Property + "');window.document.forms[0].submit();</script>");
}
/// <summary>
/// 弹出一个新窗体,Property参数功能[yes为启用,no为不启用](height=窗口高度,width=窗口宽度,top=窗口距离屏幕上方的象素值,left=窗口距离屏幕左侧的象素值,toolbar=是否显示工具栏,menubar=是否显示菜单栏,scrollbars=是否显示滚动条,resizable=是否允许改变窗口大小,location=是否显示地址栏,status=是否显示状态栏内的信息)
/// </summary>
/// <param name="page">需要输出的窗体</param>
/// <param name="FormFileName">要显示的窗体文件名</param>
/// <param name="FormName">窗体名称</param>
/// <param name="Property">窗体参数</param>
/// <param name="ValueName">要传递的变量名称</param>
/// <param name="Value">变量的值</param>
public static void OpenForm(Page page, string FormFileName, string FormName, string Property, string ValueName, string Value, string ValueNameA, string ValueA, string ValueNameB, string ValueB, string ValueNameC, string ValueC)
{
page.ClientScript.RegisterStartupScript(page.GetType(), "aa", "<script language=JavaScript> window.open('" + FormFileName + "?" + ValueName + "=" + page.Server.UrlEncode(Value) + "&" + ValueNameA + "=" + page.Server.UrlEncode(ValueA) + "&" + ValueNameB + "=" + page.Server.UrlEncode(ValueB) + "&" + ValueNameC + "=" + page.Server.UrlEncode(ValueC) + "','" + FormName + "','" + Property + "');</script>");
}
/// <summary>
//1.dialogHeight :对话框高度不小于px中dialogHeight 和 dialogWidth 默认的单位是em中是px为方便其见在定义modal方式的对话框时用px做单位。
//2.dialogWidth: 对话框宽度。
//3.dialogLeft: 离屏幕左的距离。
//4.dialogTop: 离屏幕上的距离。
//5.center: {yes | no | 1 | 0 }窗口是否居中默认yes但仍可以指定高度和宽度。
//6.help: {yes | no | 1 | 0 }是否显示帮助按钮默认yes。
//7.resizable: {yes | no | 1 | 0 } 是否可被改变大小。默认no。
//8.status: {yes | no | 1 | 0 } IE5+是否显示状态栏。默认为yes[ Modeless]或no[Modal]。
//9.scroll:{ yes | no | 1 | 0 | on | off }指明对话框是否显示滚动条。默认为yes。
//下面几个属性是用在HTA中的在一般的网页中一般不使用。
//10.dialogHide:{ yes | no | 1 | 0 | on | off }在打印或者打印预览时对话框是否隐藏。默认为no。
//11.edge:{ sunken | raised }指明对话框的边框样式。默认为raised。
//12.unadorned:{ yes | no | 1 | 0 | on | off }默认为no。
/// </summary>
/// <param name="page">需要输出的窗体</param>
/// <param name="FormFileName">要显示的窗体文件名</param>
/// <param name="Arguments">参数(对话框通过window.dialogArguments来取得传递进来的参数)</param>
/// <param name="Property">窗体属性</param>
public static void OpenDialog(Page page, string FormFileName, string Arguments, string Property, string ValueName, string Value, string ValueNameA, string ValueA, string ValueNameB, string ValueB, string ValueNameC, string ValueC)
{
page.ClientScript.RegisterStartupScript(page.GetType(), "aa", "<script language=JavaScript>window.showModalDialog('" + FormFileName + "?" + ValueName + "=" + page.Server.UrlEncode(Value) + "&" + ValueNameA + "=" + page.Server.UrlEncode(ValueA) + "&" + ValueNameB + "=" + page.Server.UrlEncode(ValueB) + "&" + ValueNameC + "=" + page.Server.UrlEncode(ValueC) + "','" + Arguments + "','" + Property + "');window.document.forms[0].submit();</script>");
}
/// <summary>
/// 弹出一个新窗体,Property参数功能[yes为启用,no为不启用](height=窗口高度,width=窗口宽度,top=窗口距离屏幕上方的象素值,left=窗口距离屏幕左侧的象素值,toolbar=是否显示工具栏,menubar=是否显示菜单栏,scrollbars=是否显示滚动条,resizable=是否允许改变窗口大小,location=是否显示地址栏,status=是否显示状态栏内的信息)
/// </summary>
/// <param name="page">需要输出的窗体</param>
/// <param name="FormFileName">要显示的窗体文件名</param>
/// <param name="FormName">窗体名称</param>
/// <param name="Property">窗体参数</param>
/// <param name="ValueName">要传递的变量名称</param>
/// <param name="Value">变量的值</param>
public static void OpenForm(Page page, string FormFileName, string FormName, string Property, string ValueName, string Value, string ValueNameA, string ValueA, string ValueNameB, string ValueB, string ValueNameC, string ValueC, string ValueNameD, string ValueD)
{
page.ClientScript.RegisterStartupScript(page.GetType(), "aa", "<script language=JavaScript> window.open('" + FormFileName + "?" + ValueName + "=" + page.Server.UrlEncode(Value) + "&" + ValueNameA + "=" + page.Server.UrlEncode(ValueA) + "&" + ValueNameB + "=" + page.Server.UrlEncode(ValueB) + "&" + ValueNameC + "=" + page.Server.UrlEncode(ValueC) + "&" + ValueNameD + "=" + page.Server.UrlEncode(ValueD) + "','" + FormName + "','" + Property + "');</script>");
}
/// <summary>
//1.dialogHeight :对话框高度不小于px中dialogHeight 和 dialogWidth 默认的单位是em中是px为方便其见在定义modal方式的对话框时用px做单位。
//2.dialogWidth: 对话框宽度。
//3.dialogLeft: 离屏幕左的距离。
//4.dialogTop: 离屏幕上的距离。
//5.center: {yes | no | 1 | 0 }窗口是否居中默认yes但仍可以指定高度和宽度。
//6.help: {yes | no | 1 | 0 }是否显示帮助按钮默认yes。
//7.resizable: {yes | no | 1 | 0 } 是否可被改变大小。默认no。
//8.status: {yes | no | 1 | 0 } IE5+是否显示状态栏。默认为yes[ Modeless]或no[Modal]。
//9.scroll:{ yes | no | 1 | 0 | on | off }指明对话框是否显示滚动条。默认为yes。
//下面几个属性是用在HTA中的在一般的网页中一般不使用。
//10.dialogHide:{ yes | no | 1 | 0 | on | off }在打印或者打印预览时对话框是否隐藏。默认为no。
//11.edge:{ sunken | raised }指明对话框的边框样式。默认为raised。
//12.unadorned:{ yes | no | 1 | 0 | on | off }默认为no。
/// </summary>
/// <param name="page">需要输出的窗体</param>
/// <param name="FormFileName">要显示的窗体文件名</param>
/// <param name="Arguments">参数(对话框通过window.dialogArguments来取得传递进来的参数)</param>
/// <param name="Property">窗体属性</param>
public static void OpenDialog(Page page, string FormFileName, string Arguments, string Property, string ValueName, string Value, string ValueNameA, string ValueA, string ValueNameB, string ValueB, string ValueNameC, string ValueC, string ValueNameD, string ValueD)
{
page.ClientScript.RegisterStartupScript(page.GetType(), "aa", "<script language=JavaScript>window.showModalDialog('" + FormFileName + "?" + ValueName + "=" + page.Server.UrlEncode(Value) + "&" + ValueNameA + "=" + page.Server.UrlEncode(ValueA) + "&" + ValueNameB + "=" + page.Server.UrlEncode(ValueB) + "&" + ValueNameC + "=" + page.Server.UrlEncode(ValueC) + "&" + ValueNameD + "=" + page.Server.UrlEncode(ValueD) + "','" + Arguments + "','" + Property + "');window.document.forms[0].submit();</script>");
}
/// <summary>
/// 弹出一个新窗体,Property参数功能[yes为启用,no为不启用](height=窗口高度,width=窗口宽度,top=窗口距离屏幕上方的象素值,left=窗口距离屏幕左侧的象素值,toolbar=是否显示工具栏,menubar=是否显示菜单栏,scrollbars=是否显示滚动条,resizable=是否允许改变窗口大小,location=是否显示地址栏,status=是否显示状态栏内的信息)
/// </summary>
/// <param name="page">需要输出的窗体</param>
/// <param name="FormFileName">要显示的窗体文件名</param>
/// <param name="FormName">窗体名称</param>
/// <param name="Property">窗体参数</param>
/// <param name="ValueName">要传递的变量名称</param>
/// <param name="Value">变量的值</param>
public static void OpenForm(Page page, string FormFileName, string FormName, string Property, string ValueName, string Value, string ValueNameA, string ValueA, string ValueNameB, string ValueB, string ValueNameC, string ValueC, string ValueNameD, string ValueD, string ValueNameE, string ValueE)
{
page.ClientScript.RegisterStartupScript(page.GetType(), "aa", "<script language=JavaScript> window.open('" + FormFileName + "?" + ValueName + "=" + page.Server.UrlEncode(Value) + "&" + ValueNameA + "=" + page.Server.UrlEncode(ValueA) + "&" + ValueNameB + "=" + page.Server.UrlEncode(ValueB) + "&" + ValueNameC + "=" + page.Server.UrlEncode(ValueC) + "&" + ValueNameD + "=" + page.Server.UrlEncode(ValueD) + "&" + ValueNameE + "=" + page.Server.UrlEncode(ValueE) + "','" + FormName + "','" + Property + "');</script>");
}
/// <summary>
//1.dialogHeight :对话框高度不小于px中dialogHeight 和 dialogWidth 默认的单位是em中是px为方便其见在定义modal方式的对话框时用px做单位。
//2.dialogWidth: 对话框宽度。
//3.dialogLeft: 离屏幕左的距离。
//4.dialogTop: 离屏幕上的距离。
//5.center: {yes | no | 1 | 0 }窗口是否居中默认yes但仍可以指定高度和宽度。
//6.help: {yes | no | 1 | 0 }是否显示帮助按钮默认yes。
//7.resizable: {yes | no | 1 | 0 } 是否可被改变大小。默认no。
//8.status: {yes | no | 1 | 0 } IE5+是否显示状态栏。默认为yes[ Modeless]或no[Modal]。
//9.scroll:{ yes | no | 1 | 0 | on | off }指明对话框是否显示滚动条。默认为yes。
//下面几个属性是用在HTA中的在一般的网页中一般不使用。
//10.dialogHide:{ yes | no | 1 | 0 | on | off }在打印或者打印预览时对话框是否隐藏。默认为no。
//11.edge:{ sunken | raised }指明对话框的边框样式。默认为raised。
//12.unadorned:{ yes | no | 1 | 0 | on | off }默认为no。
/// </summary>
/// <param name="page">需要输出的窗体</param>
/// <param name="FormFileName">要显示的窗体文件名</param>
/// <param name="Arguments">参数(对话框通过window.dialogArguments来取得传递进来的参数)</param>
/// <param name="Property">窗体属性</param>
public static void OpenDialog(Page page, string FormFileName, string Arguments, string Property, string ValueName, string Value, string ValueNameA, string ValueA, string ValueNameB, string ValueB, string ValueNameC, string ValueC, string ValueNameD, string ValueD, string ValueNameE, string ValueE)
{
page.ClientScript.RegisterStartupScript(page.GetType(), "aa", "<script language=JavaScript>window.showModalDialog('" + FormFileName + "?" + ValueName + "=" + page.Server.UrlEncode(Value) + "&" + ValueNameA + "=" + page.Server.UrlEncode(ValueA) + "&" + ValueNameB + "=" + page.Server.UrlEncode(ValueB) + "&" + ValueNameC + "=" + page.Server.UrlEncode(ValueC) + "&" + ValueNameD + "=" + page.Server.UrlEncode(ValueD) + "&" + ValueNameE + "=" + page.Server.UrlEncode(ValueE) + "','" + Arguments + "','" + Property + "');window.document.forms[0].submit();</script>");
}
/// <summary>
/// 弹出一个新窗体,Property参数功能[yes为启用,no为不启用](height=窗口高度,width=窗口宽度,top=窗口距离屏幕上方的象素值,left=窗口距离屏幕左侧的象素值,toolbar=是否显示工具栏,menubar=是否显示菜单栏,scrollbars=是否显示滚动条,resizable=是否允许改变窗口大小,location=是否显示地址栏,status=是否显示状态栏内的信息)
/// </summary>
/// <param name="page">需要输出的窗体</param>
/// <param name="FormFileName">要显示的窗体文件名</param>
/// <param name="FormName">窗体名称</param>
/// <param name="Property">窗体参数</param>
/// <param name="ValueName">要传递的变量名称</param>
/// <param name="Value">变量的值</param>
public static void OpenForm(Page page, string FormFileName, string FormName, string Property, string ValueName, string Value, string ValueNameA, string ValueA, string ValueNameB, string ValueB, string ValueNameC, string ValueC, string ValueNameD, string ValueD, string ValueNameE, string ValueE, string ValueNameF, string ValueF)
{
page.ClientScript.RegisterStartupScript(page.GetType(), "aa", "<script language=JavaScript> window.open('" + FormFileName + "?" + ValueName + "=" + page.Server.UrlEncode(Value) + "&" + ValueNameA + "=" + page.Server.UrlEncode(ValueA) + "&" + ValueNameB + "=" + page.Server.UrlEncode(ValueB) + "&" + ValueNameC + "=" + page.Server.UrlEncode(ValueC) + "&" + ValueNameD + "=" + page.Server.UrlEncode(ValueD) + "&" + ValueNameE + "=" + page.Server.UrlEncode(ValueE) + "&" + ValueNameF + "=" + page.Server.UrlEncode(ValueF) + "','" + FormName + "','" + Property + "');</script>");
}
/// <summary>
//1.dialogHeight :对话框高度不小于px中dialogHeight 和 dialogWidth 默认的单位是em中是px为方便其见在定义modal方式的对话框时用px做单位。
//2.dialogWidth: 对话框宽度。
//3.dialogLeft: 离屏幕左的距离。
//4.dialogTop: 离屏幕上的距离。
//5.center: {yes | no | 1 | 0 }窗口是否居中默认yes但仍可以指定高度和宽度。
//6.help: {yes | no | 1 | 0 }是否显示帮助按钮默认yes。
//7.resizable: {yes | no | 1 | 0 } 是否可被改变大小。默认no。
//8.status: {yes | no | 1 | 0 } IE5+是否显示状态栏。默认为yes[ Modeless]或no[Modal]。
//9.scroll:{ yes | no | 1 | 0 | on | off }指明对话框是否显示滚动条。默认为yes。
//下面几个属性是用在HTA中的在一般的网页中一般不使用。
//10.dialogHide:{ yes | no | 1 | 0 | on | off }在打印或者打印预览时对话框是否隐藏。默认为no。
//11.edge:{ sunken | raised }指明对话框的边框样式。默认为raised。
//12.unadorned:{ yes | no | 1 | 0 | on | off }默认为no。
/// </summary>
/// <param name="page">需要输出的窗体</param>
/// <param name="FormFileName">要显示的窗体文件名</param>
/// <param name="Arguments">参数(对话框通过window.dialogArguments来取得传递进来的参数)</param>
/// <param name="Property">窗体属性</param>
public static void OpenDialog(Page page, string FormFileName, string Arguments, string Property, string ValueName, string Value, string ValueNameA, string ValueA, string ValueNameB, string ValueB, string ValueNameC, string ValueC, string ValueNameD, string ValueD, string ValueNameE, string ValueE, string ValueNameF, string ValueF)
{
page.ClientScript.RegisterStartupScript(page.GetType(), "aa", "<script language=JavaScript>window.showModalDialog('" + FormFileName + "?" + ValueName + "=" + page.Server.UrlEncode(Value) + "&" + ValueNameA + "=" + page.Server.UrlEncode(ValueA) + "&" + ValueNameB + "=" + page.Server.UrlEncode(ValueB) + "&" + ValueNameC + "=" + page.Server.UrlEncode(ValueC) + "&" + ValueNameD + "=" + page.Server.UrlEncode(ValueD) + "&" + ValueNameE + "=" + page.Server.UrlEncode(ValueE) + "&" + ValueNameF + "=" + page.Server.UrlEncode(ValueF) + "','" + Arguments + "','" + Property + "');window.document.forms[0].submit();</script>");
}
/// <summary>
/// 弹出一个确定按钮对话框
/// </summary>
public static void Show(Page page, string msg)
{
if (page.Session["CodeTest"] != null) return;
page.ClientScript.RegisterStartupScript(page.GetType(), "b1", "<script language=javascript>window.alert(\"" + msg + "\");</script>");
}
/// <summary>
/// 弹出一个确定按钮对话框
/// </summary>
public static void Show(System.Web.UI.WebControls.WebControl ctrl, string msg)
{
if (ctrl.Page.Session["CodeTest"] != null) return;
ctrl.Page.ClientScript.RegisterStartupScript(ctrl.Page.GetType(), "b2", "<script language=javascript>window.alert(\"" + msg + "\");</script>");
ctrl.Focus();
}
/// <summary>
/// 执行JS代码
/// </summary>
public static void RegisterStartupScript(Page page, string script)
{
if (page.Session["CodeTest"] != null) return;
page.ClientScript.RegisterStartupScript(page.GetType(), "b3", "<script type='text/javascript' language='javascript'>" + script + "</script>");
}
/// <summary>
/// 弹出一个确定与取消按钮对话框
/// </summary>
public static void Show(Page page, string msg, string key)
{
if (page.Session["CodeTest"] != null) return;
if (key == "") { key = "b4"; }
page.ClientScript.RegisterStartupScript(page.GetType(), key, "<script language=javascript>return window.confirm(\"" + msg + "\");</script>");
}
}//类结束
}

@ -0,0 +1,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HuizhongLibrary.PhonePay
{
public class AliPay
{
}
}

@ -0,0 +1,180 @@
using HuizhongLibrary.Log;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using WxPayAPI;
namespace HuizhongLibrary.PhonePay
{
public class WeiXinPay
{
public string url { get; set; }
public string key { get; set; }
//https://api.mch.weixin.qq.com/pay/unifiedorder
public WeiXinPay()
{
}
/// <summary>
/// openid用于调用统一下单接口
/// </summary>
public string openid { get; set; }
/// <summary>
/// access_token用于获取收货地址js函数入口参数
/// </summary>
public string access_token { get; set; }
/// <summary>
/// 商品金额,用于统一下单
/// </summary>
public int total_fee { get; set; }
public string trade_type { get; set; }
/// <summary>
/// 统一下单接口返回结果
/// </summary>
public WxPayData unifiedOrderResult { get; set; }
public WxPayData GetUnifiedOrderResult()
{
//统一下单
WxPayData data = new WxPayData();
data.SetValue("body", "test");
data.SetValue("attach", "test");
data.SetValue("out_trade_no", WxPayApi.GenerateOutTradeNo());
data.SetValue("total_fee", total_fee);
data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));
data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss"));
data.SetValue("goods_tag", "test");
data.SetValue("trade_type", trade_type);
data.SetValue("openid", openid);
ErrorFollow.TraceWrite("GetUnifiedOrderResult", "openid:", openid);
WxPayData result = WxPayApi.UnifiedOrder(data);
if (!result.IsSet("appid") || !result.IsSet("prepay_id") || result.GetValue("prepay_id").ToString() == "")
{
ErrorFollow.TraceWrite("GetUnifiedOrderResult",this.GetType().ToString(), "UnifiedOrder response error!");
// Log.Error(this.GetType().ToString(), "UnifiedOrder response error!");
// throw new WxPayException("UnifiedOrder response error!");
}
unifiedOrderResult = result;
return result;
}
public string unifiedorder(WeiXinPayModel model)
{
//StringBuilder sb = new StringBuilder();
//sb.Append("<xml>");
//sb.Append("<appid>"+model.appid+"</appid>");
//sb.Append("<attach>"+model.attach+"</attach>");
//sb.Append("<body>"+model.body+"</body>");
//sb.Append("<mch_id>" + model.mch_id + "</mch_id>");
//sb.Append("<nonce_str>" + model.nonce_str + "</nonce_str>");
//sb.Append("< notify_url >"+model.notify_url+"</notify_url>");
//if(model.openid!=null&&model.openid!="")
//sb.Append("<openid>"+ model.openid + "</openid>");
//sb.Append("<out_trade_no>"+model.out_trade_no+"</out_trade_no>");
//sb.Append("<spbill_create_ip>"+model.spbill_create_ip+"</spbill_create_ip>");
//sb.Append("<total_fee >"+model.total_fee+"</total_fee>");
//sb.Append("<spbill_create_ip>" + model.spbill_create_ip + "</spbill_create_ip>");
//sb.Append("<trade_type>"+model.trade_type+"</trade_type>");
//sb.Append("<scene_info>{ \"h5_info\": { \"type\":"+model.scene_info.h5_info.type + ",\"wap_name\": " + model.scene_info.h5_info.wap_name + ",\"wap_url\": " + model.scene_info.h5_info.wap_url+"} }</scene_info>");
//sb.Append("<sign>"+model.sign+"</sign>");
//sb.Append("</xml>");
return "";
//< appid > wx2421b1c4370ec43b </ appid >
//< attach > 支付测试 </ attach >
//< body > H5支付测试 </ body >
//< mch_id > 10000100 </ mch_id >
//< nonce_str > 1add1a30ac87aa2db72f57a2375d8fec </ nonce_str >
// < notify_url > http://wxpay.wxutil.com/pub_v2/pay/notify.v2.php</notify_url>
//< openid > oUpF8uMuAJO_M2pxb1Q9zNjWeS6o </ openid >
//< out_trade_no > 1415659990 </ out_trade_no >
//< spbill_create_ip > 14.23.150.211 </ spbill_create_ip >
// < total_fee > 1 </ total_fee >
// < trade_type > MWEB </ trade_type >
// < scene_info >{ "h5_info": { "type":"IOS","app_name": "王者荣耀","package_name": "com.tencent.tmgp.sgame"} }</ scene_info >
// < sign > 0CB01533B8C1EF103065174F50BCA001 </ sign >
// </ xml >
}
}
public class WeiXinPayModel
{
public string appid { get; set; }
public string attach { get; set; }
public string mch_id { get; set; }
public string body { get; set; }
public string nonce_str { get; set; }
public string notify_url { get; set; }
public string openid { get; set; }
public string out_trade_no { get; set; }
public string spbill_create_ip { get; set; }
public string total_fee { get; set; }
public string trade_type { get; set; }
public scene_info scene_info { get; set; }
public string sign { get; set; }
}
public class scene_info
{
//{"h5_info": {"type":"Wap","wap_url": "https://pay.qq.com","wap_name": "腾讯充值"}}
public h5_info h5_info { get; set; }
}
public class h5_info
{
public string type { get; set; }
public string wap_url { get; set; }
public string wap_name { get; set; }
}
public class Return_info
{
public string return_code { get; set; }
public string return_msg { get; set; }
public string appid { get; set; }
public string mch_id { get; set; }
public string nonce_str { get; set; }
public string sign { get; set; }
public string prepay_id { get; set; }
public string trade_type { get; set; }
public string mweb_url { get; set; }
// <xml>
// <return_code><![CDATA[SUCCESS]]></return_code>
// <return_msg><![CDATA[OK]]></return_msg>
// <appid><![CDATA[wx2421b1c4370ec43b]]></appid>
// <mch_id><![CDATA[10000100]]></mch_id>
// <nonce_str><![CDATA[IITRi8Iabbblz1Jc]]></nonce_str>
// <sign><![CDATA[7921E432F65EB8ED0CE9755F0E86D72F]]></sign>
// <result_code><![CDATA[SUCCESS]]></result_code>
// <prepay_id><![CDATA[wx201411101639507cbf6ffd8b0779950874]]></prepay_id>
// <trade_type><![CDATA[MWEB]]></trade_type>
// <mweb_url><![CDATA[https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb?prepay_id=wx2016121516420242444321ca0631331346&package=1405458241]]></mweb_url>
//</xml>
}
}

@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Web;
namespace WxPayAPI
{
public class DownloadBill
{
/***
*
* @param bill_date 20140603
* @param bill_type
* ALL
* SUCCESS
* REFUND退
* REVOKED
* @return xml
*/
public static string Run(string bill_date, string bill_type)
{
Log.Info("DownloadBill", "DownloadBill is processing...");
WxPayData data = new WxPayData();
data.SetValue("bill_date", bill_date);//账单日期
data.SetValue("bill_type", bill_type);//账单类型
WxPayData result = WxPayApi.DownloadBill(data);//提交下载对账单请求给API接收返回结果
Log.Info("DownloadBill", "DownloadBill process complete, result : " + result.ToXml());
return result.ToPrintStr();
}
}
}

@ -0,0 +1,326 @@
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Runtime.Serialization;
using System.IO;
using System.Text;
using System.Net;
using System.Web.Security;
using LitJson;
using HuizhongLibrary.Log;
namespace WxPayAPI
{
public class JsApiPay
{
/// <summary>
/// 保存页面对象因为要在类的方法中使用Page的Request对象
/// </summary>
private Page page {get;set;}
/// <summary>
/// openid用于调用统一下单接口
/// </summary>
public string openid { get; set; }
/// <summary>
/// access_token用于获取收货地址js函数入口参数
/// </summary>
public string access_token { get; set; }
/// <summary>
/// 商品金额,用于统一下单
/// </summary>
public int total_fee { get; set; }
/// <summary>
/// 统一下单接口返回结果
/// </summary>
public WxPayData unifiedOrderResult { get; set; }
public JsApiPay(Page page)
{
this.page = page;
}
/**
*
*
* http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html
* urlcode
* codeopenidaccess_token
*
*/
public void GetOpenidAndAccessToken()
{
if (!string.IsNullOrEmpty(page.Request.QueryString["code"]))
{
//获取code码以获取openid和access_token
string code = page.Request.QueryString["code"];
ErrorFollow.TraceWrite("GetOpenidAndAccessTokenFromCode", this.GetType().ToString(), "Get code : " + code);
//Log.Debug(this.GetType().ToString(), "Get code : " + code);
GetOpenidAndAccessTokenFromCode(code);
}
else
{
//构造网页授权获取code的URL
string host = page.Request.Url.Host;
string path = page.Request.Path;
string Query="";
if (!string.IsNullOrEmpty(page.Request.QueryString["MoneyNum"]))
Query = "?ordercode=" + page.Request.QueryString["ordercode"] + "&MoneyNum=" + page.Request.QueryString["MoneyNum"];
else
if (!string.IsNullOrEmpty(page.Request.QueryString["ItemNo"]))
Query = "?ItemNo=" + page.Request.QueryString["ItemNo"] + "&PayNum=" + page.Request.QueryString["PayNum"];
else if (!string.IsNullOrEmpty(page.Request.QueryString["PayNum"]))
Query = "?CompanyId=" + page.Request.QueryString["CompanyId"] + "&PayNum=" + page.Request.QueryString["PayNum"] + "&UserId=" + page.Request.QueryString["UserId"] + "&AppType=" + page.Request.QueryString["AppType"] + "&UserName=" + page.Request.QueryString["UserName"] + "&ReaName=" + page.Request.QueryString["ReaName"];
ErrorFollow.TraceWrite("Query", "", page.Request.QueryString["MoneyNum"]);
ErrorFollow.TraceWrite("Query2", "", Query);
// ErrorFollow.TraceWrite("GetOpenidAndAccessTokenFromCode", "redirect_uri:", path);
string redirect_uri = HttpUtility.UrlEncode("http://" + host + path + Query);
ErrorFollow.TraceWrite("redirect_uri", "redirect_uri:", redirect_uri);
WxPayData data = new WxPayData();
// ErrorFollow.TraceWrite("GetOpenidAndAccessTokenFromCode", "APPID:", WxPayConfig.APPID);
// ErrorFollow.TraceWrite("GetOpenidAndAccessTokenFromCode", "redirect_uri:", WxPayConfig.APPID);
data.SetValue("appid", WxPayConfig.APPID);
data.SetValue("redirect_uri", redirect_uri);
data.SetValue("response_type", "code");
data.SetValue("scope", "snsapi_base");
data.SetValue("state", "STATE" + "#wechat_redirect");
string url = "https://open.weixin.qq.com/connect/oauth2/authorize?" + data.ToUrl();
Log.Debug(this.GetType().ToString(), "Will Redirect to URL : " + url);
try
{
//触发微信返回code码
page.Response.Redirect(url);//Redirect函数会抛出ThreadAbortException异常不用处理这个异常
}
catch(System.Threading.ThreadAbortException ex)
{
ErrorFollow.TraceWrite("GetOpenidAndAccessTokenFromCode", "redirect_uri:", ex.Message);
}
}
}
public void GetOpenidAndAccessTokenOrder()
{
if (!string.IsNullOrEmpty(page.Request.QueryString["code"]))
{
//获取code码以获取openid和access_token
string code = page.Request.QueryString["code"];
ErrorFollow.TraceWrite("GetOpenidAndAccessTokenFromCode", this.GetType().ToString(), "Get code : " + code);
//Log.Debug(this.GetType().ToString(), "Get code : " + code);
GetOpenidAndAccessTokenFromCode(code);
}
else
{
//构造网页授权获取code的URL
string host = page.Request.Url.Host;
string path = page.Request.Path;
string Query = "";
if (!string.IsNullOrEmpty(page.Request.QueryString["out_trade_no"]))
Query = "?CompanyId=" + page.Request.QueryString["CompanyId"] + "&Amount=" + page.Request.QueryString["Amount"] + "&AppType=" + page.Request.QueryString["AppType"] + "&out_trade_no=" + page.Request.QueryString["out_trade_no"];
ErrorFollow.TraceWrite("Query", "", page.Request.QueryString["MoneyNum"]);
ErrorFollow.TraceWrite("Query2", "", Query);
// ErrorFollow.TraceWrite("GetOpenidAndAccessTokenFromCode", "redirect_uri:", path);
string redirect_uri = HttpUtility.UrlEncode("http://" + host + path + Query);
ErrorFollow.TraceWrite("redirect_uri", "redirect_uri:", redirect_uri);
WxPayData data = new WxPayData();
// ErrorFollow.TraceWrite("GetOpenidAndAccessTokenFromCode", "APPID:", WxPayConfig.APPID);
// ErrorFollow.TraceWrite("GetOpenidAndAccessTokenFromCode", "redirect_uri:", WxPayConfig.APPID);
data.SetValue("appid", WxPayConfig.APPID);
data.SetValue("redirect_uri", redirect_uri);
data.SetValue("response_type", "code");
data.SetValue("scope", "snsapi_base");
data.SetValue("state", "STATE" + "#wechat_redirect");
string url = "https://open.weixin.qq.com/connect/oauth2/authorize?" + data.ToUrl();
Log.Debug(this.GetType().ToString(), "Will Redirect to URL : " + url);
try
{
//触发微信返回code码
page.Response.Redirect(url);//Redirect函数会抛出ThreadAbortException异常不用处理这个异常
}
catch (System.Threading.ThreadAbortException ex)
{
ErrorFollow.TraceWrite("GetOpenidAndAccessTokenFromCode", "redirect_uri:", ex.Message);
}
}
}
/**
*
* codeaccess_tokenopenidJSON
* {
* "access_token":"ACCESS_TOKEN",
* "expires_in":7200,
* "refresh_token":"REFRESH_TOKEN",
* "openid":"OPENID",
* "scope":"SCOPE",
* "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
* }
* access_token
* openidjsapi
* http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html
* @WxPayException
*/
public void GetOpenidAndAccessTokenFromCode(string code)
{
try
{
//构造获取openid及access_token的url
WxPayData data = new WxPayData();
data.SetValue("appid", WxPayConfig.APPID);
data.SetValue("secret", WxPayConfig.APPSECRET);
data.SetValue("code", code);
data.SetValue("grant_type", "authorization_code");
string url = "https://api.weixin.qq.com/sns/oauth2/access_token?" + data.ToUrl();
//请求url以获取数据
string result = HttpService.Get(url);
Log.Debug(this.GetType().ToString(), "GetOpenidAndAccessTokenFromCode response : " + result);
//保存access_token用于收货地址获取
JsonData jd = JsonMapper.ToObject(result);
access_token = (string)jd["access_token"];
//获取用户openid
openid = (string)jd["openid"];
Log.Debug(this.GetType().ToString(), "Get openid : " + openid);
Log.Debug(this.GetType().ToString(), "Get access_token : " + access_token);
}
catch (Exception ex)
{
Log.Error(this.GetType().ToString(), ex.ToString());
throw new WxPayException(ex.ToString());
}
}
/**
*
* @return
* @WxPayException
*/
public WxPayData GetUnifiedOrderResult(string out_trade_no)
{
//统一下单
WxPayData data = new WxPayData();
data.SetValue("body", "平台服务");
data.SetValue("attach", "平台服务");
data.SetValue("out_trade_no", out_trade_no);//WxPayApi.GenerateOutTradeNo()
data.SetValue("total_fee", total_fee);
data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));
data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss"));
data.SetValue("goods_tag", "平台服务");
data.SetValue("trade_type", "JSAPI");
data.SetValue("openid", openid);
WxPayData result = WxPayApi.UnifiedOrder(data);
if (!result.IsSet("appid") || !result.IsSet("prepay_id") || result.GetValue("prepay_id").ToString() == "")
{
Log.Error(this.GetType().ToString(), "UnifiedOrder response error!");
throw new WxPayException("UnifiedOrder response error!");
}
unifiedOrderResult = result;
return result;
}
/**
*
* jsapi
* JSAPI
* {
* "appId" : "wx2421b1c4370ec43b", //公众号名称,由商户传入
* "timeStamp":" 1395712654", //时间戳自1970年以来的秒数
* "nonceStr" : "e61463f8efa94090b1f366cccfbbb444", //随机串
* "package" : "prepay_id=u802345jgfjsdfgsdg888",
* "signType" : "MD5", //微信签名方式:
* "paySign" : "70EA570631E4BB79628FBCA90534C63FF7FADD89" //微信签名
* }
* @return string JSAPIjson
* APIhttp://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_7
*
*/
public string GetJsApiParameters()
{
Log.Debug(this.GetType().ToString(), "JsApiPay::GetJsApiParam is processing...");
WxPayData jsApiParam = new WxPayData();
jsApiParam.SetValue("appId", unifiedOrderResult.GetValue("appid"));
jsApiParam.SetValue("timeStamp", WxPayApi.GenerateTimeStamp());
jsApiParam.SetValue("nonceStr", WxPayApi.GenerateNonceStr());
jsApiParam.SetValue("package", "prepay_id=" + unifiedOrderResult.GetValue("prepay_id"));
jsApiParam.SetValue("signType", "MD5");
jsApiParam.SetValue("paySign", jsApiParam.MakeSign());
string parameters = jsApiParam.ToJson();
Log.Debug(this.GetType().ToString(), "Get jsApiParam : " + parameters);
return parameters;
}
/**
*
* js,http://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_9
* @return string jsjson使
*/
public string GetEditAddressParameters()
{
string parameter = "";
try
{
string host = page.Request.Url.Host;
string path = page.Request.Path;
string queryString = page.Request.Url.Query;
//这个地方要注意参与签名的是网页授权获取用户信息时微信后台回传的完整url
//string url = "http://wx.huizsoft.com" + path + queryString;
string url = "http://" + host + path + queryString;
//构造需要用SHA1算法加密的数据
WxPayData signData = new WxPayData();
signData.SetValue("appid",WxPayConfig.APPID);
signData.SetValue("url", url);
signData.SetValue("timestamp",WxPayApi.GenerateTimeStamp());
signData.SetValue("noncestr",WxPayApi.GenerateNonceStr());
signData.SetValue("accesstoken",access_token);
string param = signData.ToUrl();
Log.Debug(this.GetType().ToString(), "SHA1 encrypt param : " + param);
//SHA1加密
string addrSign = FormsAuthentication.HashPasswordForStoringInConfigFile(param, "SHA1");
Log.Debug(this.GetType().ToString(), "SHA1 encrypt result : " + addrSign);
//获取收货地址js函数入口参数
WxPayData afterData = new WxPayData();
afterData.SetValue("appId",WxPayConfig.APPID);
afterData.SetValue("scope","jsapi_address");
afterData.SetValue("signType","sha1");
afterData.SetValue("addrSign",addrSign);
afterData.SetValue("timeStamp",signData.GetValue("timestamp"));
afterData.SetValue("nonceStr",signData.GetValue("noncestr"));
//转为json格式
parameter = afterData.ToJson();
Log.Debug(this.GetType().ToString(), "Get EditAddressParam : " + parameter);
}
catch (Exception ex)
{
Log.Error(this.GetType().ToString(), ex.ToString());
throw new WxPayException(ex.ToString());
}
return parameter;
}
}
}

@ -0,0 +1,183 @@
using System;
using System.Collections.Generic;
using System.Web;
using System.Threading;
namespace WxPayAPI
{
public class MicroPay
{
/**
*
* @param body
* @param total_fee
* @param auth_code
* @throws WxPayException
* @return
*/
public static string Run(string body, string total_fee, string auth_code)
{
Log.Info("MicroPay", "Micropay is processing...");
WxPayData data = new WxPayData();
data.SetValue("auth_code", auth_code);//授权码
data.SetValue("body", body);//商品描述
data.SetValue("total_fee", int.Parse(total_fee));//总金额
data.SetValue("out_trade_no", WxPayApi.GenerateOutTradeNo());//产生随机的商户订单号
WxPayData result = WxPayApi.Micropay(data, 10); //提交被扫支付,接收返回结果
//如果提交被扫支付接口调用失败,则抛异常
if (!result.IsSet("return_code") || result.GetValue("return_code").ToString() == "FAIL")
{
string returnMsg = result.IsSet("return_msg") ? result.GetValue("return_msg").ToString() : "";
Log.Error("MicroPay", "Micropay API interface call failure, result : " + result.ToXml());
throw new WxPayException("Micropay API interface call failure, return_msg : " + returnMsg);
}
//签名验证
result.CheckSign();
Log.Debug("MicroPay", "Micropay response check sign success");
//刷卡支付直接成功
if(result.GetValue("return_code").ToString() == "SUCCESS" &&
result.GetValue("result_code").ToString() == "SUCCESS")
{
Log.Debug("MicroPay", "Micropay business success, result : " + result.ToXml());
return result.ToPrintStr();
}
/******************************************************************
*
* ****************************************************************/
//1业务结果明确失败
if(result.GetValue("err_code").ToString() != "USERPAYING" &&
result.GetValue("err_code").ToString() != "SYSTEMERROR")
{
Log.Error("MicroPay", "micropay API interface call success, business failure, result : " + result.ToXml());
return result.ToPrintStr();
}
//2不能确定是否失败需查单
//用商户订单号去查单
string out_trade_no = data.GetValue("out_trade_no").ToString();
//确认支付是否成功,每隔一段时间查询一次订单共查询10次
int queryTimes = 10;//查询次数计数器
while(queryTimes-- > 0)
{
int succResult = 0;//查询结果
WxPayData queryResult = Query(out_trade_no, out succResult);
//如果需要继续查询则等待2s后继续
if(succResult == 2)
{
Thread.Sleep(2000);
continue;
}
//查询成功,返回订单查询接口返回的数据
else if(succResult == 1)
{
Log.Debug("MicroPay", "Mircopay success, return order query result : " + queryResult.ToXml());
return queryResult.ToPrintStr();
}
//订单交易失败直接返回刷卡支付接口返回的结果失败原因会在err_code中描述
else
{
Log.Error("MicroPay", "Micropay failure, return micropay result : " + result.ToXml());
return result.ToPrintStr();
}
}
//确认失败,则撤销订单
Log.Error("MicroPay", "Micropay failure, Reverse order is processing...");
if(!Cancel(out_trade_no))
{
Log.Error("MicroPay", "Reverse order failure");
throw new WxPayException("Reverse order failure");
}
return result.ToPrintStr();
}
/**
*
*
* @param string out_trade_no
* @param int succCode 012
* @return
*/
public static WxPayData Query(string out_trade_no, out int succCode)
{
WxPayData queryOrderInput = new WxPayData();
queryOrderInput.SetValue("out_trade_no",out_trade_no);
WxPayData result = WxPayApi.OrderQuery(queryOrderInput);
if(result.GetValue("return_code").ToString() == "SUCCESS"
&& result.GetValue("result_code").ToString() == "SUCCESS")
{
//支付成功
if(result.GetValue("trade_state").ToString() == "SUCCESS")
{
succCode = 1;
return result;
}
//用户支付中,需要继续查询
else if(result.GetValue("trade_state").ToString() == "USERPAYING")
{
succCode = 2;
return result;
}
}
//如果返回错误码为“此交易订单号不存在”则直接认定失败
if(result.GetValue("err_code").ToString() == "ORDERNOTEXIST")
{
succCode = 0;
}
else
{
//如果是系统错误,则后续继续
succCode = 2;
}
return result;
}
/**
*
* 10
* @param string out_trade_no
* @param depth
* @return falsetrue
*/
public static bool Cancel(string out_trade_no, int depth = 0)
{
if(depth > 10)
{
return false;
}
WxPayData reverseInput = new WxPayData();
reverseInput.SetValue("out_trade_no",out_trade_no);
WxPayData result = WxPayApi.Reverse(reverseInput);
//接口调用失败
if(result.GetValue("return_code").ToString() != "SUCCESS")
{
return false;
}
//如果结果为success且不需要重新调用撤销则表示撤销成功
if(result.GetValue("result_code").ToString() != "SUCCESS" && result.GetValue("recall").ToString() == "N")
{
return true;
}
else if(result.GetValue("recall").ToString() == "Y")
{
return Cancel(out_trade_no, ++depth);
}
return false;
}
}
}

@ -0,0 +1,499 @@
using HuizhongLibrary.Common.Configuration;
using HuizhongLibrary.Data;
using HuizhongLibrary.Log;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.IO;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WxPayAPI
{
/// <summary>
/// 扫码支付模式一回调处理类
/// 接收微信支付后台发送的扫码结果,调用统一下单接口并将下单结果返回给微信支付后台
/// </summary>
public class NativeNotify:Notify
{
public NativeNotify(Page page):base(page)
{
}
public override void ProcessNotify()
{
WxPayData notifyData = GetNotifyData();
ErrorFollow.TraceWrite("notifyData", "", notifyData.ToPrintStr());
//检查openid和product_id是否返回
//appid=wx0a895a6721484fb0<br>attach=test<br>bank_type=CFT<br>cash_fee=1<br>fee_type=CNY<br>is_subscribe=Y<br>mch_id=1438351202<br>nonce_str=0047c34002ef4ac597939d84984e8e9a<br>openid=o6CUIwKBdgyCy9B1xJMxNK8vdWeU<br>out_trade_no=14383512022018012310014931<br>result_code=SUCCESS<br>return_code=SUCCESS<br>sign=2E4C394C780D0C7BFAF2EDF54A73E927<br>time_end=20180123100323<br>total_fee=1<br>trade_type=JSAPI<br>transaction_id=4200000065201801239112746930<br>
int PayState = 0;
string out_trade_no = "";
if (!notifyData.IsSet("openid")|| !notifyData.IsSet("out_trade_no"))
{
PayState = 1;
WxPayData res = new WxPayData();
res.SetValue("return_code", "FAIL");
res.SetValue("return_msg", "回调数据异常");
ErrorFollow.TraceWrite("ProcessNotify", this.GetType().ToString(), "The data WeChat post is error : " + res.ToXml());
// Log.Info(this.GetType().ToString(), "The data WeChat post is error : " + res.ToXml());
try
{
Update_PayLog(out_trade_no, "The data WeChat post is error : " + res.ToXml(), PayState);
}
catch (Exception ex)
{
ErrorFollow.TraceWrite("ProcessNotify", "错误", ex.Message);
}
page.Response.Write(res.ToXml());
page.Response.End();
}
out_trade_no = notifyData.GetValue("out_trade_no").ToString();
//调统一下单接口,获得下单结果
//string openid = notifyData.GetValue("openid").ToString();
//string product_id = notifyData.GetValue("product_id").ToString();
//WxPayData unifiedOrderResult = new WxPayData();
//try
//{
// unifiedOrderResult = UnifiedOrder(openid, product_id);
//}
//catch(Exception ex)//若在调统一下单接口时抛异常,立即返回结果给微信支付后台
//{
// PayState = 1;
// WxPayData res = new WxPayData();
// res.SetValue("return_code", "FAIL");
// res.SetValue("return_msg", "统一下单失败");
// Log.Error(this.GetType().ToString(), "UnifiedOrder failure : " + res.ToXml());
// page.Response.Write(res.ToXml());
// page.Response.End();
//}
////若下单失败,则立即返回结果给微信支付后台
//if (!notifyData.IsSet("appid") || !notifyData.IsSet("mch_id") || !unifiedOrderResult.IsSet("prepay_id"))
//{
// WxPayData res = new WxPayData();
// res.SetValue("return_code", "FAIL");
// res.SetValue("return_msg", "统一下单失败");
// Log.Error(this.GetType().ToString(), "UnifiedOrder failure : " + res.ToXml());
// page.Response.Write(res.ToXml());
// page.Response.End();
//}
// ErrorFollow.TraceWrite("ProcessNotify", "", notifyData.GetValue("result_code").ToString());
if (notifyData.GetValue("result_code").ToString() == "SUCCESS")
{
// ErrorFollow.TraceWrite("ProcessNotify", "支付成功", PayState.ToString());
PayState = 2;//支付成功
try
{
int AppType = Update_PayLog(out_trade_no, "支付成功" + notifyData.ToPrintStr(), PayState);
if (AppType == 1)
{
SendSync(out_trade_no);
}
else if (AppType == 4)
{
SendZZQPYSync(out_trade_no);
}
else if (AppType == 9)
{
SendYTGPay(out_trade_no);
}
else
{
SendTYSync(out_trade_no);
}
}
catch (Exception ex)
{
ErrorFollow.TraceWrite("ProcessNotify", "错误", ex.Message);
}
}
//统一下单成功,则返回成功结果给微信支付后台
WxPayData data = new WxPayData();
data.SetValue("return_code", "SUCCESS");
data.SetValue("return_msg", "OK");
data.SetValue("appid", WxPayConfig.APPID);
data.SetValue("mch_id", WxPayConfig.MCHID);
data.SetValue("nonce_str", WxPayApi.GenerateNonceStr());
//data.SetValue("prepay_id", notifyData.GetValue("prepay_id"));
data.SetValue("result_code", "SUCCESS");
data.SetValue("err_code_des", "OK");
ErrorFollow.TraceWrite("ProcessNotify0", this.GetType().ToString(), "UnifiedOrder send data: " + data.ToXml());
data.SetValue("sign", data.MakeSign());
ErrorFollow.TraceWrite("ProcessNotify", this.GetType().ToString(), "UnifiedOrder success , send data to WeChat : " + data.ToXml());
//out_trade_no
//Log.Info(this.GetType().ToString(), "UnifiedOrder success , send data to WeChat : " + data.ToXml());
page.Response.Write(data.ToXml());
page.Response.End();
}
private WxPayData UnifiedOrder(string openId,string productId)
{
//统一下单
WxPayData req = new WxPayData();
req.SetValue("body", "test");
req.SetValue("attach", "test");
req.SetValue("out_trade_no", WxPayApi.GenerateOutTradeNo());
req.SetValue("total_fee", 1);
req.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));
req.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss"));
req.SetValue("goods_tag", "test");
req.SetValue("trade_type", "NATIVE");
req.SetValue("openid", openId);
req.SetValue("product_id", productId);
WxPayData result = WxPayApi.UnifiedOrder(req);
return result;
}
private static DataSet GetPayInfo(string out_trade_no)
{
string tsql = @"
select top 1 a.*,b.Url,c.AppCode,e.OutId from ZZQ_Pay a
inner join JC_Company b on a.CompanyId=b.CompanyId
inner join DL_AppConfing c on a.CompanyId=c.CompanyId
inner join JC_UserInfo e on e.UserId=a.UserId
where a.out_trade_no=@out_trade_no";
Database db = DatabaseFactory.CreateDatabase();
DbCommand cmd = db.GetSqlStringCommand(tsql);
db.AddInParameter(cmd, "@out_trade_no", DbType.String, out_trade_no);
return db.ExecuteDataSet(cmd);
}
private static DataSet GetPayInfoTY(string out_trade_no)
{
string tsql = @"
select top 1 a.*,b.Url,c.AppCode from ZZQ_Pay a
inner join JC_Company b on a.CompanyId=b.CompanyId
inner join DL_AppConfing c on a.CompanyId=c.CompanyId
where a.out_trade_no=@out_trade_no";
Database db = DatabaseFactory.CreateDatabase();
DbCommand cmd = db.GetSqlStringCommand(tsql);
db.AddInParameter(cmd, "@out_trade_no", DbType.String, out_trade_no);
return db.ExecuteDataSet(cmd);
}
public static void SendSms(int UserID, string Title, string SmsContent)
{
if (string.IsNullOrEmpty(SmsContent) == true) return;
string tsql = @"
INSERT INTO [T_MESSAGE]([MESSAGEID],[TITLE],[CONTENT],[MOBILELIST],[ANNOUNCETYPE],[OBJECTTYPE],[IFREGULAR],[REGULARTIME],[SENDTIME],[SIGNNAME],[TEACHERID],[MESSAGETYPE],[IFSEND],MsgID,UserName,PassWord)
select '',@Title,@SmsContent,Mobile,'00','00','N',null,getdate(),'','1','04','N','','',''
from JC_UserMobile
where UserID=@UserID and IsUse=1
";
Database db = DatabaseFactory.CreateDatabase();
DbCommand cmd = db.GetSqlStringCommand(tsql);
db.AddInParameter(cmd, "@UserID", DbType.Int32, UserID);
db.AddInParameter(cmd, "@Title", DbType.String, Title);
db.AddInParameter(cmd, "@SmsContent", DbType.String, SmsContent);
db.ExecuteNonQuery(cmd);
}
#region 返回支付结果
public static int Update_PayLog(string out_trade_no, string PayResult, int PayState)
{
// string SetupPath = AppDomain.CurrentDomain.BaseDirectory + "Web.config";
// string PayApp = ConfigurationSourceSection.LoadXml_Attribute(SetupPath, "PayApp");
string tsql = "";
//if (PayApp == "1")
//{
tsql = @"
declare @PayMonth int ,@UserId int,@CompanyId int,@PayApp int,@UserName nvarchar(50),@LastPayState int
set @PayApp=0
select @PayMonth=Num,@UserId=UserId,@CompanyId=CompanyId,@PayApp=AppType,@UserName=UserName,@LastPayState=PayState from ZZQ_Pay
where out_trade_no=@out_trade_no
if (@PayApp = 1) --
begin
if @PayState=2 --
begin
if(@LastPayState!=2 or @LastPayState is NULL)
begin
if (select count(0) from JC_UserWeiXin where UserId=@UserId and UserName=@UserName and VipState=1 and VipEndDate>getdate())>0
Update JC_UserWeiXin set VipState=1,[VipEndDate]=(select DATEADD(MONTH,@PayMonth,VipEndDate)) where UserId=@UserId and CompanyId=@CompanyId and UserName=@UserName
else
Update JC_UserWeiXin set VipState=1,[VipEndDate]=(select DATEADD(MONTH,@PayMonth,GETDATE())) where UserId=@UserId and CompanyId=@CompanyId and UserName=@UserName
end
end
Update ZZQ_Pay set PayState=@PayState,FeeBack=@PayResult,PayDate=getdate() where out_trade_no=@out_trade_no
--Update [BF_Log] set [Remark]=@PayResult,ReturnDate=getdate() where out_trade_no=@out_trade_no
end
else if (@PayApp = 4) --
begin
if @PayState=2 --
begin
if (select count(0) from JC_UserInfo where UserId=@UserId and VipState=1 and VipEndDate>getdate())>0
Update JC_UserInfo set VipState=1,[VipEndDate]=(select DATEADD(MONTH,@PayMonth,VipEndDate)) where UserId=@UserId and CompanyId=@CompanyId
else
Update JC_UserInfo set VipState=1,[VipEndDate]=(select DATEADD(MONTH,@PayMonth,GETDATE())) where UserId=@UserId and CompanyId=@CompanyId
end
Update ZZQ_Pay set PayState=@PayState,FeeBack=@PayResult,PayDate=getdate() where out_trade_no=@out_trade_no
--Update [BF_Log] set [Remark]=@PayResult,ReturnDate=getdate() where out_trade_no=@out_trade_no
end
else if (@PayApp = 2) --
begin
if @PayState=2 --
begin
Update BF_BuyUser set FeeState=2,FeeBack=@PayResult,PayDate=getdate() where out_trade_no=@out_trade_no
end
else --
begin
Update BF_BuyUser set FeeState=@PayState,FeeBack=@PayResult,PayDate=getdate() where out_trade_no=@out_trade_no
end
Update [BF_Log] set [Remark]=@PayResult,ReturnDate=getdate() where out_trade_no=@out_trade_no
end
else if (@PayApp = 3) --
begin
if @PayState=2 --
begin
Update ZZQ_Pay set PayState=2,FeeBack=@PayResult,PayDate=getdate() where out_trade_no=@out_trade_no
end
else --
begin
Update ZZQ_Pay set PayState=@PayState,FeeBack=@PayResult,PayDate=getdate() where out_trade_no=@out_trade_no
end
end
else if (@PayApp = 9) --
begin
if @PayState=2 --
begin
Update ZZQ_Pay set PayState=2,FeeBack=@PayResult,PayDate=getdate() where out_trade_no=@out_trade_no
INSERT INTO [YTG_Order]
(
[paycode]
,[state]
,[paydate],remark
)
VALUES (@out_trade_no,@PayState,getdate(),@PayResult)
end
else --
begin
Update ZZQ_Pay set PayState=@PayState,FeeBack=@PayResult,PayDate=getdate() where out_trade_no=@out_trade_no
INSERT INTO [YTG_Order]
(
[paycode]
,[state]
,[paydate],remark
)
VALUES (@out_trade_no,@PayState,getdate(),@PayResult)
end
end
else
begin
Update ZZQ_Pay set PayState=@PayState,FeeBack=@PayResult,PayDate=getdate() where out_trade_no=@out_trade_no
end
select PayApp=@PayApp
";
// }
// if (PayApp != "1")
// {
// tsql = @"if @PayState=2 --支付成功
//begin
//Update XSBD_StudentInfo set IsPay=@PayState where out_trade_no=@out_trade_no
//end
//else --支付失败
//begin
//Update XSBD_StudentInfo set IsPay=@PayState where out_trade_no=@out_trade_no
//end
//Update [XSBD_PayLog] set [PayResult]=@PayResult,ReturnDate=getdate(),PayState=@PayState where out_trade_no=@out_trade_no
//select 0
//";
// }
// if (PayApp == "8")
// {
// tsql = @"
//if @PayState=2 --支付成功
//begin
//Update ZZQ_Pay set PayState=2,FeeBack=@PayResult,PayDate=getdate() where out_trade_no=@out_trade_no
//update YX_UserPay set State=2,PayDate=getdate() where out_trade_no=@out_trade_no
//declare @PayMonth int ,@UserId int
//select @PayMonth=[Month],@UserId=UserId from YX_UserPay
//where out_trade_no=@out_trade_no
//Update[ZZQ_Student] set
//[VipState]=1 ,
//[VipEndDate]=(select DATEADD(MONTH,@PayMonth,GETDATE()))
//where UserId=@UserId
//end
//else --支付失败
//begin
//Update ZZQ_Pay set PayState=@PayState,FeeBack=@PayResult,PayDate=getdate() where out_trade_no=@out_trade_no
//update YX_UserPay set State=@PayState,PayDate=getdate() where out_trade_no=@out_trade_no
//end
////--[VipEndDate]=(select DATEADD(MONTH,@PayMonth,ISNULL(
////--(select top 1 VipEndDate from ZZQ_Student
////--where VipEndDate>GETDATE() and UserId=@UserId and VipState=1)
////--,GETDATE())))
//select 8
//";
// }
Database db = DatabaseFactory.CreateDatabase();
DbCommand cmd = db.GetSqlStringCommand(tsql);
db.AddInParameter(cmd, "@out_trade_no", DbType.String, out_trade_no);
db.AddInParameter(cmd, "@PayResult", DbType.String, PayResult);
db.AddInParameter(cmd, "@PayState", DbType.Int32, PayState);
//db.ExecuteNonQuery(cmd);
return Convert.ToInt32(db.ExecuteScalar(cmd));
//if (PayApp == "1"||PayApp == "3")
//{
// SendNotice(out_trade_no);
//}
}
#endregion
public static void SendSync(string out_trade_no)
{
try
{
DataTable dtPay = GetPayInfo(out_trade_no).Tables[0];
if (dtPay.Rows.Count > 0)
{
string SetupPath = AppDomain.CurrentDomain.BaseDirectory + "Web.config";
//string Mess = HuizhongLibrary.Common.Configuration.ConfigurationSourceSection.LoadXml_Attribute(SetupPath, "PayMess");
//SendSms(Convert.ToInt32(dtPay.Rows[0]["UserId"]), "支付成功通知", Mess);
string _url = dtPay.Rows[0]["Url"] + "/OuterService/GetInfo.ashx?Ver=1.0&UserCode=" + dtPay.Rows[0]["AppCode"] + "&Method=UpdatePay&UserId=" + dtPay.Rows[0]["OutId"] + "&PayNum=" + dtPay.Rows[0]["Num"] + "&PayMoney=" + dtPay.Rows[0]["PayMoney"] + "&UserName=" + dtPay.Rows[0]["UserName"];
//var request = (HttpWebRequest)WebRequest.Create(_url);
//request.Method = "GET";
//request.ContentType = "text/html;charset=UTF-8";
//HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//Stream myResponseStream = response.GetResponseStream();
//StreamReader myStreamReader = new StreamReader(myResponseStream, System.Text.Encoding.UTF8);
//string retString = myStreamReader.ReadToEnd();
//System.Web.Script.Serialization.JavaScriptSerializer json = new System.Web.Script.Serialization.JavaScriptSerializer();
string error = "";
string str2 = HuizhongLibrary.CustomIO.HttpRequest(_url, "Get", "text/html;charset=UTF-8", null, null, null, out error);
//RuBianInfo model = json.Deserialize<RuBianInfo>(retString);
//return model;
}
}
catch (Exception ex)
{
ErrorFollow.TraceWrite("SendSync", out_trade_no, ex.Message);
}
}
public static void SendTYSync(string out_trade_no)
{
try
{
DataTable dtPay = GetPayInfoTY(out_trade_no).Tables[0];
if (dtPay.Rows.Count > 0)
{
string SetupPath = AppDomain.CurrentDomain.BaseDirectory + "Web.config";
//string Mess = HuizhongLibrary.Common.Configuration.ConfigurationSourceSection.LoadXml_Attribute(SetupPath, "PayMess");
//SendSms(Convert.ToInt32(dtPay.Rows[0]["UserId"]), "支付成功通知", Mess);
string _url = dtPay.Rows[0]["Url"] + "/OuterService/GetInfo.ashx?Ver=1.0&UserCode=" + dtPay.Rows[0]["AppCode"] + "&Method=UpdateTYPay&out_trade_no=" + dtPay.Rows[0]["out_trade_no"] + "&AppType=" + dtPay.Rows[0]["AppType"] + "&PayType=" + dtPay.Rows[0]["PayType"] + "&Amount=" + dtPay.Rows[0]["PayMoney"];
ErrorFollow.TraceWrite("SendTYSync", out_trade_no, _url);
var request = (HttpWebRequest)WebRequest.Create(_url);
request.Method = "GET";
request.ContentType = "text/html;charset=UTF-8";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, System.Text.Encoding.UTF8);
string retString = myStreamReader.ReadToEnd();
System.Web.Script.Serialization.JavaScriptSerializer json = new System.Web.Script.Serialization.JavaScriptSerializer();
//RuBianInfo model = json.Deserialize<RuBianInfo>(retString);
//return model;
}
}
catch (Exception ex)
{
ErrorFollow.TraceWrite("SendTYSync", out_trade_no, ex.Message);
}
}
public static void SendZZQPYSync(string out_trade_no)
{
try
{
DataTable dtPay = GetPayInfo(out_trade_no).Tables[0];
if (dtPay.Rows.Count > 0)
{
string SetupPath = AppDomain.CurrentDomain.BaseDirectory + "Web.config";
string Mess = HuizhongLibrary.Common.Configuration.ConfigurationSourceSection.LoadXml_Attribute(SetupPath, "PayMess");
SendSms(Convert.ToInt32(dtPay.Rows[0]["UserId"]), "支付成功通知", Mess);
string _url = dtPay.Rows[0]["Url"] + "/OuterService/GetInfo.ashx?Ver=1.0&UserCode=" + dtPay.Rows[0]["AppCode"] + "&Method=UpdatePay&UserId=" + dtPay.Rows[0]["OutId"] + "&PayNum=" + dtPay.Rows[0]["Num"] + "&PayMoney=" + dtPay.Rows[0]["PayMoney"];
var request = (HttpWebRequest)WebRequest.Create(_url);
request.Method = "GET";
request.ContentType = "text/html;charset=UTF-8";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, System.Text.Encoding.UTF8);
string retString = myStreamReader.ReadToEnd();
System.Web.Script.Serialization.JavaScriptSerializer json = new System.Web.Script.Serialization.JavaScriptSerializer();
//RuBianInfo model = json.Deserialize<RuBianInfo>(retString);
//return model;
}
}
catch (Exception ex)
{
ErrorFollow.TraceWrite("SendZZQPYSync", out_trade_no, ex.Message);
}
}
public static void SendYTGPay(string out_trade_no)
{
try
{
string SetupPath = AppDomain.CurrentDomain.BaseDirectory + "Web.config";
string _url ="http://book.huizsoft.com/OuterService/GetInfo.ashx?Ver=1.0&UserCode=test&Method=UpdateYTGPay&PayCode=" + out_trade_no;
var request = (HttpWebRequest)WebRequest.Create(_url);
request.Method = "GET";
request.ContentType = "text/html;charset=UTF-8";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, System.Text.Encoding.UTF8);
string retString = myStreamReader.ReadToEnd();
}
catch (Exception ex)
{
ErrorFollow.TraceWrite("SendYTGPay", out_trade_no, ex.Message);
}
}
}
}

@ -0,0 +1,75 @@
using System;
using System.Collections.Generic;
using System.Web;
namespace WxPayAPI
{
public class NativePay
{
/**
* URL
* @param productId ID
* @return URL
*/
public string GetPrePayUrl(string productId)
{
Log.Info(this.GetType().ToString(), "Native pay mode 1 url is producing...");
WxPayData data = new WxPayData();
data.SetValue("appid", WxPayConfig.APPID);//公众帐号id
data.SetValue("mch_id", WxPayConfig.MCHID);//商户号
data.SetValue("time_stamp", WxPayApi.GenerateTimeStamp());//时间戳
data.SetValue("nonce_str", WxPayApi.GenerateNonceStr());//随机字符串
data.SetValue("product_id", productId);//商品ID
data.SetValue("sign", data.MakeSign());//签名
string str = ToUrlParams(data.GetValues());//转换为URL串
string url = "weixin://wxpay/bizpayurl?" + str;
Log.Info(this.GetType().ToString(), "Get native pay mode 1 url : " + url);
return url;
}
/**
* urlurl2,
* @param productId ID
* @return URL
*/
public string GetPayUrl(string productId)
{
Log.Info(this.GetType().ToString(), "Native pay mode 2 url is producing...");
WxPayData data = new WxPayData();
data.SetValue("body", "test");//商品描述
data.SetValue("attach", "test");//附加数据
data.SetValue("out_trade_no", WxPayApi.GenerateOutTradeNo());//随机字符串
data.SetValue("total_fee", 1);//总金额
data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));//交易起始时间
data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss"));//交易结束时间
data.SetValue("goods_tag", "jjj");//商品标记
data.SetValue("trade_type", "NATIVE");//交易类型
data.SetValue("product_id", productId);//商品ID
WxPayData result = WxPayApi.UnifiedOrder(data);//调用统一下单接口
string url = result.GetValue("code_url").ToString();//获得统一下单接口返回的二维码链接
Log.Info(this.GetType().ToString(), "Get native pay mode 2 url : " + url);
return url;
}
/**
* url
* @param map
* @return URL
*/
private string ToUrlParams(SortedDictionary<string, object> map)
{
string buff = "";
foreach (KeyValuePair<string, object> pair in map)
{
buff += pair.Key + "=" + pair.Value + "&";
}
buff = buff.Trim('&');
return buff;
}
}
}

@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Web;
namespace WxPayAPI
{
public class OrderQuery
{
/***
*
* @param transaction_id 使
* @param out_trade_no
* @return xml
*/
public static string Run(string transaction_id, string out_trade_no)
{
Log.Info("OrderQuery", "OrderQuery is processing...");
WxPayData data = new WxPayData();
if(!string.IsNullOrEmpty(transaction_id))//如果微信订单号存在,则以微信订单号为准
{
data.SetValue("transaction_id", transaction_id);
}
else//微信订单号不存在,才根据商户订单号去查单
{
data.SetValue("out_trade_no", out_trade_no);
}
WxPayData result = WxPayApi.OrderQuery(data);//提交订单查询请求给API接收返回数据
Log.Info("OrderQuery", "OrderQuery process complete, result : " + result.ToXml());
return result.ToPrintStr();
}
}
}

@ -0,0 +1,42 @@
using System;
using System.Collections.Generic;
using System.Web;
namespace WxPayAPI
{
public class Refund
{
/***
* 退
* @param transaction_id 使
* @param out_trade_no
* @param total_fee
* @param refund_fee 退
* @return 退xml
*/
public static string Run(string transaction_id, string out_trade_no, string total_fee, string refund_fee)
{
Log.Info("Refund", "Refund is processing...");
WxPayData data = new WxPayData();
if (!string.IsNullOrEmpty(transaction_id))//微信订单号存在的条件下,则已微信订单号为准
{
data.SetValue("transaction_id", transaction_id);
}
else//微信订单号不存在,才根据商户订单号去退款
{
data.SetValue("out_trade_no", out_trade_no);
}
data.SetValue("total_fee", int.Parse(total_fee));//订单总金额
data.SetValue("refund_fee", int.Parse(refund_fee));//退款金额
data.SetValue("out_refund_no", WxPayApi.GenerateOutTradeNo());//随机生成商户退款单号
data.SetValue("op_user_id", WxPayConfig.MCHID);//操作员,默认为商户号
WxPayData result = WxPayApi.Refund(data);//提交退款申请给API接收返回数据
Log.Info("Refund", "Refund process complete, result : " + result.ToXml());
return result.ToPrintStr();
}
}
}

@ -0,0 +1,45 @@
using System;
using System.Collections.Generic;
using System.Web;
namespace WxPayAPI
{
public class RefundQuery
{
/***
* 退
* @param refund_id 退使
* @param out_refund_no 退
* @param transaction_id
* @param out_trade_no
* @return 退xml
*/
public static string Run(string refund_id, string out_refund_no, string transaction_id, string out_trade_no)
{
Log.Info("RefundQuery", "RefundQuery is processing...");
WxPayData data = new WxPayData();
if(!string.IsNullOrEmpty(refund_id))
{
data.SetValue("refund_id", refund_id);//微信退款单号,优先级最高
}
else if(!string.IsNullOrEmpty(out_refund_no))
{
data.SetValue("out_refund_no", out_refund_no);//商户退款单号,优先级第二
}
else if(!string.IsNullOrEmpty(transaction_id))
{
data.SetValue("transaction_id", transaction_id);//微信订单号,优先级第三
}
else
{
data.SetValue("out_trade_no", out_trade_no);//商户订单号,优先级最低
}
WxPayData result = WxPayApi.RefundQuery(data);//提交退款查询给API接收返回数据
Log.Info("RefundQuery", "RefundQuery process complete, result : " + result.ToXml());
return result.ToPrintStr();
}
}
}

@ -0,0 +1,77 @@
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WxPayAPI
{
/// <summary>
/// 支付结果通知回调处理类
/// 负责接收微信支付后台发送的支付结果并对订单有效性进行验证,将验证结果反馈给微信支付后台
/// </summary>
public class ResultNotify:Notify
{
public ResultNotify(Page page):base(page)
{
}
public override void ProcessNotify()
{
WxPayData notifyData = GetNotifyData();
//检查支付结果中transaction_id是否存在
if (!notifyData.IsSet("transaction_id"))
{
//若transaction_id不存在则立即返回结果给微信支付后台
WxPayData res = new WxPayData();
res.SetValue("return_code", "FAIL");
res.SetValue("return_msg", "支付结果中微信订单号不存在");
Log.Error(this.GetType().ToString(), "The Pay result is error : " + res.ToXml());
page.Response.Write(res.ToXml());
page.Response.End();
}
string transaction_id = notifyData.GetValue("transaction_id").ToString();
//查询订单,判断订单真实性
if (!QueryOrder(transaction_id))
{
//若订单查询失败,则立即返回结果给微信支付后台
WxPayData res = new WxPayData();
res.SetValue("return_code", "FAIL");
res.SetValue("return_msg", "订单查询失败");
Log.Error(this.GetType().ToString(), "Order query failure : " + res.ToXml());
page.Response.Write(res.ToXml());
page.Response.End();
}
//查询订单成功
else
{
WxPayData res = new WxPayData();
res.SetValue("return_code", "SUCCESS");
res.SetValue("return_msg", "OK");
Log.Info(this.GetType().ToString(), "order query success : " + res.ToXml());
page.Response.Write(res.ToXml());
page.Response.End();
}
}
//查询订单
private bool QueryOrder(string transaction_id)
{
WxPayData req = new WxPayData();
req.SetValue("transaction_id", transaction_id);
WxPayData res = WxPayApi.OrderQuery(req);
if (res.GetValue("return_code").ToString() == "SUCCESS" &&
res.GetValue("result_code").ToString() == "SUCCESS")
{
return true;
}
else
{
return false;
}
}
}
}

@ -0,0 +1,62 @@
using HuizhongLibrary.Common.Configuration;
using System;
using System.Collections.Generic;
using System.Web;
namespace WxPayAPI
{
/**
*
*/
public class WxPayConfig
{
//=======【基本信息设置】=====================================
/*
* APPIDAPPID
* MCHID
* KEY
* APPSECRETsecertJSAPI
*/
public static string SetupPath = AppDomain.CurrentDomain.BaseDirectory + "Web.config";
public static string APPID = ConfigurationSourceSection.LoadXml_Attribute(SetupPath, "appId2");// "wx0a895a6721484fb0";// "wx36c993c30d3b6f0b";//"wxdf1f17164598d212";////"wx2428e34e0e7dc6ef";
public static string MCHID = ConfigurationSourceSection.LoadXml_Attribute(SetupPath, "MCHID");// "1438351202";//"10021220";// "1233410002";
public static string KEY = ConfigurationSourceSection.LoadXml_Attribute(SetupPath, "KEY");//"G6g1D7EcO5nphIfdxPVRwugxSZmEj7hF";// "cnHR45zLWk6GDs7UBo1FmcKJKvGx7tVC";//"e10adc3849ba56abbe56e056f20f883e";
public static string APPSECRET = ConfigurationSourceSection.LoadXml_Attribute(SetupPath, "appSecret2");//"meishimeikejiaoyukeji57487345027";//"f3e4a23c29d2652f967b1a845869735f";// "ef393a0a66954f84c04875360c46b3e0";// "51c56b886b5be869567dd389b3e5d1d6";
//=======【证书路径设置】=====================================
/* ,退
*/
public static string SSLCERT_PATH = ConfigurationSourceSection.LoadXml_Attribute(SetupPath, "SSLCERT_PATH");//"cert/apiclient_cert.p12";
public static string SSLCERT_PASSWORD = ConfigurationSourceSection.LoadXml_Attribute(SetupPath, "SSLCERT_PASSWORD"); //"1438351202";//"10021220";//"1233410002";
//=======【支付结果通知url】=====================================
/* url
*/
public static string NOTIFY_URL = ConfigurationSourceSection.LoadXml_Attribute(SetupPath, "NOTIFY_URL");// "http://szxy.edu-oto.com/Phone/ResultNotifyPage.aspx";
//=======【商户系统后台机器IP】=====================================
/*
*/
public const string IP = "";//"8.8.8.8";
//=======【代理服务器设置】===================================
/* IP0.0.0.00
*/
public const string PROXY_URL = "";
//=======【上报信息配置】===================================
/* 0.; 1.; 2.
*/
public const int REPORT_LEVENL = 1;
//=======【日志级别】===================================
/* 0.1.; 2.; 3.
*/
public const int LOG_LEVENL = 0;
}
}

@ -0,0 +1,267 @@
using System;
using System.Collections.Generic;
using System.Web;
using System.Xml;
using System.Security.Cryptography;
using System.Text;
using LitJson;
namespace WxPayAPI
{
/// <summary>
/// 微信支付协议接口数据类所有的API接口通信都依赖这个数据结构
/// 在调用接口之前先填充各个字段的值,然后进行接口通信,
/// 这样设计的好处是可扩展性强,用户可随意对协议进行更改而不用重新设计数据结构,
/// 还可以随意组合出不同的协议数据包,不用为每个协议设计一个数据包结构
/// </summary>
public class WxPayData
{
public WxPayData()
{
}
//采用排序的Dictionary的好处是方便对数据包进行签名不用再签名之前再做一次排序
private SortedDictionary<string, object> m_values = new SortedDictionary<string, object>();
/**
*
* @param key
* @param value
*/
public void SetValue(string key, object value)
{
m_values[key] = value;
}
/**
*
* @param key
* @return key
*/
public object GetValue(string key)
{
object o = null;
m_values.TryGetValue(key, out o);
return o;
}
/**
*
* @param key
* @return keytruefalse
*/
public bool IsSet(string key)
{
object o = null;
m_values.TryGetValue(key, out o);
if (null != o)
return true;
else
return false;
}
/**
* @Dictionaryxml
* @return xml
* @throws WxPayException
**/
public string ToXml()
{
//数据为空时不能转化为xml格式
if (0 == m_values.Count)
{
Log.Error(this.GetType().ToString(), "WxPayData数据为空!");
throw new WxPayException("WxPayData数据为空!");
}
string xml = "<xml>";
foreach (KeyValuePair<string, object> pair in m_values)
{
//字段值不能为null会影响后续流程
if (pair.Value == null)
{
Log.Error(this.GetType().ToString(), "WxPayData内部含有值为null的字段!");
throw new WxPayException("WxPayData内部含有值为null的字段!");
}
if (pair.Value.GetType() == typeof(int))
{
xml += "<" + pair.Key + ">" + pair.Value + "</" + pair.Key + ">";
}
else if (pair.Value.GetType() == typeof(string))
{
xml += "<" + pair.Key + ">" + "<![CDATA[" + pair.Value + "]]></" + pair.Key + ">";
}
else//除了string和int类型不能含有其他数据类型
{
Log.Error(this.GetType().ToString(), "WxPayData字段数据类型错误!");
throw new WxPayException("WxPayData字段数据类型错误!");
}
}
xml += "</xml>";
return xml;
}
/**
* @xmlWxPayData
* @param string xml
* @return Dictionary
* @throws WxPayException
*/
public SortedDictionary<string, object> FromXml(string xml)
{
if (string.IsNullOrEmpty(xml))
{
Log.Error(this.GetType().ToString(), "将空的xml串转换为WxPayData不合法!");
throw new WxPayException("将空的xml串转换为WxPayData不合法!");
}
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
XmlNode xmlNode = xmlDoc.FirstChild;//获取到根节点<xml>
XmlNodeList nodes = xmlNode.ChildNodes;
foreach (XmlNode xn in nodes)
{
XmlElement xe = (XmlElement)xn;
m_values[xe.Name] = xe.InnerText;//获取xml的键值对到WxPayData内部的数据中
}
try
{
//2015-06-29 错误是没有签名
if(m_values["return_code"] != "SUCCESS")
{
return m_values;
}
CheckSign();//验证签名,不通过会抛异常
}
catch(WxPayException ex)
{
throw new WxPayException(ex.Message);
}
return m_values;
}
/**
* @Dictionaryurl
* @ return url, sign
*/
public string ToUrl()
{
string buff = "";
foreach (KeyValuePair<string, object> pair in m_values)
{
if (pair.Value == null)
{
Log.Error(this.GetType().ToString(), "WxPayData内部含有值为null的字段!");
throw new WxPayException("WxPayData内部含有值为null的字段!");
}
if (pair.Key != "sign" && Convert.ToString(pair.Value) != "")
{
buff += pair.Key + "=" + pair.Value + "&";
}
}
buff = buff.Trim('&');
return buff;
}
/**
* @DictionaryJson
* @return json
*/
public string ToJson()
{
string jsonStr = JsonMapper.ToJson(m_values);
return jsonStr;
}
/**
* @valuesWebwebxml
*/
public string ToPrintStr()
{
string str = "";
foreach (KeyValuePair<string, object> pair in m_values)
{
if (pair.Value == null)
{
Log.Error(this.GetType().ToString(), "WxPayData内部含有值为null的字段!");
throw new WxPayException("WxPayData内部含有值为null的字段!");
}
str += string.Format("{0}={1}<br>", pair.Key, pair.Value.ToString());
}
Log.Debug(this.GetType().ToString(), "Print in Web Page : " + str);
return str;
}
/**
* @
* @return , sign
*/
public string MakeSign()
{
//转url格式
string str = ToUrl();
//在string后加入API KEY
str += "&key=" + WxPayConfig.KEY;
//MD5加密
var md5 = MD5.Create();
var bs = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
var sb = new StringBuilder();
foreach (byte b in bs)
{
sb.Append(b.ToString("x2"));
}
//所有字符转为大写
return sb.ToString().ToUpper();
}
/**
*
*
* true
*/
public bool CheckSign()
{
//如果没有设置签名,则跳过检测
if (!IsSet("sign"))
{
Log.Error(this.GetType().ToString(), "WxPayData签名存在但不合法!");
throw new WxPayException("WxPayData签名存在但不合法!");
}
//如果设置了签名但是签名为空,则抛异常
else if(GetValue("sign") == null || GetValue("sign").ToString() == "")
{
Log.Error(this.GetType().ToString(), "WxPayData签名存在但不合法!");
throw new WxPayException("WxPayData签名存在但不合法!");
}
//获取接收到的签名
string return_sign = GetValue("sign").ToString();
//在本地计算新的签名
string cal_sign = MakeSign();
if (cal_sign == return_sign)
{
return true;
}
Log.Error(this.GetType().ToString(), "WxPayData签名验证错误!");
throw new WxPayException("WxPayData签名验证错误!");
}
/**
* @Dictionary
*/
public SortedDictionary<string, object> GetValues()
{
return m_values;
}
}
}

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Web;
namespace WxPayAPI
{
public class WxPayException : Exception
{
public WxPayException(string msg) : base(msg)
{
}
}
}

@ -0,0 +1,203 @@
using System;
using System.Collections.Generic;
using System.Web;
using System.Net;
using System.IO;
using System.Text;
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
namespace WxPayAPI
{
/// <summary>
/// http连接基础类负责底层的http通信
/// </summary>
public class HttpService
{
public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
//直接确认,否则打不开
return true;
}
public static string Post(string xml, string url, bool isUseCert, int timeout)
{
System.GC.Collect();//垃圾回收回收没有正常关闭的http连接
string result = "";//返回结果
HttpWebRequest request = null;
HttpWebResponse response = null;
Stream reqStream = null;
try
{
//设置最大连接数
ServicePointManager.DefaultConnectionLimit = 200;
//设置https验证方式
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback =
new RemoteCertificateValidationCallback(CheckValidationResult);
}
/***************************************************************
* HttpWebRequest
* ************************************************************/
request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.Timeout = timeout * 1000;
//设置代理服务器
//WebProxy proxy = new WebProxy(); //定义一个网关对象
//proxy.Address = new Uri(WxPayConfig.PROXY_URL); //网关服务器端口:端口
//request.Proxy = proxy;
//设置POST的数据类型和长度
request.ContentType = "text/xml";
byte[] data = System.Text.Encoding.UTF8.GetBytes(xml);
request.ContentLength = data.Length;
//是否使用证书
if (isUseCert)
{
string path = HttpContext.Current.Request.PhysicalApplicationPath;
X509Certificate2 cert = new X509Certificate2(path + WxPayConfig.SSLCERT_PATH, WxPayConfig.SSLCERT_PASSWORD);
request.ClientCertificates.Add(cert);
Log.Debug("WxPayApi", "PostXml used cert");
}
//往服务器写入数据
reqStream = request.GetRequestStream();
reqStream.Write(data, 0, data.Length);
reqStream.Close();
//获取服务端返回
response = (HttpWebResponse)request.GetResponse();
//获取服务端返回数据
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
result = sr.ReadToEnd().Trim();
sr.Close();
}
catch (System.Threading.ThreadAbortException e)
{
Log.Error("HttpService", "Thread - caught ThreadAbortException - resetting.");
Log.Error("Exception message: {0}", e.Message);
System.Threading.Thread.ResetAbort();
}
catch (WebException e)
{
Log.Error("HttpService", e.ToString());
if (e.Status == WebExceptionStatus.ProtocolError)
{
Log.Error("HttpService", "StatusCode : " + ((HttpWebResponse)e.Response).StatusCode);
Log.Error("HttpService", "StatusDescription : " + ((HttpWebResponse)e.Response).StatusDescription);
}
throw new WxPayException(e.ToString());
}
catch (Exception e)
{
Log.Error("HttpService", e.ToString());
throw new WxPayException(e.ToString());
}
finally
{
//关闭连接和流
if (response != null)
{
response.Close();
}
if(request != null)
{
request.Abort();
}
}
return result;
}
/// <summary>
/// 处理http GET请求返回数据
/// </summary>
/// <param name="url">请求的url地址</param>
/// <returns>http GET成功后返回的数据失败抛WebException异常</returns>
public static string Get(string url)
{
System.GC.Collect();
string result = "";
HttpWebRequest request = null;
HttpWebResponse response = null;
//请求url以获取数据
try
{
//设置最大连接数
ServicePointManager.DefaultConnectionLimit = 200;
//设置https验证方式
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback =
new RemoteCertificateValidationCallback(CheckValidationResult);
}
/***************************************************************
* HttpWebRequest
* ************************************************************/
request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
//设置代理
//WebProxy proxy = new WebProxy();
//proxy.Address = new Uri(WxPayConfig.PROXY_URL);
//request.Proxy = proxy;
//获取服务器返回
response = (HttpWebResponse)request.GetResponse();
//获取HTTP返回数据
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
result = sr.ReadToEnd().Trim();
sr.Close();
}
catch (System.Threading.ThreadAbortException e)
{
Log.Error("HttpService","Thread - caught ThreadAbortException - resetting.");
Log.Error("Exception message: {0}", e.Message);
System.Threading.Thread.ResetAbort();
}
catch (WebException e)
{
Log.Error("HttpService", e.ToString());
if (e.Status == WebExceptionStatus.ProtocolError)
{
Log.Error("HttpService", "StatusCode : " + ((HttpWebResponse)e.Response).StatusCode);
Log.Error("HttpService", "StatusDescription : " + ((HttpWebResponse)e.Response).StatusDescription);
}
throw new WxPayException(e.ToString());
}
catch (Exception e)
{
Log.Error("HttpService", e.ToString());
throw new WxPayException(e.ToString());
}
finally
{
//关闭连接和流
if (response != null)
{
response.Close();
}
if (request != null)
{
request.Abort();
}
}
return result;
}
}
}

@ -0,0 +1,79 @@
using System;
using System.Collections.Generic;
using System.Web;
using System.IO;
namespace WxPayAPI
{
public class Log
{
//在网站根目录下创建日志目录
public static string path = HttpContext.Current.Request.PhysicalApplicationPath + "logs";
/**
*
* @param className
* @param content
*/
public static void Debug(string className, string content)
{
if(WxPayConfig.LOG_LEVENL >= 3)
{
WriteLog("DEBUG", className, content);
}
}
/**
*
* @param className
* @param content
*/
public static void Info(string className, string content)
{
if (WxPayConfig.LOG_LEVENL >= 2)
{
WriteLog("INFO", className, content);
}
}
/**
*
* @param className
* @param content
*/
public static void Error(string className, string content)
{
if(WxPayConfig.LOG_LEVENL >= 1)
{
WriteLog("ERROR", className, content);
}
}
/**
*
* @param type
* @param className
* @param content
*/
protected static void WriteLog(string type, string className, string content)
{
if(!Directory.Exists(path))//如果日志目录不存在就创建
{
Directory.CreateDirectory(path);
}
string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");//获取当前系统时间
string filename = path + "/" + DateTime.Now.ToString("yyyy-MM-dd") + ".log";//用日期对日志文件命名
//创建或打开日志文件,向日志文件末尾追加记录
StreamWriter mySw = File.AppendText(filename);
//向日志文件写入内容
string write_content = time + " " + type + " " + className + ": " + content;
mySw.WriteLine(write_content);
//关闭日志文件
mySw.Close();
}
}
}

@ -0,0 +1,71 @@
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
namespace WxPayAPI
{
/// <summary>
/// 回调处理基类
/// 主要负责接收微信支付后台发送过来的数据,对数据进行签名验证
/// 子类在此类基础上进行派生并重写自己的回调处理过程
/// </summary>
public class Notify
{
public Page page {get;set;}
public Notify(Page page)
{
this.page = page;
}
/// <summary>
/// 接收从微信支付后台发送过来的数据并验证签名
/// </summary>
/// <returns>微信支付后台返回的数据</returns>
public WxPayData GetNotifyData()
{
//接收从微信后台POST过来的数据
System.IO.Stream s = page.Request.InputStream;
int count = 0;
byte[] buffer = new byte[1024];
StringBuilder builder = new StringBuilder();
while ((count = s.Read(buffer, 0, 1024)) > 0)
{
builder.Append(Encoding.UTF8.GetString(buffer, 0, count));
}
s.Flush();
s.Close();
s.Dispose();
Log.Info(this.GetType().ToString(), "Receive data from WeChat : " + builder.ToString());
//转换数据格式并验证签名
WxPayData data = new WxPayData();
try
{
data.FromXml(builder.ToString());
}
catch(WxPayException ex)
{
//若签名错误,则立即返回结果给微信支付后台
WxPayData res = new WxPayData();
res.SetValue("return_code", "FAIL");
res.SetValue("return_msg", ex.Message);
Log.Error(this.GetType().ToString(), "Sign check error : " + res.ToXml());
page.Response.Write(res.ToXml());
page.Response.End();
}
Log.Info(this.GetType().ToString(), "Check sign success");
return data;
}
//派生类需要重写这个方法,进行不同的回调处理
public virtual void ProcessNotify()
{
}
}
}

@ -0,0 +1,614 @@
using System;
using System.Collections.Generic;
using System.Web;
using System.Net;
using System.IO;
using System.Text;
using HuizhongLibrary.Log;
namespace WxPayAPI
{
public class WxPayApi
{
/**
* API
* 使
*
* @param WxPayData inputObj API
* @param int timeOut
* @throws WxPayException
* @return
*/
public static WxPayData Micropay(WxPayData inputObj, int timeOut = 10)
{
string url = "https://api.mch.weixin.qq.com/pay/micropay";
//检测必填参数
if (!inputObj.IsSet("body"))
{
throw new WxPayException("提交被扫支付API接口中缺少必填参数body");
}
else if (!inputObj.IsSet("out_trade_no"))
{
throw new WxPayException("提交被扫支付API接口中缺少必填参数out_trade_no");
}
else if (!inputObj.IsSet("total_fee"))
{
throw new WxPayException("提交被扫支付API接口中缺少必填参数total_fee");
}
else if (!inputObj.IsSet("auth_code"))
{
throw new WxPayException("提交被扫支付API接口中缺少必填参数auth_code");
}
inputObj.SetValue("spbill_create_ip", WxPayConfig.IP);//终端ip
inputObj.SetValue("appid", WxPayConfig.APPID);//公众账号ID
inputObj.SetValue("mch_id", WxPayConfig.MCHID);//商户号
inputObj.SetValue("nonce_str", Guid.NewGuid().ToString().Replace("-", ""));//随机字符串
inputObj.SetValue("sign", inputObj.MakeSign());//签名
string xml = inputObj.ToXml();
var start = DateTime.Now;//请求开始时间
Log.Debug("WxPayApi", "MicroPay request : " + xml);
string response = HttpService.Post(xml, url, false, timeOut);//调用HTTP通信接口以提交数据到API
Log.Debug("WxPayApi", "MicroPay response : " + response);
var end = DateTime.Now;
int timeCost = (int)((end - start).TotalMilliseconds);//获得接口耗时
//将xml格式的结果转换为对象以返回
WxPayData result = new WxPayData();
result.FromXml(response);
ReportCostTime(url, timeCost, result);//测速上报
return result;
}
/**
*
*
* @param WxPayData inputObj API
* @param int timeOut
* @throws WxPayException
* @return
*/
public static WxPayData OrderQuery(WxPayData inputObj, int timeOut = 6)
{
string url = "https://api.mch.weixin.qq.com/pay/orderquery";
//检测必填参数
if (!inputObj.IsSet("out_trade_no") && !inputObj.IsSet("transaction_id"))
{
throw new WxPayException("订单查询接口中out_trade_no、transaction_id至少填一个");
}
inputObj.SetValue("appid", WxPayConfig.APPID);//公众账号ID
inputObj.SetValue("mch_id", WxPayConfig.MCHID);//商户号
inputObj.SetValue("nonce_str", WxPayApi.GenerateNonceStr());//随机字符串
inputObj.SetValue("sign", inputObj.MakeSign());//签名
string xml = inputObj.ToXml();
var start = DateTime.Now;
Log.Debug("WxPayApi", "OrderQuery request : " + xml);
string response = HttpService.Post(xml, url, false, timeOut);//调用HTTP通信接口提交数据
Log.Debug("WxPayApi", "OrderQuery response : " + response);
var end = DateTime.Now;
int timeCost = (int)((end - start).TotalMilliseconds);//获得接口耗时
//将xml格式的数据转化为对象以返回
WxPayData result = new WxPayData();
result.FromXml(response);
ReportCostTime(url, timeCost, result);//测速上报
return result;
}
/**
*
* API
* @param WxPayData inputObj APIout_trade_notransaction_id
* @param int timeOut
* @throws WxPayException
* @return API
*/
public static WxPayData Reverse(WxPayData inputObj, int timeOut = 6)
{
string url = "https://api.mch.weixin.qq.com/secapi/pay/reverse";
//检测必填参数
if (!inputObj.IsSet("out_trade_no") && !inputObj.IsSet("transaction_id"))
{
throw new WxPayException("撤销订单API接口中参数out_trade_no和transaction_id必须填写一个");
}
inputObj.SetValue("appid", WxPayConfig.APPID);//公众账号ID
inputObj.SetValue("mch_id", WxPayConfig.MCHID);//商户号
inputObj.SetValue("nonce_str", GenerateNonceStr());//随机字符串
inputObj.SetValue("sign", inputObj.MakeSign());//签名
string xml = inputObj.ToXml();
var start = DateTime.Now;//请求开始时间
Log.Debug("WxPayApi", "Reverse request : " + xml);
string response = HttpService.Post(xml, url, true, timeOut);
Log.Debug("WxPayApi", "Reverse response : " + response);
var end = DateTime.Now;
int timeCost = (int)((end - start).TotalMilliseconds);
WxPayData result = new WxPayData();
result.FromXml(response);
ReportCostTime(url, timeCost, result);//测速上报
return result;
}
/**
*
* 退
* @param WxPayData inputObj 退API
* @param int timeOut
* @throws WxPayException
* @return
*/
public static WxPayData Refund(WxPayData inputObj, int timeOut = 6)
{
string url = "https://api.mch.weixin.qq.com/secapi/pay/refund";
//检测必填参数
if (!inputObj.IsSet("out_trade_no") && !inputObj.IsSet("transaction_id"))
{
throw new WxPayException("退款申请接口中out_trade_no、transaction_id至少填一个");
}
else if (!inputObj.IsSet("out_refund_no"))
{
throw new WxPayException("退款申请接口中缺少必填参数out_refund_no");
}
else if (!inputObj.IsSet("total_fee"))
{
throw new WxPayException("退款申请接口中缺少必填参数total_fee");
}
else if (!inputObj.IsSet("refund_fee"))
{
throw new WxPayException("退款申请接口中缺少必填参数refund_fee");
}
else if (!inputObj.IsSet("op_user_id"))
{
throw new WxPayException("退款申请接口中缺少必填参数op_user_id");
}
inputObj.SetValue("appid", WxPayConfig.APPID);//公众账号ID
inputObj.SetValue("mch_id", WxPayConfig.MCHID);//商户号
inputObj.SetValue("nonce_str", Guid.NewGuid().ToString().Replace("-", ""));//随机字符串
inputObj.SetValue("sign", inputObj.MakeSign());//签名
string xml = inputObj.ToXml();
var start = DateTime.Now;
Log.Debug("WxPayApi", "Refund request : " + xml);
string response = HttpService.Post(xml, url, true, timeOut);//调用HTTP通信接口提交数据到API
Log.Debug("WxPayApi", "Refund response : " + response);
var end = DateTime.Now;
int timeCost = (int)((end - start).TotalMilliseconds);//获得接口耗时
//将xml格式的结果转换为对象以返回
WxPayData result = new WxPayData();
result.FromXml(response);
ReportCostTime(url, timeCost, result);//测速上报
return result;
}
/**
*
* 退
* 退退退
* 退20退3退
* out_refund_noout_trade_notransaction_idrefund_id
* @param WxPayData inputObj 退API
* @param int timeOut
* @throws WxPayException
* @return
*/
public static WxPayData RefundQuery(WxPayData inputObj, int timeOut = 6)
{
string url = "https://api.mch.weixin.qq.com/pay/refundquery";
//检测必填参数
if (!inputObj.IsSet("out_refund_no") && !inputObj.IsSet("out_trade_no") &&
!inputObj.IsSet("transaction_id") && !inputObj.IsSet("refund_id"))
{
throw new WxPayException("退款查询接口中out_refund_no、out_trade_no、transaction_id、refund_id四个参数必填一个");
}
inputObj.SetValue("appid", WxPayConfig.APPID);//公众账号ID
inputObj.SetValue("mch_id", WxPayConfig.MCHID);//商户号
inputObj.SetValue("nonce_str", GenerateNonceStr());//随机字符串
inputObj.SetValue("sign", inputObj.MakeSign());//签名
string xml = inputObj.ToXml();
var start = DateTime.Now;//请求开始时间
Log.Debug("WxPayApi", "RefundQuery request : " + xml);
string response = HttpService.Post(xml, url, false, timeOut);//调用HTTP通信接口以提交数据到API
Log.Debug("WxPayApi", "RefundQuery response : " + response);
var end = DateTime.Now;
int timeCost = (int)((end - start).TotalMilliseconds);//获得接口耗时
//将xml格式的结果转换为对象以返回
WxPayData result = new WxPayData();
result.FromXml(response);
ReportCostTime(url, timeCost, result);//测速上报
return result;
}
/**
*
* @param WxPayData inputObj API
* @param int timeOut
* @throws WxPayException
* @return
*/
public static WxPayData DownloadBill(WxPayData inputObj, int timeOut = 6)
{
string url = "https://api.mch.weixin.qq.com/pay/downloadbill";
//检测必填参数
if (!inputObj.IsSet("bill_date"))
{
throw new WxPayException("对账单接口中缺少必填参数bill_date");
}
inputObj.SetValue("appid", WxPayConfig.APPID);//公众账号ID
inputObj.SetValue("mch_id", WxPayConfig.MCHID);//商户号
inputObj.SetValue("nonce_str", GenerateNonceStr());//随机字符串
inputObj.SetValue("sign", inputObj.MakeSign());//签名
string xml = inputObj.ToXml();
Log.Debug("WxPayApi", "DownloadBill request : " + xml);
string response = HttpService.Post(xml, url, false, timeOut);//调用HTTP通信接口以提交数据到API
Log.Debug("WxPayApi", "DownloadBill result : " + response);
WxPayData result = new WxPayData();
//若接口调用失败会返回xml格式的结果
if (response.Substring(0, 5) == "<xml>")
{
result.FromXml(response);
}
//接口调用成功则返回非xml格式的数据
else
result.SetValue("result", response);
return result;
}
/**
*
*
* (weixin://wxpay/s/XXXXXX)
*
* @param WxPayData inputObj API
* @param int timeOut
* @throws WxPayException
* @return
*/
public static WxPayData ShortUrl(WxPayData inputObj, int timeOut = 6)
{
string url = "https://api.mch.weixin.qq.com/tools/shorturl";
//检测必填参数
if (!inputObj.IsSet("long_url"))
{
throw new WxPayException("需要转换的URL签名用原串传输需URL encode");
}
inputObj.SetValue("appid", WxPayConfig.APPID);//公众账号ID
inputObj.SetValue("mch_id", WxPayConfig.MCHID);//商户号
inputObj.SetValue("nonce_str", GenerateNonceStr());//随机字符串
inputObj.SetValue("sign", inputObj.MakeSign());//签名
string xml = inputObj.ToXml();
var start = DateTime.Now;//请求开始时间
Log.Debug("WxPayApi", "ShortUrl request : " + xml);
string response = HttpService.Post(xml, url, false, timeOut);
Log.Debug("WxPayApi", "ShortUrl response : " + response);
var end = DateTime.Now;
int timeCost = (int)((end - start).TotalMilliseconds);
WxPayData result = new WxPayData();
result.FromXml(response);
ReportCostTime(url, timeCost, result);//测速上报
return result;
}
/**
*
*
* @param WxPaydata inputObj API
* @param int timeOut
* @throws WxPayException
* @return
*/
public static WxPayData UnifiedOrder(WxPayData inputObj, int timeOut = 6)
{
string url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
//检测必填参数
if (!inputObj.IsSet("out_trade_no"))
{
throw new WxPayException("缺少统一支付接口必填参数out_trade_no");
}
else if (!inputObj.IsSet("body"))
{
throw new WxPayException("缺少统一支付接口必填参数body");
}
else if (!inputObj.IsSet("total_fee"))
{
throw new WxPayException("缺少统一支付接口必填参数total_fee");
}
else if (!inputObj.IsSet("trade_type"))
{
throw new WxPayException("缺少统一支付接口必填参数trade_type");
}
//关联参数
if (inputObj.GetValue("trade_type").ToString() == "JSAPI" && !inputObj.IsSet("openid"))
{
throw new WxPayException("统一支付接口中缺少必填参数openidtrade_type为JSAPI时openid为必填参数");
}
if (inputObj.GetValue("trade_type").ToString() == "NATIVE" && !inputObj.IsSet("product_id"))
{
throw new WxPayException("统一支付接口中缺少必填参数product_idtrade_type为JSAPI时product_id为必填参数");
}
//异步通知url未设置则使用配置文件中的url
if (!inputObj.IsSet("notify_url"))
{
inputObj.SetValue("notify_url", WxPayConfig.NOTIFY_URL);//异步通知url
}
inputObj.SetValue("appid", WxPayConfig.APPID);//公众账号ID
inputObj.SetValue("mch_id", WxPayConfig.MCHID);//商户号
inputObj.SetValue("spbill_create_ip", HuizhongLibrary.LocalIpAddress.GetIPAddress);//终端ip
inputObj.SetValue("nonce_str", GenerateNonceStr());//随机字符串
//签名
inputObj.SetValue("sign", inputObj.MakeSign());
string xml = inputObj.ToXml();
var start = DateTime.Now;
ErrorFollow.TraceWrite("WxPayApi", "", "UnfiedOrder request : " + xml);
// Log.Debug("WxPayApi", "UnfiedOrder request : " + xml);
string response = HttpService.Post(xml, url, false, timeOut);
// Log.Debug("WxPayApi", "UnfiedOrder response : " + response);
ErrorFollow.TraceWrite("WxPayApi", "", "UnfiedOrder response : " + response);
var end = DateTime.Now;
int timeCost = (int)((end - start).TotalMilliseconds);
WxPayData result = new WxPayData();
result.FromXml(response);
// ReportCostTime(url, timeCost, result);//测速上报
return result;
}
/**
*
*
* @param WxPayData inputObj API
* @param int timeOut
* @throws WxPayException
* @return
*/
public static WxPayData CloseOrder(WxPayData inputObj, int timeOut = 6)
{
string url = "https://api.mch.weixin.qq.com/pay/closeorder";
//检测必填参数
if (!inputObj.IsSet("out_trade_no"))
{
throw new WxPayException("关闭订单接口中out_trade_no必填");
}
inputObj.SetValue("appid", WxPayConfig.APPID);//公众账号ID
inputObj.SetValue("mch_id", WxPayConfig.MCHID);//商户号
inputObj.SetValue("nonce_str", GenerateNonceStr());//随机字符串
inputObj.SetValue("sign", inputObj.MakeSign());//签名
string xml = inputObj.ToXml();
var start = DateTime.Now;//请求开始时间
string response = HttpService.Post(xml, url, false, timeOut);
var end = DateTime.Now;
int timeCost = (int)((end - start).TotalMilliseconds);
WxPayData result = new WxPayData();
result.FromXml(response);
// ReportCostTime(url, timeCost, result);//测速上报
return result;
}
/**
*
*
* @param string interface_url URL
* @param int timeCost
* @param WxPayData inputObj
*/
private static void ReportCostTime(string interface_url, int timeCost, WxPayData inputObj)
{
//如果不需要进行上报
if (WxPayConfig.REPORT_LEVENL == 0)
{
return;
}
//如果仅失败上报
if (WxPayConfig.REPORT_LEVENL == 1 && inputObj.IsSet("return_code") && inputObj.GetValue("return_code").ToString() == "SUCCESS" &&
inputObj.IsSet("result_code") && inputObj.GetValue("result_code").ToString() == "SUCCESS")
{
return;
}
//上报逻辑
WxPayData data = new WxPayData();
data.SetValue("interface_url", interface_url);
data.SetValue("execute_time_", timeCost);
//返回状态码
if (inputObj.IsSet("return_code"))
{
data.SetValue("return_code", inputObj.GetValue("return_code"));
}
//返回信息
if (inputObj.IsSet("return_msg"))
{
data.SetValue("return_msg", inputObj.GetValue("return_msg"));
}
//业务结果
if (inputObj.IsSet("result_code"))
{
data.SetValue("result_code", inputObj.GetValue("result_code"));
}
//错误代码
if (inputObj.IsSet("err_code"))
{
data.SetValue("err_code", inputObj.GetValue("err_code"));
}
//错误代码描述
if (inputObj.IsSet("err_code_des"))
{
data.SetValue("err_code_des", inputObj.GetValue("err_code_des"));
}
//商户订单号
if (inputObj.IsSet("out_trade_no"))
{
data.SetValue("out_trade_no", inputObj.GetValue("out_trade_no"));
}
//设备号
if (inputObj.IsSet("device_info"))
{
data.SetValue("device_info", inputObj.GetValue("device_info"));
}
try
{
Report(data);
}
catch (WxPayException ex)
{
//不做任何处理
}
}
/**
*
*
* @param WxPayData inputObj
* @param int timeOut
* @throws WxPayException
* @return
*/
public static WxPayData Report(WxPayData inputObj, int timeOut = 1)
{
string url = "https://api.mch.weixin.qq.com/payitil/report";
//检测必填参数
if (!inputObj.IsSet("interface_url"))
{
throw new WxPayException("接口URL缺少必填参数interface_url");
}
if (!inputObj.IsSet("return_code"))
{
throw new WxPayException("返回状态码缺少必填参数return_code");
}
if (!inputObj.IsSet("result_code"))
{
throw new WxPayException("业务结果缺少必填参数result_code");
}
if (!inputObj.IsSet("user_ip"))
{
throw new WxPayException("访问接口IP缺少必填参数user_ip");
}
if (!inputObj.IsSet("execute_time_"))
{
throw new WxPayException("接口耗时缺少必填参数execute_time_");
}
inputObj.SetValue("appid", WxPayConfig.APPID);//公众账号ID
inputObj.SetValue("mch_id", WxPayConfig.MCHID);//商户号
inputObj.SetValue("user_ip", WxPayConfig.IP);//终端ip
inputObj.SetValue("time", DateTime.Now.ToString("yyyyMMddHHmmss"));//商户上报时间
inputObj.SetValue("nonce_str", GenerateNonceStr());//随机字符串
inputObj.SetValue("sign", inputObj.MakeSign());//签名
string xml = inputObj.ToXml();
Log.Info("WxPayApi", "Report request : " + xml);
string response = HttpService.Post(xml, url, false, timeOut);
Log.Info("WxPayApi", "Report response : " + response);
WxPayData result = new WxPayData();
result.FromXml(response);
return result;
}
/**
*
* @return
*/
public static string GenerateOutTradeNo()
{
var ran = new Random();
return string.Format("{0}{1}{2}", WxPayConfig.MCHID, DateTime.Now.ToString("yyyyMMddHHmmss"), ran.Next(10001,99999));
}
public static string GenerateOutTradeNo2(string no)
{
var ran = new Random();
return string.Format("{0}{1}{2}", WxPayConfig.MCHID, DateTime.Now.ToString("yyyyMMddHHmmss"), no);
}
/**
* 197011 000
* @return
*/
public static string GenerateTimeStamp()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalSeconds).ToString();
}
/**
*
* @return
*/
public static string GenerateNonceStr()
{
return Guid.NewGuid().ToString().Replace("-", "");
}
}
}

@ -0,0 +1,484 @@
namespace HuizhongLibrary.ReportPrint
{
partial class PrintSetup
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.cmdPrintView = new System.Windows.Forms.Button();
this.cmdPrint = new System.Windows.Forms.Button();
this.groupBox5 = new System.Windows.Forms.GroupBox();
this.label7 = new System.Windows.Forms.Label();
this.txtColumnWidthRectify = new System.Windows.Forms.NumericUpDown();
this.groupBox4 = new System.Windows.Forms.GroupBox();
this.radioButton2 = new System.Windows.Forms.RadioButton();
this.radioButton1 = new System.Windows.Forms.RadioButton();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.txtStop = new System.Windows.Forms.NumericUpDown();
this.label6 = new System.Windows.Forms.Label();
this.txtStart = new System.Windows.Forms.NumericUpDown();
this.CheckPagerNumber = new System.Windows.Forms.CheckBox();
this.CheckPagerHeader = new System.Windows.Forms.CheckBox();
this.checkIsFillBlank = new System.Windows.Forms.CheckBox();
this.CheckCollate = new System.Windows.Forms.CheckBox();
this.txtCopies = new System.Windows.Forms.NumericUpDown();
this.label5 = new System.Windows.Forms.Label();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.label4 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.txtHeight = new System.Windows.Forms.NumericUpDown();
this.txtWidth = new System.Windows.Forms.NumericUpDown();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.listPagerKinds = new System.Windows.Forms.ComboBox();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.listPinterName = new System.Windows.Forms.ComboBox();
this.groupBox5.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.txtColumnWidthRectify)).BeginInit();
this.groupBox4.SuspendLayout();
this.groupBox3.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.txtStop)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.txtStart)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.txtCopies)).BeginInit();
this.groupBox2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.txtHeight)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.txtWidth)).BeginInit();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// cmdPrintView
//
this.cmdPrintView.Location = new System.Drawing.Point(258, 256);
this.cmdPrintView.Name = "cmdPrintView";
this.cmdPrintView.Size = new System.Drawing.Size(75, 23);
this.cmdPrintView.TabIndex = 30;
this.cmdPrintView.Text = "打印预览";
this.cmdPrintView.UseVisualStyleBackColor = true;
this.cmdPrintView.Click += new System.EventHandler(this.cmdPrintView_Click);
//
// cmdPrint
//
this.cmdPrint.Location = new System.Drawing.Point(166, 256);
this.cmdPrint.Name = "cmdPrint";
this.cmdPrint.Size = new System.Drawing.Size(75, 23);
this.cmdPrint.TabIndex = 29;
this.cmdPrint.Text = "打印";
this.cmdPrint.UseVisualStyleBackColor = true;
this.cmdPrint.Click += new System.EventHandler(this.cmdPrint_Click);
//
// groupBox5
//
this.groupBox5.Controls.Add(this.label7);
this.groupBox5.Controls.Add(this.txtColumnWidthRectify);
this.groupBox5.Location = new System.Drawing.Point(11, 236);
this.groupBox5.Name = "groupBox5";
this.groupBox5.Size = new System.Drawing.Size(123, 49);
this.groupBox5.TabIndex = 28;
this.groupBox5.TabStop = false;
this.groupBox5.Text = "列宽调整";
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(86, 22);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(29, 12);
this.label7.TabIndex = 8;
this.label7.Text = "毫米";
//
// txtColumnWidthRectify
//
this.txtColumnWidthRectify.DecimalPlaces = 1;
this.txtColumnWidthRectify.Increment = new decimal(new int[] {
1,
0,
0,
65536});
this.txtColumnWidthRectify.Location = new System.Drawing.Point(16, 20);
this.txtColumnWidthRectify.Name = "txtColumnWidthRectify";
this.txtColumnWidthRectify.ReadOnly = true;
this.txtColumnWidthRectify.Size = new System.Drawing.Size(64, 21);
this.txtColumnWidthRectify.TabIndex = 7;
//
// groupBox4
//
this.groupBox4.Controls.Add(this.radioButton2);
this.groupBox4.Controls.Add(this.radioButton1);
this.groupBox4.Location = new System.Drawing.Point(206, 178);
this.groupBox4.Name = "groupBox4";
this.groupBox4.Size = new System.Drawing.Size(127, 52);
this.groupBox4.TabIndex = 27;
this.groupBox4.TabStop = false;
this.groupBox4.Text = "方向";
//
// radioButton2
//
this.radioButton2.AutoSize = true;
this.radioButton2.Enabled = false;
this.radioButton2.Location = new System.Drawing.Point(64, 23);
this.radioButton2.Name = "radioButton2";
this.radioButton2.Size = new System.Drawing.Size(47, 16);
this.radioButton2.TabIndex = 1;
this.radioButton2.TabStop = true;
this.radioButton2.Text = "横向";
this.radioButton2.UseVisualStyleBackColor = true;
//
// radioButton1
//
this.radioButton1.AutoSize = true;
this.radioButton1.Enabled = false;
this.radioButton1.Location = new System.Drawing.Point(11, 23);
this.radioButton1.Name = "radioButton1";
this.radioButton1.Size = new System.Drawing.Size(47, 16);
this.radioButton1.TabIndex = 0;
this.radioButton1.TabStop = true;
this.radioButton1.Text = "纵向";
this.radioButton1.UseVisualStyleBackColor = true;
//
// groupBox3
//
this.groupBox3.Controls.Add(this.txtStop);
this.groupBox3.Controls.Add(this.label6);
this.groupBox3.Controls.Add(this.txtStart);
this.groupBox3.Location = new System.Drawing.Point(11, 177);
this.groupBox3.Name = "groupBox3";
this.groupBox3.Size = new System.Drawing.Size(189, 53);
this.groupBox3.TabIndex = 26;
this.groupBox3.TabStop = false;
this.groupBox3.Text = "打印范围";
//
// txtStop
//
this.txtStop.Location = new System.Drawing.Point(109, 20);
this.txtStop.Maximum = new decimal(new int[] {
1000,
0,
0,
0});
this.txtStop.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.txtStop.Name = "txtStop";
this.txtStop.Size = new System.Drawing.Size(61, 21);
this.txtStop.TabIndex = 8;
this.txtStop.Value = new decimal(new int[] {
1,
0,
0,
0});
this.txtStop.ValueChanged += new System.EventHandler(this.txtStop_ValueChanged);
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(86, 27);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(17, 12);
this.label6.TabIndex = 7;
this.label6.Text = "--";
//
// txtStart
//
this.txtStart.Location = new System.Drawing.Point(19, 20);
this.txtStart.Maximum = new decimal(new int[] {
1000,
0,
0,
0});
this.txtStart.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.txtStart.Name = "txtStart";
this.txtStart.Size = new System.Drawing.Size(61, 21);
this.txtStart.TabIndex = 6;
this.txtStart.Value = new decimal(new int[] {
1,
0,
0,
0});
this.txtStart.ValueChanged += new System.EventHandler(this.txtStart_ValueChanged);
//
// CheckPagerNumber
//
this.CheckPagerNumber.AutoSize = true;
this.CheckPagerNumber.Checked = true;
this.CheckPagerNumber.CheckState = System.Windows.Forms.CheckState.Checked;
this.CheckPagerNumber.Location = new System.Drawing.Point(217, 117);
this.CheckPagerNumber.Name = "CheckPagerNumber";
this.CheckPagerNumber.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
this.CheckPagerNumber.Size = new System.Drawing.Size(72, 16);
this.CheckPagerNumber.TabIndex = 25;
this.CheckPagerNumber.Text = "打印页码";
this.CheckPagerNumber.UseVisualStyleBackColor = true;
//
// CheckPagerHeader
//
this.CheckPagerHeader.AutoSize = true;
this.CheckPagerHeader.Checked = true;
this.CheckPagerHeader.CheckState = System.Windows.Forms.CheckState.Checked;
this.CheckPagerHeader.Enabled = false;
this.CheckPagerHeader.Location = new System.Drawing.Point(217, 136);
this.CheckPagerHeader.Name = "CheckPagerHeader";
this.CheckPagerHeader.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
this.CheckPagerHeader.Size = new System.Drawing.Size(72, 16);
this.CheckPagerHeader.TabIndex = 24;
this.CheckPagerHeader.Text = "分页打印";
this.CheckPagerHeader.UseVisualStyleBackColor = true;
//
// checkIsFillBlank
//
this.checkIsFillBlank.AutoSize = true;
this.checkIsFillBlank.Location = new System.Drawing.Point(217, 155);
this.checkIsFillBlank.Name = "checkIsFillBlank";
this.checkIsFillBlank.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
this.checkIsFillBlank.Size = new System.Drawing.Size(72, 16);
this.checkIsFillBlank.TabIndex = 23;
this.checkIsFillBlank.Text = "填充空行";
this.checkIsFillBlank.UseVisualStyleBackColor = true;
//
// CheckCollate
//
this.CheckCollate.AutoSize = true;
this.CheckCollate.Location = new System.Drawing.Point(217, 98);
this.CheckCollate.Name = "CheckCollate";
this.CheckCollate.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
this.CheckCollate.Size = new System.Drawing.Size(72, 16);
this.CheckCollate.TabIndex = 22;
this.CheckCollate.Text = "逐份打印";
this.CheckCollate.UseVisualStyleBackColor = true;
//
// txtCopies
//
this.txtCopies.Location = new System.Drawing.Point(274, 71);
this.txtCopies.Name = "txtCopies";
this.txtCopies.Size = new System.Drawing.Size(59, 21);
this.txtCopies.TabIndex = 20;
this.txtCopies.Value = new decimal(new int[] {
1,
0,
0,
0});
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(215, 80);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(53, 12);
this.label5.TabIndex = 21;
this.label5.Text = "打印份数";
//
// groupBox2
//
this.groupBox2.Controls.Add(this.label4);
this.groupBox2.Controls.Add(this.label3);
this.groupBox2.Controls.Add(this.txtHeight);
this.groupBox2.Controls.Add(this.txtWidth);
this.groupBox2.Controls.Add(this.label2);
this.groupBox2.Controls.Add(this.label1);
this.groupBox2.Controls.Add(this.listPagerKinds);
this.groupBox2.Location = new System.Drawing.Point(11, 71);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(189, 100);
this.groupBox2.TabIndex = 19;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "纸张选择";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(153, 77);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(29, 12);
this.label4.TabIndex = 7;
this.label4.Text = "毫米";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(153, 50);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(29, 12);
this.label3.TabIndex = 6;
this.label3.Text = "毫米";
//
// txtHeight
//
this.txtHeight.Enabled = false;
this.txtHeight.Location = new System.Drawing.Point(70, 75);
this.txtHeight.Maximum = new decimal(new int[] {
1000,
0,
0,
0});
this.txtHeight.Name = "txtHeight";
this.txtHeight.Size = new System.Drawing.Size(77, 21);
this.txtHeight.TabIndex = 5;
this.txtHeight.ValueChanged += new System.EventHandler(this.txtHeight_ValueChanged);
//
// txtWidth
//
this.txtWidth.Enabled = false;
this.txtWidth.Location = new System.Drawing.Point(70, 48);
this.txtWidth.Maximum = new decimal(new int[] {
1000,
0,
0,
0});
this.txtWidth.Name = "txtWidth";
this.txtWidth.Size = new System.Drawing.Size(77, 21);
this.txtWidth.TabIndex = 4;
this.txtWidth.ValueChanged += new System.EventHandler(this.txtWidth_ValueChanged);
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(17, 77);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(47, 12);
this.label2.TabIndex = 3;
this.label2.Text = "高度(H)";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(17, 50);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(47, 12);
this.label1.TabIndex = 2;
this.label1.Text = "宽度(W)";
//
// listPagerKinds
//
this.listPagerKinds.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.listPagerKinds.FormattingEnabled = true;
this.listPagerKinds.Location = new System.Drawing.Point(16, 20);
this.listPagerKinds.Name = "listPagerKinds";
this.listPagerKinds.Size = new System.Drawing.Size(154, 20);
this.listPagerKinds.TabIndex = 1;
this.listPagerKinds.SelectedIndexChanged += new System.EventHandler(this.listPagerKinds_SelectedIndexChanged);
//
// groupBox1
//
this.groupBox1.Controls.Add(this.listPinterName);
this.groupBox1.Location = new System.Drawing.Point(12, 12);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(321, 53);
this.groupBox1.TabIndex = 18;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "打印机";
//
// listPinterName
//
this.listPinterName.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.listPinterName.FormattingEnabled = true;
this.listPinterName.Location = new System.Drawing.Point(19, 21);
this.listPinterName.Name = "listPinterName";
this.listPinterName.Size = new System.Drawing.Size(296, 20);
this.listPinterName.TabIndex = 0;
//
// PrintSetup
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.White;
this.ClientSize = new System.Drawing.Size(355, 300);
this.Controls.Add(this.cmdPrintView);
this.Controls.Add(this.cmdPrint);
this.Controls.Add(this.groupBox5);
this.Controls.Add(this.groupBox4);
this.Controls.Add(this.groupBox3);
this.Controls.Add(this.CheckPagerNumber);
this.Controls.Add(this.CheckPagerHeader);
this.Controls.Add(this.checkIsFillBlank);
this.Controls.Add(this.CheckCollate);
this.Controls.Add(this.txtCopies);
this.Controls.Add(this.label5);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.groupBox1);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "PrintSetup";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "打印";
this.groupBox5.ResumeLayout(false);
this.groupBox5.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.txtColumnWidthRectify)).EndInit();
this.groupBox4.ResumeLayout(false);
this.groupBox4.PerformLayout();
this.groupBox3.ResumeLayout(false);
this.groupBox3.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.txtStop)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.txtStart)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.txtCopies)).EndInit();
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.txtHeight)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.txtWidth)).EndInit();
this.groupBox1.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button cmdPrintView;
private System.Windows.Forms.Button cmdPrint;
private System.Windows.Forms.GroupBox groupBox5;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.NumericUpDown txtColumnWidthRectify;
private System.Windows.Forms.GroupBox groupBox4;
private System.Windows.Forms.RadioButton radioButton2;
private System.Windows.Forms.RadioButton radioButton1;
private System.Windows.Forms.GroupBox groupBox3;
private System.Windows.Forms.NumericUpDown txtStop;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.NumericUpDown txtStart;
private System.Windows.Forms.CheckBox CheckPagerNumber;
private System.Windows.Forms.CheckBox CheckPagerHeader;
private System.Windows.Forms.CheckBox checkIsFillBlank;
private System.Windows.Forms.CheckBox CheckCollate;
private System.Windows.Forms.NumericUpDown txtCopies;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.NumericUpDown txtHeight;
private System.Windows.Forms.NumericUpDown txtWidth;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.ComboBox listPagerKinds;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.ComboBox listPinterName;
}
}

@ -0,0 +1,241 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace HuizhongLibrary.ReportPrint
{
public partial class PrintSetup : Form
{
private PrintReport m_PrintReport = null;
public PrintReport PrintReport
{
get { return this.m_PrintReport; }
set { this.m_PrintReport = value; }
}
private PrintMuchReport muchReport;
private MyReport report;
public PrintSetup(PrintReport print)
{
InitializeComponent();
this.PrintReport = print;
this.report = print.Report;
BindPinterName();
BindPagerKinds();
checkIsFillBlank.Checked = report.IsFillBlank;
txtCopies.Value = print.Copies;
if (string.IsNullOrEmpty(PrintReport.Document.PrinterSettings.PrinterName) == false) listPinterName.SelectedItem = PrintReport.Document.PrinterSettings.PrinterName;
}
public PrintSetup(PrintMuchReport print)
{
InitializeComponent();
this.muchReport = print;
this.report = print.Report[0];
BindPinterName();
BindPagerKinds();
checkIsFillBlank.Visible = false;
txtCopies.Value = print.Copies;
if (string.IsNullOrEmpty(muchReport.Document.PrinterSettings.PrinterName) == false) listPinterName.SelectedItem = muchReport.Document.PrinterSettings.PrinterName;
}
#region 获取打印机列表
public void BindPinterName()
{
int a = 0, b = 0;
if (PrintReport != null)
{
foreach (string sc in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
{
listPinterName.Items.Add(sc);
if (sc == PrintReport.Document.PrinterSettings.PrinterName) b = a;
a++;
}
}
else
{
foreach (string sc in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
{
listPinterName.Items.Add(sc);
if (sc == muchReport.Document.PrinterSettings.PrinterName) b = a;
a++;
}
}
listPinterName.SelectedIndex = b;
}
#endregion
#region 可使用纸张列表
public void BindPagerKinds()
{
foreach (Kind kd in report.PagerKind)
{
listPagerKinds.Items.Add(kd.Name);
}
if (report.PagerKind[0].Landscape == false)
{
radioButton1.Checked = true;
txtWidth.Value = Convert.ToDecimal(report.PagerKind[0].Width);
txtHeight.Value = Convert.ToDecimal(report.PagerKind[0].Height);
}
else
{
radioButton2.Checked = true;
txtWidth.Value = Convert.ToDecimal(report.PagerKind[0].Height);
txtHeight.Value = Convert.ToDecimal(report.PagerKind[0].Width);
}
listPagerKinds.SelectedIndex = 0;
CheckPagerNumber.Checked = report.ShowPagerNumber;
}
#endregion
private void listPagerKinds_SelectedIndexChanged(object sender, System.EventArgs e)
{
if (report.PagerKind[listPagerKinds.SelectedIndex].Landscape == false)
{
radioButton1.Checked = true;
txtWidth.Value = Convert.ToDecimal(report.PagerKind[listPagerKinds.SelectedIndex].Width);
txtHeight.Value = Convert.ToDecimal(report.PagerKind[listPagerKinds.SelectedIndex].Height);
}
else
{
radioButton2.Checked = true;
txtWidth.Value = Convert.ToDecimal(report.PagerKind[listPagerKinds.SelectedIndex].Height);
txtHeight.Value = Convert.ToDecimal(report.PagerKind[listPagerKinds.SelectedIndex].Width);
}
report.Width = Convert.ToSingle(txtWidth.Value);
report.Height = Convert.ToSingle(txtHeight.Value);
if (PrintReport != null)
{
this.PrintReport.SetPageRecordNumber(Convert.ToInt32(txtWidth.Value), Convert.ToInt32(txtHeight.Value));
this.PrintReport.MathPageCount();
int PagerCount = this.PrintReport.GetPagerCount();
txtStart.Value = 1; txtStop.Maximum = PagerCount; txtStop.Value = PagerCount;
}
else
{
int PagerCount = muchReport.GetPagerCount();
txtStart.Value = 1; txtStop.Maximum = PagerCount; txtStop.Value = PagerCount;
}
}
private void txtWidth_ValueChanged(object sender, System.EventArgs e)
{
//if (report.Width > Convert.ToSingle(txtWidth.Value)) { MessageBox.Show(this, "打印纸张宽度不能小于" + report.Width.ToString() + "毫米"); return; }
}
private void txtHeight_ValueChanged(object sender, System.EventArgs e)
{
//float h = report.Header.Height + report.Footer.Height;
//if (h >= Convert.ToSingle(txtHeight.Value)) { MessageBox.Show(this, "打印纸张高度不能小于" + h.ToString() + "毫米"); return; }
}
private void cmdPrint_Click(object sender, System.EventArgs e)
{
try
{
if (PrintReport != null)
{
this.PrintReport.Document.PrinterSettings.PrinterName = listPinterName.Text;
report.ShowPagerNumber = CheckPagerNumber.Checked;
this.PrintReport.IsFixHeaderFooter = CheckPagerHeader.Checked;
this.PrintReport.Copies = Convert.ToInt16(txtCopies.Value);
this.PrintReport.Collate = CheckCollate.Checked;
this.PrintReport.StartPageNumber = Convert.ToInt32(txtStart.Value) - 1;
this.PrintReport.StopPageNumber = Convert.ToInt32(txtStop.Value);
this.PrintReport.Kind = report.PagerKind[listPagerKinds.SelectedIndex];
this.PrintReport.ColumnWidthRectify = Convert.ToSingle(txtColumnWidthRectify.Value);
this.PrintReport.IsFillBlank = checkIsFillBlank.Checked;
this.PrintReport.Print();
}
else
{
muchReport.Document.PrinterSettings.PrinterName = listPinterName.Text;
report.ShowPagerNumber = CheckPagerNumber.Checked;
//muchReport.IsFixHeaderFooter = CheckPagerHeader.Checked;
muchReport.Copies = Convert.ToInt16(txtCopies.Value);
muchReport.Collate = CheckCollate.Checked;
//muchReport.StartPageNumber = Convert.ToInt32(txtStart.Value) - 1;
//muchReport.StopPageNumber = Convert.ToInt32(txtStop.Value);
muchReport.Kind = report.PagerKind[listPagerKinds.SelectedIndex];
//muchReport.ColumnWidthRectify = Convert.ToSingle(txtColumnWidthRectify.Value);
//muchReport.IsFillBlank = checkIsFillBlank.Checked;
muchReport.Print();
}
this.Close();
}
catch
{
}
}
private void cmdPrintView_Click(object sender, System.EventArgs e)
{
try
{
if (PrintReport != null)
{
this.PrintReport.Document.PrinterSettings.PrinterName = listPinterName.Text;
report.ShowPagerNumber = CheckPagerNumber.Checked;
this.PrintReport.IsFixHeaderFooter = CheckPagerHeader.Checked;
this.PrintReport.Copies = Convert.ToInt16(txtCopies.Value);
this.PrintReport.Collate = CheckCollate.Checked;
this.PrintReport.StartPageNumber = Convert.ToInt32(txtStart.Value) - 1;
this.PrintReport.StopPageNumber = Convert.ToInt32(txtStop.Value);
this.PrintReport.Kind = report.PagerKind[listPagerKinds.SelectedIndex];
this.PrintReport.ColumnWidthRectify = Convert.ToSingle(txtColumnWidthRectify.Value);
this.PrintReport.IsFillBlank = checkIsFillBlank.Checked;
this.Hide();
PrintPreviewDialog printPreviewDialog1 = new PrintPreviewDialog();
printPreviewDialog1.Document = this.m_PrintReport.Document;
printPreviewDialog1.SetDesktopLocation(0, 0);
printPreviewDialog1.SetDesktopBounds(0, 0, SystemInformation.PrimaryMonitorMaximizedWindowSize.Width, SystemInformation.PrimaryMonitorMaximizedWindowSize.Height);
printPreviewDialog1.PrintPreviewControl.Zoom = 0.9;
printPreviewDialog1.ShowDialog();
}
else
{
muchReport.Document.PrinterSettings.PrinterName = listPinterName.Text;
report.ShowPagerNumber = CheckPagerNumber.Checked;
//muchReport.IsFixHeaderFooter = CheckPagerHeader.Checked;
muchReport.Copies = Convert.ToInt16(txtCopies.Value);
muchReport.Collate = CheckCollate.Checked;
//muchReport.StartPageNumber = Convert.ToInt32(txtStart.Value) - 1;
//muchReport.StopPageNumber = Convert.ToInt32(txtStop.Value);
muchReport.Kind = report.PagerKind[listPagerKinds.SelectedIndex];
//muchReport.ColumnWidthRectify = Convert.ToSingle(txtColumnWidthRectify.Value);
//muchReport.IsFillBlank = checkIsFillBlank.Checked;
this.Hide();
PrintPreviewDialog printPreviewDialog1 = new PrintPreviewDialog();
printPreviewDialog1.Document = muchReport.Document;
printPreviewDialog1.SetDesktopLocation(0, 0);
printPreviewDialog1.SetDesktopBounds(0, 0, SystemInformation.PrimaryMonitorMaximizedWindowSize.Width, SystemInformation.PrimaryMonitorMaximizedWindowSize.Height);
printPreviewDialog1.PrintPreviewControl.Zoom = 0.9;
printPreviewDialog1.ShowDialog();
}
this.Close();
}
catch
{
}
}
private void txtStart_ValueChanged(object sender, System.EventArgs e)
{
if (txtStart.Value > txtStop.Value) txtStart.Value = txtStop.Value;
}
private void txtStop_ValueChanged(object sender, System.EventArgs e)
{
if (txtStart.Value > txtStop.Value) txtStop.Value = txtStart.Value;
}
}
}

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save