diff --git a/单机/菜单工具/MenuTool/Form1.Designer.cs b/单机/菜单工具/MenuTool/Form1.Designer.cs new file mode 100644 index 0000000..11d143c --- /dev/null +++ b/单机/菜单工具/MenuTool/Form1.Designer.cs @@ -0,0 +1,377 @@ +namespace MenuTool +{ + partial class Form1 + { + /// + /// 必需的设计器变量。 + /// + private System.ComponentModel.IContainer components = null; + + /// + /// 清理所有正在使用的资源。 + /// + /// 如果应释放托管资源,为 true;否则为 false。 + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows 窗体设计器生成的代码 + + /// + /// 设计器支持所需的方法 - 不要修改 + /// 使用代码编辑器修改此方法的内容。 + /// + 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; + } +} + diff --git a/单机/菜单工具/MenuTool/Form1.cs b/单机/菜单工具/MenuTool/Form1.cs new file mode 100644 index 0000000..70b29ef --- /dev/null +++ b/单机/菜单工具/MenuTool/Form1.cs @@ -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 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 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 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 GetListMenu(int ParentModuleNo) + { + if (ListMenu == null) return new List(); + var query = from item in ListMenu + where item.ParentModuleNo == ParentModuleNo + orderby item.SortNo + select item; + List list = query.ToList(); + //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 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 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 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 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 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("保存成功"); + } + } +} + diff --git a/单机/菜单工具/MenuTool/Form1.resx b/单机/菜单工具/MenuTool/Form1.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/单机/菜单工具/MenuTool/Form1.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/单机/菜单工具/MenuTool/MenuTool.csproj b/单机/菜单工具/MenuTool/MenuTool.csproj new file mode 100644 index 0000000..ae002fa --- /dev/null +++ b/单机/菜单工具/MenuTool/MenuTool.csproj @@ -0,0 +1,82 @@ + + + + + Debug + AnyCPU + {99FFA09B-022A-4685-8F99-F29636D5B87F} + WinExe + MenuTool + MenuTool + v4.0 + 512 + true + + + x86 + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + Form + + + Form1.cs + + + + + + + + + Form1.cs + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + \ No newline at end of file diff --git a/单机/菜单工具/MenuTool/MenuTool.sln b/单机/菜单工具/MenuTool/MenuTool.sln new file mode 100644 index 0000000..5ad258c --- /dev/null +++ b/单机/菜单工具/MenuTool/MenuTool.sln @@ -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 diff --git a/单机/菜单工具/MenuTool/Model/BaseModel.cs b/单机/菜单工具/MenuTool/Model/BaseModel.cs new file mode 100644 index 0000000..7cac726 --- /dev/null +++ b/单机/菜单工具/MenuTool/Model/BaseModel.cs @@ -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; } + + } +} diff --git a/单机/菜单工具/MenuTool/Model/SysMenu.cs b/单机/菜单工具/MenuTool/Model/SysMenu.cs new file mode 100644 index 0000000..1ec15f9 --- /dev/null +++ b/单机/菜单工具/MenuTool/Model/SysMenu.cs @@ -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; } + } +} diff --git a/单机/菜单工具/MenuTool/Model/WX_App.cs b/单机/菜单工具/MenuTool/Model/WX_App.cs new file mode 100644 index 0000000..ea0079e --- /dev/null +++ b/单机/菜单工具/MenuTool/Model/WX_App.cs @@ -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 +} diff --git a/单机/菜单工具/MenuTool/Program.cs b/单机/菜单工具/MenuTool/Program.cs new file mode 100644 index 0000000..646816d --- /dev/null +++ b/单机/菜单工具/MenuTool/Program.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Windows.Forms; + +namespace MenuTool +{ + internal static class Program + { + /// + /// 应用程序的主入口点。 + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new Form1()); + } + } +} diff --git a/单机/菜单工具/MenuTool/Properties/AssemblyInfo.cs b/单机/菜单工具/MenuTool/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..13eabb8 --- /dev/null +++ b/单机/菜单工具/MenuTool/Properties/AssemblyInfo.cs @@ -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")] diff --git a/单机/菜单工具/MenuTool/Properties/Resources.Designer.cs b/单机/菜单工具/MenuTool/Properties/Resources.Designer.cs new file mode 100644 index 0000000..4a48811 --- /dev/null +++ b/单机/菜单工具/MenuTool/Properties/Resources.Designer.cs @@ -0,0 +1,71 @@ +//------------------------------------------------------------------------------ +// +// 此代码由工具生成。 +// 运行时版本: 4.0.30319.42000 +// +// 对此文件的更改可能导致不正确的行为,如果 +// 重新生成代码,则所做更改将丢失。 +// +//------------------------------------------------------------------------------ + +namespace MenuTool.Properties +{ + + + /// + /// 强类型资源类,用于查找本地化字符串等。 + /// + // 此类是由 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() + { + } + + /// + /// 返回此类使用的缓存 ResourceManager 实例。 + /// + [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; + } + } + + /// + /// 重写当前线程的 CurrentUICulture 属性,对 + /// 使用此强类型资源类的所有资源查找执行重写。 + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture + { + get + { + return resourceCulture; + } + set + { + resourceCulture = value; + } + } + } +} diff --git a/单机/菜单工具/MenuTool/Properties/Resources.resx b/单机/菜单工具/MenuTool/Properties/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/单机/菜单工具/MenuTool/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/单机/菜单工具/MenuTool/Properties/Settings.Designer.cs b/单机/菜单工具/MenuTool/Properties/Settings.Designer.cs new file mode 100644 index 0000000..59debe5 --- /dev/null +++ b/单机/菜单工具/MenuTool/Properties/Settings.Designer.cs @@ -0,0 +1,30 @@ +//------------------------------------------------------------------------------ +// +// 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. +// +//------------------------------------------------------------------------------ + +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; + } + } + } +} diff --git a/单机/菜单工具/MenuTool/Properties/Settings.settings b/单机/菜单工具/MenuTool/Properties/Settings.settings new file mode 100644 index 0000000..3964565 --- /dev/null +++ b/单机/菜单工具/MenuTool/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/单机/菜单工具/MenuTool/StaticModel.cs b/单机/菜单工具/MenuTool/StaticModel.cs new file mode 100644 index 0000000..7594335 --- /dev/null +++ b/单机/菜单工具/MenuTool/StaticModel.cs @@ -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 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 ListModel = tb.ToList(); + return ListModel; + } + #endregion + + } +} diff --git a/基础类库/HuizhongLibrary/ActivityKeyHook.cs b/基础类库/HuizhongLibrary/ActivityKeyHook.cs new file mode 100644 index 0000000..3f5f1c1 --- /dev/null +++ b/基础类库/HuizhongLibrary/ActivityKeyHook.cs @@ -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); + } + } +} diff --git a/基础类库/HuizhongLibrary/AesGcm.cs b/基础类库/HuizhongLibrary/AesGcm.cs new file mode 100644 index 0000000..0f10bbd --- /dev/null +++ b/基础类库/HuizhongLibrary/AesGcm.cs @@ -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); + } + } +} diff --git a/基础类库/HuizhongLibrary/CDmSoft.cs b/基础类库/HuizhongLibrary/CDmSoft.cs new file mode 100644 index 0000000..9de04ba --- /dev/null +++ b/基础类库/HuizhongLibrary/CDmSoft.cs @@ -0,0 +1,2558 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Runtime.InteropServices; + +namespace HuizhongLibrary +{ + /// + /// 大漠插件C#免注册调用类 + /// 本模块必须包含dmc.dll 实现不用注册dm.dll 到系统可以动态调用 + /// + public class CDmSoft : IDisposable + { + + #region import DLL 函数 + [DllImport("dmc.dll",CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern IntPtr CreateDM(string dmpath); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int FreeDM(); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string Ver(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int SetPath(IntPtr dm,string path); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string Ocr(IntPtr dm,int x1,int y1,int x2,int y2,string color,double sim); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int FindStr(IntPtr dm,int x1,int y1,int x2,int y2,string str,string color,double sim,out object x,out object y); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int GetResultCount(IntPtr dm,string str); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int GetResultPos(IntPtr dm,string str,int index,out object x,out object y); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int StrStr(IntPtr dm,string s,string str); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int SendCommand(IntPtr dm,string cmd); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int UseDict(IntPtr dm,int index); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string GetBasePath(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int SetDictPwd(IntPtr dm,string pwd); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string OcrInFile(IntPtr dm,int x1,int y1,int x2,int y2,string pic_name,string color,double sim); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int Capture(IntPtr dm,int x1,int y1,int x2,int y2,string file_); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int KeyPress(IntPtr dm,int vk); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int KeyDown(IntPtr dm,int vk); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int KeyUp(IntPtr dm,int vk); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int LeftClick(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int RightClick(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int MiddleClick(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int LeftDoubleClick(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int LeftDown(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int LeftUp(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int RightDown(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int RightUp(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int MoveTo(IntPtr dm,int x,int y); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int MoveR(IntPtr dm,int rx,int ry); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string GetColor(IntPtr dm,int x,int y); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string GetColorBGR(IntPtr dm,int x,int y); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string RGB2BGR(IntPtr dm,string rgb_color); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string BGR2RGB(IntPtr dm,string bgr_color); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int UnBindWindow(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int CmpColor(IntPtr dm,int x,int y,string color,double sim); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int ClientToScreen(IntPtr dm,int hwnd,ref object x,ref object y); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int ScreenToClient(IntPtr dm,int hwnd,ref object x,ref object y); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int ShowScrMsg(IntPtr dm,int x1,int y1,int x2,int y2,string msg,string color); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int SetMinRowGap(IntPtr dm,int row_gap); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int SetMinColGap(IntPtr dm,int col_gap); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int FindColor(IntPtr dm,int x1,int y1,int x2,int y2,string color,double sim,int dir,out object x,out object y); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string FindColorEx(IntPtr dm,int x1,int y1,int x2,int y2,string color,double sim,int dir); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int SetWordLineHeight(IntPtr dm,int line_height); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int SetWordGap(IntPtr dm,int word_gap); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int SetRowGapNoDict(IntPtr dm,int row_gap); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int SetColGapNoDict(IntPtr dm,int col_gap); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int SetWordLineHeightNoDict(IntPtr dm,int line_height); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int SetWordGapNoDict(IntPtr dm,int word_gap); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int GetWordResultCount(IntPtr dm,string str); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int GetWordResultPos(IntPtr dm,string str,int index,out object x,out object y); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string GetWordResultStr(IntPtr dm,string str,int index); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string GetWords(IntPtr dm,int x1,int y1,int x2,int y2,string color,double sim); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string GetWordsNoDict(IntPtr dm,int x1,int y1,int x2,int y2,string color); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int SetShowErrorMsg(IntPtr dm,int show); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int GetClientSize(IntPtr dm,int hwnd,out object width,out object height); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int MoveWindow(IntPtr dm,int hwnd,int x,int y); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string GetColorHSV(IntPtr dm,int x,int y); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string GetAveRGB(IntPtr dm,int x1,int y1,int x2,int y2); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string GetAveHSV(IntPtr dm,int x1,int y1,int x2,int y2); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int GetForegroundWindow(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int GetForegroundFocus(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int GetMousePointWindow(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int GetPointWindow(IntPtr dm,int x,int y); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string EnumWindow(IntPtr dm,int parent,string title,string class_name,int filter); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int GetWindowState(IntPtr dm,int hwnd,int flag); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int GetWindow(IntPtr dm,int hwnd,int flag); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int GetSpecialWindow(IntPtr dm,int flag); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int SetWindowText(IntPtr dm,int hwnd,string text); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int SetWindowSize(IntPtr dm,int hwnd,int width,int height); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int GetWindowRect(IntPtr dm,int hwnd,out object x1,out object y1,out object x2,out object y2); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string GetWindowTitle(IntPtr dm,int hwnd); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string GetWindowClass(IntPtr dm,int hwnd); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int SetWindowState(IntPtr dm,int hwnd,int flag); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int CreateFoobarRect(IntPtr dm,int hwnd,int x,int y,int w,int h); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int CreateFoobarRoundRect(IntPtr dm,int hwnd,int x,int y,int w,int h,int rw,int rh); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int CreateFoobarEllipse(IntPtr dm,int hwnd,int x,int y,int w,int h); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int CreateFoobarCustom(IntPtr dm,int hwnd,int x,int y,string pic,string trans_color,double sim); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int FoobarFillRect(IntPtr dm,int hwnd,int x1,int y1,int x2,int y2,string color); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int FoobarDrawText(IntPtr dm,int hwnd,int x,int y,int w,int h,string text,string color,int align); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int FoobarDrawPic(IntPtr dm,int hwnd,int x,int y,string pic,string trans_color); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int FoobarUpdate(IntPtr dm,int hwnd); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int FoobarLock(IntPtr dm,int hwnd); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int FoobarUnlock(IntPtr dm,int hwnd); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int FoobarSetFont(IntPtr dm,int hwnd,string font_name,int size,int flag); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int FoobarTextRect(IntPtr dm,int hwnd,int x,int y,int w,int h); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int FoobarPrintText(IntPtr dm,int hwnd,string text,string color); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int FoobarClearText(IntPtr dm,int hwnd); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int FoobarTextLineGap(IntPtr dm,int hwnd,int gap); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int Play(IntPtr dm,string file_); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int FaqCapture(IntPtr dm,int x1,int y1,int x2,int y2,int quality,int delay,int time); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int FaqRelease(IntPtr dm,int handle); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string FaqSend(IntPtr dm,string server,int handle,int request_type,int time_out); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int Beep(IntPtr dm,int fre,int delay); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int FoobarClose(IntPtr dm,int hwnd); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int MoveDD(IntPtr dm,int dx,int dy); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int FaqGetSize(IntPtr dm,int handle); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int LoadPic(IntPtr dm,string pic_name); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int FreePic(IntPtr dm,string pic_name); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int GetScreenData(IntPtr dm,int x1,int y1,int x2,int y2); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int FreeScreenData(IntPtr dm,int handle); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int WheelUp(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int WheelDown(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int SetMouseDelay(IntPtr dm,string type_,int delay); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int SetKeypadDelay(IntPtr dm,string type_,int delay); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string GetEnv(IntPtr dm,int index,string name); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int SetEnv(IntPtr dm,int index,string name,string value); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int SendString(IntPtr dm,int hwnd,string str); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int DelEnv(IntPtr dm,int index,string name); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string GetPath(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int SetDict(IntPtr dm,int index,string dict_name); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int FindPic(IntPtr dm,int x1,int y1,int x2,int y2,string pic_name,string delta_color,double sim,int dir,out object x,out object y); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string FindPicEx(IntPtr dm,int x1,int y1,int x2,int y2,string pic_name,string delta_color,double sim,int dir); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int SetClientSize(IntPtr dm,int hwnd,int width,int height); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int ReadInt(IntPtr dm,int hwnd,string addr,int type_); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int ReadFloat(IntPtr dm,int hwnd,string addr); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int ReadDouble(IntPtr dm,int hwnd,string addr); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string FindInt(IntPtr dm,int hwnd,string addr_range,int int_value_min,int int_value_max,int type_); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string FindFloat(IntPtr dm,int hwnd,string addr_range,Single float_value_min,Single float_value_max); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string FindDouble(IntPtr dm,int hwnd,string addr_range,double double_value_min,double double_value_max); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string FindString(IntPtr dm,int hwnd,string addr_range,string string_value,int type_); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int GetModuleBaseAddr(IntPtr dm,int hwnd,string module_name); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string MoveToEx(IntPtr dm,int x,int y,int w,int h); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string MatchPicName(IntPtr dm,string pic_name); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int AddDict(IntPtr dm,int index,string dict_info); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int EnterCri(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int LeaveCri(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int WriteInt(IntPtr dm,int hwnd,string addr,int type_,int v); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int WriteFloat(IntPtr dm,int hwnd,string addr,Single v); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int WriteDouble(IntPtr dm,int hwnd,string addr,double v); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int WriteString(IntPtr dm,int hwnd,string addr,int type_,string v); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int AsmAdd(IntPtr dm,string asm_ins); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int AsmClear(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int AsmCall(IntPtr dm,int hwnd,int mode); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int FindMultiColor(IntPtr dm,int x1,int y1,int x2,int y2,string first_color,string offset_color,double sim,int dir,out object x,out object y); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string FindMultiColorEx(IntPtr dm,int x1,int y1,int x2,int y2,string first_color,string offset_color,double sim,int dir); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string AsmCode(IntPtr dm,int base_addr); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string Assemble(IntPtr dm,string asm_code,int base_addr,int is_upper); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int SetWindowTransparent(IntPtr dm,int hwnd,int v); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string ReadData(IntPtr dm,int hwnd,string addr,int len); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int WriteData(IntPtr dm,int hwnd,string addr,string data); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string FindData(IntPtr dm,int hwnd,string addr_range,string data); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int SetPicPwd(IntPtr dm,string pwd); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int Log(IntPtr dm,string info); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string FindStrE(IntPtr dm,int x1,int y1,int x2,int y2,string str,string color,double sim); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string FindColorE(IntPtr dm,int x1,int y1,int x2,int y2,string color,double sim,int dir); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string FindPicE(IntPtr dm,int x1,int y1,int x2,int y2,string pic_name,string delta_color,double sim,int dir); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string FindMultiColorE(IntPtr dm,int x1,int y1,int x2,int y2,string first_color,string offset_color,double sim,int dir); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int SetExactOcr(IntPtr dm,int exact_ocr); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string ReadString(IntPtr dm,int hwnd,string addr,int type_,int len); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int FoobarTextPrintDir(IntPtr dm,int hwnd,int dir); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string OcrEx(IntPtr dm,int x1,int y1,int x2,int y2,string color,double sim); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int SetDisplayInput(IntPtr dm,string mode); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int GetTime(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int GetScreenWidth(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int GetScreenHeight(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int BindWindowEx(IntPtr dm,int hwnd,string display,string mouse,string keypad,string public_desc,int mode); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string GetDiskSerial(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string Md5(IntPtr dm,string str); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string GetMac(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int ActiveInputMethod(IntPtr dm,int hwnd,string id); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int CheckInputMethod(IntPtr dm,int hwnd,string id); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int FindInputMethod(IntPtr dm,string id); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int GetCursorPos(IntPtr dm,out object x,out object y); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int BindWindow(IntPtr dm,int hwnd,string display,string mouse,string keypad,int mode); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int FindWindow(IntPtr dm,string class_name,string title_name); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int GetScreenDepth(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int SetScreen(IntPtr dm,int width,int height,int depth); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int ExitOs(IntPtr dm,int type_); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string GetDir(IntPtr dm,int type_); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int GetOsType(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int FindWindowEx(IntPtr dm,int parent,string class_name,string title_name); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int SetExportDict(IntPtr dm,int index,string dict_name); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string GetCursorShape(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int DownCpu(IntPtr dm,int rate); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string GetCursorSpot(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int SendString2(IntPtr dm,int hwnd,string str); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int FaqPost(IntPtr dm,string server,int handle,int request_type,int time_out); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string FaqFetch(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string FetchWord(IntPtr dm,int x1,int y1,int x2,int y2,string color,string word); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int CaptureJpg(IntPtr dm,int x1,int y1,int x2,int y2,string file_,int quality); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int FindStrWithFont(IntPtr dm,int x1,int y1,int x2,int y2,string str,string color,double sim,string font_name,int font_size,int flag,out object x,out object y); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string FindStrWithFontE(IntPtr dm,int x1,int y1,int x2,int y2,string str,string color,double sim,string font_name,int font_size,int flag); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string FindStrWithFontEx(IntPtr dm,int x1,int y1,int x2,int y2,string str,string color,double sim,string font_name,int font_size,int flag); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string GetDictInfo(IntPtr dm,string str,string font_name,int font_size,int flag); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int SaveDict(IntPtr dm,int index,string file_); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int GetWindowProcessId(IntPtr dm,int hwnd); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string GetWindowProcessPath(IntPtr dm,int hwnd); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int LockInput(IntPtr dm,int lock1); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string GetPicSize(IntPtr dm,string pic_name); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int GetID(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int CapturePng(IntPtr dm,int x1,int y1,int x2,int y2,string file_); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int CaptureGif(IntPtr dm,int x1,int y1,int x2,int y2,string file_,int delay,int time); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int ImageToBmp(IntPtr dm,string pic_name,string bmp_name); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int FindStrFast(IntPtr dm,int x1,int y1,int x2,int y2,string str,string color,double sim,out object x,out object y); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string FindStrFastEx(IntPtr dm,int x1,int y1,int x2,int y2,string str,string color,double sim); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string FindStrFastE(IntPtr dm,int x1,int y1,int x2,int y2,string str,string color,double sim); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int EnableDisplayDebug(IntPtr dm,int enable_debug); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int CapturePre(IntPtr dm,string file_); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int RegEx(IntPtr dm,string code,string Ver,string ip); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string GetMachineCode(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int SetClipboard(IntPtr dm,string data); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string GetClipboard(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int GetNowDict(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int Is64Bit(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int GetColorNum(IntPtr dm,int x1,int y1,int x2,int y2,string color,double sim); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string EnumWindowByProcess(IntPtr dm,string process_name,string title,string class_name,int filter); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int GetDictCount(IntPtr dm,int index); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int GetLastError(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string GetNetTime(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int EnableGetColorByCapture(IntPtr dm,int en); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int CheckUAC(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int SetUAC(IntPtr dm,int uac); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int DisableFontSmooth(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int CheckFontSmooth(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int SetDisplayAcceler(IntPtr dm,int level); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int FindWindowByProcess(IntPtr dm,string process_name,string class_name,string title_name); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int FindWindowByProcessId(IntPtr dm,int process_id,string class_name,string title_name); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string ReadIni(IntPtr dm,string section,string key,string file_); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int WriteIni(IntPtr dm,string section,string key,string v,string file_); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int RunApp(IntPtr dm,string path,int mode); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int delay(IntPtr dm,int mis); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int FindWindowSuper(IntPtr dm,string spec1,int flag1,int type1,string spec2,int flag2,int type2); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string ExcludePos(IntPtr dm,string all_pos,int type_,int x1,int y1,int x2,int y2); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string FindNearestPos(IntPtr dm,string all_pos,int type_,int x,int y); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string SortPosDistance(IntPtr dm,string all_pos,int type_,int x,int y); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int FindPicMem(IntPtr dm,int x1,int y1,int x2,int y2,string pic_info,string delta_color,double sim,int dir,out object x,out object y); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string FindPicMemEx(IntPtr dm,int x1,int y1,int x2,int y2,string pic_info,string delta_color,double sim,int dir); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string FindPicMemE(IntPtr dm,int x1,int y1,int x2,int y2,string pic_info,string delta_color,double sim,int dir); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string AppendPicAddr(IntPtr dm,string pic_info,int addr,int size); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int WriteFile(IntPtr dm,string file_,string content); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int Stop(IntPtr dm,int id); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int SetDictMem(IntPtr dm,int index,int addr,int size); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string GetNetTimeSafe(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int ForceUnBindWindow(IntPtr dm,int hwnd); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string ReadIniPwd(IntPtr dm,string section,string key,string file_,string pwd); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int WriteIniPwd(IntPtr dm,string section,string key,string v,string file_,string pwd); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int DecodeFile(IntPtr dm,string file_,string pwd); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int KeyDownChar(IntPtr dm,string key_str); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int KeyUpChar(IntPtr dm,string key_str); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int KeyPressChar(IntPtr dm,string key_str); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int KeyPressStr(IntPtr dm,string key_str,int delay); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int EnableKeypadPatch(IntPtr dm,int en); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int EnableKeypadSync(IntPtr dm,int en,int time_out); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int EnableMouseSync(IntPtr dm,int en,int time_out); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int DmGuard(IntPtr dm,int en,string type_); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int FaqCaptureFromFile(IntPtr dm,int x1,int y1,int x2,int y2,string file_,int quality); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string FindIntEx(IntPtr dm,int hwnd,string addr_range,int int_value_min,int int_value_max,int type_,int step,int multi_thread,int mode); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string FindFloatEx(IntPtr dm,int hwnd,string addr_range,Single float_value_min,Single float_value_max,int step,int multi_thread,int mode); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string FindDoubleEx(IntPtr dm,int hwnd,string addr_range,double double_value_min,double double_value_max,int step,int multi_thread,int mode); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string FindStringEx(IntPtr dm,int hwnd,string addr_range,string string_value,int type_,int step,int multi_thread,int mode); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string FindDataEx(IntPtr dm,int hwnd,string addr_range,string data,int step,int multi_thread,int mode); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int EnableRealMouse(IntPtr dm,int en,int mousedelay,int mousestep); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int EnableRealKeypad(IntPtr dm,int en); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int SendStringIme(IntPtr dm,string str); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int FoobarDrawLine(IntPtr dm,int hwnd,int x1,int y1,int x2,int y2,string color,int style,int width); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string FindStrEx(IntPtr dm,int x1,int y1,int x2,int y2,string str,string color,double sim); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int IsBind(IntPtr dm,int hwnd); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int SetDisplayDelay(IntPtr dm,int t); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int GetDmCount(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int DisableScreenSave(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int DisablePowerSave(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int SetMemoryHwndAsProcessId(IntPtr dm,int en); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int FindShape(IntPtr dm,int x1,int y1,int x2,int y2,string offset_color,double sim,int dir,out object x,out object y); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string FindShapeE(IntPtr dm,int x1,int y1,int x2,int y2,string offset_color,double sim,int dir); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string FindShapeEx(IntPtr dm,int x1,int y1,int x2,int y2,string offset_color,double sim,int dir); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string FindStrS(IntPtr dm,int x1,int y1,int x2,int y2,string str,string color,double sim,out object x,out object y); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string FindStrExS(IntPtr dm,int x1,int y1,int x2,int y2,string str,string color,double sim); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string FindStrFastS(IntPtr dm,int x1,int y1,int x2,int y2,string str,string color,double sim,out object x,out object y); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string FindStrFastExS(IntPtr dm,int x1,int y1,int x2,int y2,string str,string color,double sim); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string FindPicS(IntPtr dm,int x1,int y1,int x2,int y2,string pic_name,string delta_color,double sim,int dir,out object x,out object y); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string FindPicExS(IntPtr dm,int x1,int y1,int x2,int y2,string pic_name,string delta_color,double sim,int dir); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int ClearDict(IntPtr dm,int index); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string GetMachineCodeNoMac(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int GetClientRect(IntPtr dm,int hwnd,out object x1,out object y1,out object x2,out object y2); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int EnableFakeActive(IntPtr dm,int en); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int GetScreenDataBmp(IntPtr dm,int x1,int y1,int x2,int y2,out object data,out object size); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int EncodeFile(IntPtr dm,string file_,string pwd); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string GetCursorShapeEx(IntPtr dm,int type_); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int FaqCancel(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string IntToData(IntPtr dm,int int_value,int type_); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string FloatToData(IntPtr dm,Single float_value); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string DoubleToData(IntPtr dm,double double_value); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string StringToData(IntPtr dm,string string_value,int type_); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int SetMemoryFindResultToFile(IntPtr dm,string file_); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int EnableBind(IntPtr dm,int en); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int SetSimMode(IntPtr dm,int mode); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int LockMouseRect(IntPtr dm,int x1,int y1,int x2,int y2); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int SendPaste(IntPtr dm,int hwnd); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int IsDisplayDead(IntPtr dm,int x1,int y1,int x2,int y2,int t); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int GetKeyState(IntPtr dm,int vk); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int CopyFile(IntPtr dm,string src_file,string dst_file,int over); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int IsFileExist(IntPtr dm,string file_); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int DeleteFile(IntPtr dm,string file_); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int MoveFile(IntPtr dm,string src_file,string dst_file); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int CreateFolder(IntPtr dm,string folder_name); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int DeleteFolder(IntPtr dm,string folder_name); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int GetFileLength(IntPtr dm,string file_); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string ReadFile(IntPtr dm,string file_); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int WaitKey(IntPtr dm,int key_code,int time_out); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int DeleteIni(IntPtr dm,string section,string key,string file_); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int DeleteIniPwd(IntPtr dm,string section,string key,string file_,string pwd); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int EnableSpeedDx(IntPtr dm,int en); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int EnableIme(IntPtr dm,int en); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int Reg(IntPtr dm,string code,string Ver); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string SelectFile(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string SelectDirectory(IntPtr dm); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int LockDisplay(IntPtr dm,int lock1); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int FoobarSetSave(IntPtr dm,int hwnd,string file_,int en,string header); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string EnumWindowSuper(IntPtr dm,string spec1,int flag1,int type1,string spec2,int flag2,int type2,int sort); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int DownloadFile(IntPtr dm,string url,string save_file,int timeout); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int EnableKeypadMsg(IntPtr dm,int en); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int EnableMouseMsg(IntPtr dm,int en); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int RegNoMac(IntPtr dm,string code,string Ver); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int RegExNoMac(IntPtr dm,string code,string Ver,string ip); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int SetEnumWindowDelay(IntPtr dm,int delay); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern int FindMulColor(IntPtr dm,int x1,int y1,int x2,int y2,string color,double sim); + + [DllImport("dmc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] + public static extern string GetDict(IntPtr dm,int index,int font_index); + + + #endregion + + private IntPtr _dm = IntPtr.Zero; + private bool disposed = false; + + public IntPtr DM + { + get { return _dm; } + set { _dm = value; } + } + + + public CDmSoft(string path ="dm.dll") + { + _dm = CreateDM(path); + } + + public string Ver(){ + return Ver(_dm); + } + + + + public int SetPath(string path) + { + return SetPath(_dm,path); + } + + public string Ocr(int x1,int y1,int x2,int y2,string color,double sim) + { + return Ocr(_dm,x1, y1, x2, y2, color,sim); + } + + public int FindStr(int x1,int y1,int x2,int y2,string str,string color,double sim, out object x, out object y) + { + return FindStr(_dm,x1, y1, x2, y2, str,color, sim, out x, out y); + } + + public int GetResultCount(string str) + { + return GetResultCount(_dm,str); + } + + public int GetResultPos(string str,int index, out object x,out object y) + { + return GetResultPos(_dm,str, index, out x,out y); + } + + public int StrStr(string s,string str) + { + return StrStr(_dm,s, str); + } + + public int SendCommand(string cmd) + { + return SendCommand(_dm,cmd); + } + + public int UseDict(int index) + { + return UseDict(_dm,index); + } + + public string GetBasePath(){ + return GetBasePath(_dm); + } + + public int SetDictPwd(string pwd) + { + return SetDictPwd(_dm,pwd); + } + + public string OcrInFile(int x1,int y1,int x2,int y2,string pic_name,string color,double sim) + { + return OcrInFile(_dm,x1, y1, x2, y2, pic_name, color, sim); + } + + public int Capture(int x1,int y1,int x2,int y2,string file_) + { + return Capture(_dm,x1, y1, x2, y2, file_); + } + + public int KeyPress(int vk) + { + return KeyPress(_dm,vk); + } + + public int KeyDown(int vk) + { + return KeyDown(_dm,vk); + } + + public int KeyUp(int vk) + { + return KeyUp(_dm,vk); + } + + public int LeftClick(){ + return LeftClick(_dm); + } + + public int RightClick(){ + return RightClick(_dm); + } + + public int MiddleClick(){ + return MiddleClick(_dm); + } + + public int LeftDoubleClick(){ + return LeftDoubleClick(_dm); + } + + public int LeftDown(){ + return LeftDown(_dm); + } + + public int LeftUp(){ + return LeftUp(_dm); + } + + public int RightDown(){ + return RightDown(_dm); + } + + public int RightUp(){ + return RightUp(_dm); + } + + public int MoveTo(int x,int y) + { + return MoveTo(_dm,x, y); + } + + public int MoveR(int rx,int ry) + { + return MoveR(_dm,rx, ry); + } + + public string GetColor(int x,int y) + { + return GetColor(_dm,x, y); + } + + public string GetColorBGR(int x,int y) + { + return GetColorBGR(_dm,x, y); + } + + public string RGB2BGR(string rgb_color) + { + return RGB2BGR(_dm,rgb_color); + } + + public string BGR2RGB(string bgr_color) + { + return BGR2RGB(_dm,bgr_color); + } + + public int UnBindWindow(){ + return UnBindWindow(_dm); + } + + public int CmpColor(int x,int y,string color,double sim) + { + return CmpColor(_dm,x, y, color, sim); + } + + public int ClientToScreen(int hwnd, ref object x, ref object y) + { + return ClientToScreen(_dm,hwnd, ref x, ref y); + } + + public int ScreenToClient(int hwnd, ref object x, ref object y) + { + return ScreenToClient(_dm,hwnd, ref x, ref y); + } + + public int ShowScrMsg(int x1,int y1,int x2,int y2,string msg,string color) + { + return ShowScrMsg(_dm,x1, y1, x2, y2, msg,color); + } + + public int SetMinRowGap(int row_gap) + { + return SetMinRowGap(_dm,row_gap); + } + + public int SetMinColGap(int col_gap) + { + return SetMinColGap(_dm,col_gap); + } + + public int FindColor(int x1,int y1,int x2,int y2,string color,double sim,int dir, out object x, out object y) + { + return FindColor(_dm,x1, y1, x2, y2, color,sim, dir, out x, out y); + } + + public string FindColorEx(int x1,int y1,int x2,int y2,string color,double sim,int dir) + { + return FindColorEx(_dm,x1, y1, x2, y2,color, sim, dir); + } + + public int SetWordLineHeight(int line_height) + { + return SetWordLineHeight(_dm,line_height); + } + + public int SetWordGap(int word_gap) + { + return SetWordGap(_dm,word_gap); + } + + public int SetRowGapNoDict(int row_gap) + { + return SetRowGapNoDict(_dm,row_gap); + } + + public int SetColGapNoDict(int col_gap) + { + return SetColGapNoDict(_dm,col_gap); + } + + public int SetWordLineHeightNoDict(int line_height) + { + return SetWordLineHeightNoDict(_dm,line_height); + } + + public int SetWordGapNoDict(int word_gap) + { + return SetWordGapNoDict(_dm,word_gap); + } + + public int GetWordResultCount(string str) + { + return GetWordResultCount(_dm,str); + } + + public int GetWordResultPos(string str,int index, out object x,out object y) + { + return GetWordResultPos(_dm,str, index, out x,out y); + } + + public string GetWordResultStr(string str,int index) + { + return GetWordResultStr(_dm,str, index); + } + + public string GetWords(int x1,int y1,int x2,int y2,string color,double sim) + { + return GetWords(_dm,x1, y1, x2, y2, color,sim); + } + + public string GetWordsNoDict(int x1,int y1,int x2,int y2,string color) + { + return GetWordsNoDict(_dm,x1, y1, x2, y2,color); + } + + public int SetShowErrorMsg(int show) + { + return SetShowErrorMsg(_dm,show); + } + + public int GetClientSize(int hwnd, out object width, out object height) + { + return GetClientSize(_dm,hwnd, out width, out height); + } + + public int MoveWindow(int hwnd,int x,int y) + { + return MoveWindow(_dm,hwnd, x, y); + } + + public string GetColorHSV(int x,int y) + { + return GetColorHSV(_dm,x, y); + } + + public string GetAveRGB(int x1,int y1,int x2,int y2) + { + return GetAveRGB(_dm,x1, y1, x2, y2); + } + + public string GetAveHSV(int x1,int y1,int x2,int y2) + { + return GetAveHSV(_dm,x1, y1, x2, y2); + } + + public int GetForegroundWindow(){ + return GetForegroundWindow(_dm); + } + + public int GetForegroundFocus(){ + return GetForegroundFocus(_dm); + } + + public int GetMousePointWindow(){ + return GetMousePointWindow(_dm); + } + + public int GetPointWindow(int x,int y) + { + return GetPointWindow(_dm,x, y); + } + + public string EnumWindow(int parent,string title,string class_name,int filter) + { + return EnumWindow(_dm,parent, title, class_name,filter); + } + + public int GetWindowState(int hwnd,int flag) + { + return GetWindowState(_dm,hwnd, flag); + } + + public int GetWindow(int hwnd,int flag) + { + return GetWindow(_dm,hwnd, flag); + } + + public int GetSpecialWindow(int flag) + { + return GetSpecialWindow(_dm,flag); + } + + public int SetWindowText(int hwnd,string text) + { + return SetWindowText(_dm,hwnd, text); + } + + public int SetWindowSize(int hwnd,int width,int height) + { + return SetWindowSize(_dm,hwnd, width, height); + } + + public int GetWindowRect(int hwnd, out object x1, out object y1, out object x2, out object y2) + { + return GetWindowRect(_dm,hwnd, out x1, out y1, out x2, out y2); + } + + public string GetWindowTitle(int hwnd) + { + return GetWindowTitle(_dm,hwnd); + } + + public string GetWindowClass(int hwnd) + { + return GetWindowClass(_dm,hwnd); + } + + public int SetWindowState(int hwnd,int flag) + { + return SetWindowState(_dm,hwnd, flag); + } + + public int CreateFoobarRect(int hwnd,int x,int y,int w,int h) + { + return CreateFoobarRect(_dm,hwnd, x, y, w, h); + } + + public int CreateFoobarRoundRect(int hwnd,int x,int y,int w,int h,int rw,int rh) + { + return CreateFoobarRoundRect(_dm,hwnd, x, y, w, h, rw, rh); + } + + public int CreateFoobarEllipse(int hwnd,int x,int y,int w,int h) + { + return CreateFoobarEllipse(_dm,hwnd, x, y, w, h); + } + + public int CreateFoobarCustom(int hwnd,int x,int y,string pic,string trans_color,double sim) + { + return CreateFoobarCustom(_dm,hwnd, x, y, pic, trans_color, sim); + } + + public int FoobarFillRect(int hwnd,int x1,int y1,int x2,int y2,string color) + { + return FoobarFillRect(_dm,hwnd, x1, y1, x2, y2, color); + } + + public int FoobarDrawText(int hwnd,int x,int y,int w,int h,string text,string color,int align) + { + return FoobarDrawText(_dm,hwnd, x, y, w, h, text, color, align); + } + + public int FoobarDrawPic(int hwnd,int x,int y,string pic,string trans_color) + { + return FoobarDrawPic(_dm,hwnd, x, y, pic, trans_color); + } + + public int FoobarUpdate(int hwnd) + { + return FoobarUpdate(_dm,hwnd); + } + + public int FoobarLock(int hwnd) + { + return FoobarLock(_dm,hwnd); + } + + public int FoobarUnlock(int hwnd) + { + return FoobarUnlock(_dm,hwnd); + } + + public int FoobarSetFont(int hwnd,string font_name,int size,int flag) + { + return FoobarSetFont(_dm,hwnd, font_name, size, flag); + } + + public int FoobarTextRect(int hwnd,int x,int y,int w,int h) + { + return FoobarTextRect(_dm,hwnd, x, y, w, h); + } + + public int FoobarPrintText(int hwnd,string text,string color) + { + return FoobarPrintText(_dm,hwnd, text, color); + } + + public int FoobarClearText(int hwnd) + { + return FoobarClearText(_dm,hwnd); + } + + public int FoobarTextLineGap(int hwnd,int gap) + { + return FoobarTextLineGap(_dm,hwnd, gap); + } + + public int Play(string file_) + { + return Play(_dm,file_); + } + + public int FaqCapture(int x1,int y1,int x2,int y2,int quality,int delay,int time) + { + return FaqCapture(_dm,x1, y1, x2, y2, quality,delay, time); + } + + public int FaqRelease(int handle) + { + return FaqRelease(_dm,handle); + } + + public string FaqSend(string server,int handle,int request_type,int time_out) + { + return FaqSend(_dm,server, handle, request_type, time_out); + } + + public int Beep(int fre,int delay) + { + return Beep(_dm,fre, delay); + } + + public int FoobarClose(int hwnd) + { + return FoobarClose(_dm,hwnd); + } + + public int MoveDD(int dx,int dy) + { + return MoveDD(_dm,dx, dy); + } + + public int FaqGetSize(int handle) + { + return FaqGetSize(_dm,handle); + } + + public int LoadPic(string pic_name) + { + return LoadPic(_dm,pic_name); + } + + public int FreePic(string pic_name) + { + return FreePic(_dm,pic_name); + } + + public int GetScreenData(int x1,int y1,int x2,int y2) + { + return GetScreenData(_dm,x1, y1, x2, y2); + } + + public int FreeScreenData(int handle) + { + return FreeScreenData(_dm,handle); + } + + public int WheelUp(){ + return WheelUp(_dm); + } + + public int WheelDown(){ + return WheelDown(_dm); + } + + public int SetMouseDelay(string type_,int delay) + { + return SetMouseDelay(_dm,type_, delay); + } + + public int SetKeypadDelay(string type_,int delay) + { + return SetKeypadDelay(_dm,type_, delay); + } + + public string GetEnv(int index,string name) + { + return GetEnv(_dm,index, name); + } + + public int SetEnv(int index,string name,string value) + { + return SetEnv(_dm,index, name, value); + } + + public int SendString(int hwnd,string str) + { + return SendString(_dm,hwnd, str); + } + + public int DelEnv(int index,string name) + { + return DelEnv(_dm,index, name); + } + + public string GetPath(){ + return GetPath(_dm); + } + + public int SetDict(int index,string dict_name) + { + return SetDict(_dm,index, dict_name); + } + + public int FindPic(int x1,int y1,int x2,int y2,string pic_name,string delta_color,double sim,int dir, out object x, out object y) + { + return FindPic(_dm,x1, y1, x2, y2, pic_name, delta_color, sim, dir, out x, out y); + } + + public string FindPicEx(int x1,int y1,int x2,int y2,string pic_name,string delta_color,double sim,int dir) + { + return FindPicEx(_dm,x1, y1, x2, y2, pic_name, delta_color, sim, dir); + } + + public int SetClientSize(int hwnd,int width,int height) + { + return SetClientSize(_dm,hwnd, width, height); + } + + public int ReadInt(int hwnd,string addr,int type_) + { + return ReadInt(_dm,hwnd, addr, type_); + } + + public int ReadFloat(int hwnd,string addr) + { + return ReadFloat(_dm,hwnd, addr); + } + + public int ReadDouble(int hwnd,string addr) + { + return ReadDouble(_dm,hwnd, addr); + } + + public string FindInt(int hwnd,string addr_range,int int_value_min,int int_value_max,int type_) + { + return FindInt(_dm,hwnd, addr_range, int_value_min,int_value_max, type_); + } + + public string FindFloat(int hwnd,string addr_range,Single float_value_min,Single float_value_max) + { + return FindFloat(_dm,hwnd, addr_range, float_value_min, float_value_max); + } + + public string FindDouble(int hwnd,string addr_range,double double_value_min,double double_value_max) + { + return FindDouble(_dm,hwnd, addr_range, double_value_min, double_value_max); + } + + public string FindString(int hwnd,string addr_range,string string_value,int type_) + { + return FindString(_dm,hwnd, addr_range, string_value, type_); + } + + public int GetModuleBaseAddr(int hwnd,string module_name) + { + return GetModuleBaseAddr(_dm,hwnd, module_name); + } + + public string MoveToEx(int x,int y,int w,int h) + { + return MoveToEx(_dm,x, y, w, h); + } + + public string MatchPicName(string pic_name) + { + return MatchPicName(_dm,pic_name); + } + + public int AddDict(int index,string dict_info) + { + return AddDict(_dm,index, dict_info); + } + + public int EnterCri(){ + return EnterCri(_dm); + } + + public int LeaveCri(){ + return LeaveCri(_dm); + } + + public int WriteInt(int hwnd,string addr,int type_,int v) + { + return WriteInt(_dm,hwnd, addr, type_, v); + } + + public int WriteFloat(int hwnd,string addr,Single v) + { + return WriteFloat(_dm,hwnd, addr, v); + } + + public int WriteDouble(int hwnd,string addr,double v) + { + return WriteDouble(_dm,hwnd, addr, v); + } + + public int WriteString(int hwnd,string addr,int type_,string v) + { + return WriteString(_dm,hwnd, addr, type_, v); + } + + public int AsmAdd(string asm_ins) + { + return AsmAdd(_dm,asm_ins); + } + + public int AsmClear(){ + return AsmClear(_dm); + } + + public int AsmCall(int hwnd,int mode) + { + return AsmCall(_dm,hwnd, mode); + } + + public int FindMultiColor(int x1,int y1,int x2,int y2,string first_color,string offset_color,double sim,int dir, out object x, out object y) + { + return FindMultiColor(_dm,x1, y1, x2, y2, first_color, offset_color, sim, dir, out x, out y); + } + + public string FindMultiColorEx(int x1,int y1,int x2,int y2,string first_color,string offset_color,double sim,int dir) + { + return FindMultiColorEx(_dm,x1, y1, x2, y2, first_color, offset_color, sim, dir); + } + + public string AsmCode(int base_addr) + { + return AsmCode(_dm,base_addr); + } + + public string Assemble(string asm_code,int base_addr,int is_upper) + { + return Assemble(_dm,asm_code, base_addr, is_upper); + } + + public int SetWindowTransparent(int hwnd,int v) + { + return SetWindowTransparent(_dm,hwnd, v); + } + + public string ReadData(int hwnd,string addr,int len) + { + return ReadData(_dm,hwnd, addr, len); + } + + public int WriteData(int hwnd,string addr,string data) + { + return WriteData(_dm,hwnd, addr, data); + } + + public string FindData(int hwnd,string addr_range,string data) + { + return FindData(_dm,hwnd, addr_range, data); + } + + public int SetPicPwd(string pwd) + { + return SetPicPwd(_dm,pwd); + } + + public int Log(string info) + { + return Log(_dm,info); + } + + public string FindStrE(int x1,int y1,int x2,int y2,string str,string color,double sim) + { + return FindStrE(_dm,x1, y1, x2, y2, str, color, sim); + } + + public string FindColorE(int x1,int y1,int x2,int y2,string color,double sim,int dir) + { + return FindColorE(_dm,x1, y1, x2, y2, color, sim, dir); + } + + public string FindPicE(int x1,int y1,int x2,int y2,string pic_name,string delta_color,double sim,int dir) + { + return FindPicE(_dm,x1, y1, x2, y2, pic_name, delta_color, sim, dir); + } + + public string FindMultiColorE(int x1,int y1,int x2,int y2,string first_color,string offset_color,double sim,int dir) + { + return FindMultiColorE(_dm,x1, y1, x2, y2,first_color, offset_color,sim, dir); + } + + public int SetExactOcr(int exact_ocr) + { + return SetExactOcr(_dm,exact_ocr); + } + + public string ReadString(int hwnd,string addr,int type_,int len) + { + return ReadString(_dm,hwnd, addr, type_, len); + } + + public int FoobarTextPrintDir(int hwnd,int dir) + { + return FoobarTextPrintDir(_dm,hwnd, dir); + } + + public string OcrEx(int x1,int y1,int x2,int y2,string color,double sim) + { + return OcrEx(_dm,x1, y1, x2, y2, color, sim); + } + + public int SetDisplayInput(string mode) + { + return SetDisplayInput(_dm,mode); + } + + public int GetTime(){ + return GetTime(_dm); + } + + public int GetScreenWidth(){ + return GetScreenWidth(_dm); + } + + public int GetScreenHeight(){ + return GetScreenHeight(_dm); + } + + public int BindWindowEx(int hwnd,string display,string mouse,string keypad,string public_desc,int mode) + { + return BindWindowEx(_dm,hwnd, display, mouse, keypad, public_desc, mode); + } + + public string GetDiskSerial(){ + return GetDiskSerial(_dm); + } + + public string Md5(string str) + { + return Md5(_dm,str); + } + + public string GetMac(){ + return GetMac(_dm); + } + + public int ActiveInputMethod(int hwnd,string id) + { + return ActiveInputMethod(_dm,hwnd, id); + } + + public int CheckInputMethod(int hwnd,string id) + { + return CheckInputMethod(_dm,hwnd, id); + } + + public int FindInputMethod(string id) + { + return FindInputMethod(_dm,id); + } + + public int GetCursorPos(out object x, out object y) + { + return GetCursorPos(_dm,out x, out y); + } + + public int BindWindow(int hwnd,string display,string mouse,string keypad,int mode) + { + return BindWindow(_dm,hwnd, display, mouse, keypad, mode); + } + + public int FindWindow(string class_name,string title_name) + { + return FindWindow(_dm,class_name, title_name); + } + + public int GetScreenDepth(){ + return GetScreenDepth(_dm); + } + + public int SetScreen(int width,int height,int depth) + { + return SetScreen(_dm,width, height, depth); + } + + public int ExitOs(int type_) + { + return ExitOs(_dm,type_); + } + + public string GetDir(int type_) + { + return GetDir(_dm,type_); + } + + public int GetOsType(){ + return GetOsType(_dm); + } + + public int FindWindowEx(int parent,string class_name,string title_name) + { + return FindWindowEx(_dm,parent, class_name, title_name); + } + + public int SetExportDict(int index,string dict_name) + { + return SetExportDict(_dm,index, dict_name); + } + + public string GetCursorShape(){ + return GetCursorShape(_dm); + } + + public int DownCpu(int rate) + { + return DownCpu(_dm,rate); + } + + public string GetCursorSpot(){ + return GetCursorSpot(_dm); + } + + public int SendString2(int hwnd,string str) + { + return SendString2(_dm,hwnd, str); + } + + public int FaqPost(string server,int handle,int request_type,int time_out) + { + return FaqPost(_dm,server, handle, request_type, time_out); + } + + public string FaqFetch(){ + return FaqFetch(_dm); + } + + public string FetchWord(int x1,int y1,int x2,int y2,string color,string word) + { + return FetchWord(_dm,x1, y1, x2, y2, color, word); + } + + public int CaptureJpg(int x1,int y1,int x2,int y2,string file_,int quality) + { + return CaptureJpg(_dm,x1, y1, x2, y2, file_, quality); + } + + public int FindStrWithFont(int x1,int y1,int x2,int y2,string str,string color,double sim,string font_name,int font_size,int flag, out object x, out object y) + { + return FindStrWithFont(_dm,x1, y1, x2, y2, str, color, sim, font_name, font_size, flag, out x, out y); + } + + public string FindStrWithFontE(int x1,int y1,int x2,int y2,string str,string color,double sim,string font_name,int font_size,int flag) + { + return FindStrWithFontE(_dm,x1, y1, x2, y2, str, color, sim, font_name, font_size, flag); + } + + public string FindStrWithFontEx(int x1,int y1,int x2,int y2,string str,string color,double sim,string font_name,int font_size,int flag) + { + return FindStrWithFontEx(_dm,x1, y1, x2, y2, str, color, sim, font_name, font_size, flag); + } + + public string GetDictInfo(string str,string font_name,int font_size,int flag) + { + return GetDictInfo(_dm,str, font_name, font_size, flag); + } + + public int SaveDict(int index,string file_) + { + return SaveDict(_dm,index, file_); + } + + public int GetWindowProcessId(int hwnd) + { + return GetWindowProcessId(_dm,hwnd); + } + + public string GetWindowProcessPath(int hwnd) + { + return GetWindowProcessPath(_dm,hwnd); + } + + public int LockInput(int lock1) + { + return LockInput(_dm,lock1); + } + + public string GetPicSize(string pic_name) + { + return GetPicSize(_dm,pic_name); + } + + public int GetID(){ + return GetID(_dm); + } + + public int CapturePng(int x1,int y1,int x2,int y2,string file_) + { + return CapturePng(_dm,x1, y1, x2, y2, file_); + } + + public int CaptureGif(int x1,int y1,int x2,int y2,string file_,int delay,int time) + { + return CaptureGif(_dm,x1, y1, x2, y2, file_, delay, time); + } + + public int ImageToBmp(string pic_name,string bmp_name) + { + return ImageToBmp(_dm,pic_name, bmp_name); + } + + public int FindStrFast(int x1,int y1,int x2,int y2,string str,string color,double sim, out object x, out object y) + { + return FindStrFast(_dm,x1, y1, x2, y2, str, color, sim, out x, out y); + } + + public string FindStrFastEx(int x1,int y1,int x2,int y2,string str,string color,double sim) + { + return FindStrFastEx(_dm,x1, y1, x2, y2, str, color, sim); + } + + public string FindStrFastE(int x1,int y1,int x2,int y2,string str,string color,double sim) + { + return FindStrFastE(_dm,x1, y1, x2, y2,str, color, sim); + } + + public int EnableDisplayDebug(int enable_debug) + { + return EnableDisplayDebug(_dm,enable_debug); + } + + public int CapturePre(string file_) + { + return CapturePre(_dm,file_); + } + + public int RegEx(string code,string Ver,string ip) + { + return RegEx(_dm,code, Ver, ip); + } + + public string GetMachineCode(){ + return GetMachineCode(_dm); + } + + public int SetClipboard(string data) + { + return SetClipboard(_dm,data); + } + + public string GetClipboard(){ + return GetClipboard(_dm); + } + + public int GetNowDict(){ + return GetNowDict(_dm); + } + + public int Is64Bit(){ + return Is64Bit(_dm); + } + + public int GetColorNum(int x1,int y1,int x2,int y2,string color,double sim) + { + return GetColorNum(_dm,x1, y1, x2, y2, color, sim); + } + + public string EnumWindowByProcess(string process_name,string title,string class_name,int filter) + { + return EnumWindowByProcess(_dm,process_name, title, class_name, filter); + } + + public int GetDictCount(int index) + { + return GetDictCount(_dm,index); + } + + public int GetLastError(){ + return GetLastError(_dm); + } + + public string GetNetTime(){ + return GetNetTime(_dm); + } + + public int EnableGetColorByCapture(int en) + { + return EnableGetColorByCapture(_dm,en); + } + + public int CheckUAC(){ + return CheckUAC(_dm); + } + + public int SetUAC(int uac) + { + return SetUAC(_dm,uac); + } + + public int DisableFontSmooth(){ + return DisableFontSmooth(_dm); + } + + public int CheckFontSmooth(){ + return CheckFontSmooth(_dm); + } + + public int SetDisplayAcceler(int level) + { + return SetDisplayAcceler(_dm,level); + } + + public int FindWindowByProcess(string process_name,string class_name,string title_name) + { + return FindWindowByProcess(_dm,process_name, class_name, title_name); + } + + public int FindWindowByProcessId(int process_id,string class_name,string title_name) + { + return FindWindowByProcessId(_dm,process_id, class_name, title_name); + } + + public string ReadIni(string section,string key,string file_) + { + return ReadIni(_dm,section, key, file_); + } + + public int WriteIni(string section,string key,string v,string file_) + { + return WriteIni(_dm,section, key, v, file_); + } + + public int RunApp(string path,int mode) + { + return RunApp(_dm,path, mode); + } + + public int delay(int mis) + { + return delay(_dm,mis); + } + + public int FindWindowSuper(string spec1,int flag1,int type1,string spec2,int flag2,int type2) + { + return FindWindowSuper(_dm,spec1, flag1, type1, spec2, flag2, type2); + } + + public string ExcludePos(string all_pos,int type_,int x1,int y1,int x2,int y2) + { + return ExcludePos(_dm,all_pos, type_, x1, y1, x2, y2); + } + + public string FindNearestPos(string all_pos,int type_,int x,int y) + { + return FindNearestPos(_dm,all_pos, type_, x, y); + } + + public string SortPosDistance(string all_pos,int type_,int x,int y) + { + return SortPosDistance(_dm,all_pos, type_, x, y); + } + + public int FindPicMem(int x1,int y1,int x2,int y2,string pic_info,string delta_color,double sim,int dir, out object x, out object y) + { + return FindPicMem(_dm,x1, y1, x2, y2, pic_info, delta_color, sim, dir, out x, out y); + } + + public string FindPicMemEx(int x1,int y1,int x2,int y2,string pic_info,string delta_color,double sim,int dir) + { + return FindPicMemEx(_dm,x1, y1, x2, y2,pic_info, delta_color, sim, dir); + } + + public string FindPicMemE(int x1,int y1,int x2,int y2,string pic_info,string delta_color,double sim,int dir) + { + return FindPicMemE(_dm,x1, y1, x2, y2, pic_info, delta_color, sim,dir); + } + + public string AppendPicAddr(string pic_info,int addr,int size) + { + return AppendPicAddr(_dm,pic_info, addr, size); + } + + public int WriteFile(string file_,string content) + { + return WriteFile(_dm,file_, content); + } + + public int Stop(int id) + { + return Stop(_dm,id); + } + + public int SetDictMem(int index,int addr,int size) + { + return SetDictMem(_dm,index, addr, size); + } + + public string GetNetTimeSafe(){ + return GetNetTimeSafe(_dm); + } + + public int ForceUnBindWindow(int hwnd) + { + return ForceUnBindWindow(_dm,hwnd); + } + + public string ReadIniPwd(string section,string key,string file_,string pwd) + { + return ReadIniPwd(_dm,section, key, file_, pwd); + } + + public int WriteIniPwd(string section,string key,string v,string file_,string pwd) + { + return WriteIniPwd(_dm,section, key, v, file_, pwd); + } + + public int DecodeFile(string file_,string pwd) + { + return DecodeFile(_dm,file_, pwd); + } + + public int KeyDownChar(string key_str) + { + return KeyDownChar(_dm,key_str); + } + + public int KeyUpChar(string key_str) + { + return KeyUpChar(_dm,key_str); + } + + public int KeyPressChar(string key_str) + { + return KeyPressChar(_dm,key_str); + } + + public int KeyPressStr(string key_str,int delay) + { + return KeyPressStr(_dm,key_str, delay); + } + + public int EnableKeypadPatch(int en) + { + return EnableKeypadPatch(_dm,en); + } + + public int EnableKeypadSync(int en,int time_out) + { + return EnableKeypadSync(_dm,en, time_out); + } + + public int EnableMouseSync(int en,int time_out) + { + return EnableMouseSync(_dm,en, time_out); + } + + public int DmGuard(int en,string type_) + { + return DmGuard(_dm,en, type_); + } + + public int FaqCaptureFromFile(int x1,int y1,int x2,int y2,string file_,int quality) + { + return FaqCaptureFromFile(_dm,x1, y1, x2, y2, file_, quality); + } + + public string FindIntEx(int hwnd,string addr_range,int int_value_min,int int_value_max,int type_,int step,int multi_thread,int mode) + { + return FindIntEx(_dm,hwnd, addr_range, int_value_min, int_value_max, type_, step, multi_thread, mode); + } + + public string FindFloatEx(int hwnd,string addr_range,Single float_value_min,Single float_value_max,int step,int multi_thread,int mode) + { + return FindFloatEx(_dm,hwnd, addr_range, float_value_min, float_value_max, step, multi_thread, mode); + } + + public string FindDoubleEx(int hwnd,string addr_range,double double_value_min,double double_value_max,int step,int multi_thread,int mode) + { + return FindDoubleEx(_dm,hwnd, addr_range, double_value_min, double_value_max, step, multi_thread, mode); + } + + public string FindStringEx(int hwnd,string addr_range,string string_value,int type_,int step,int multi_thread,int mode) + { + return FindStringEx(_dm,hwnd, addr_range, string_value, type_, step, multi_thread, mode); + } + + public string FindDataEx(int hwnd,string addr_range,string data,int step,int multi_thread,int mode) + { + return FindDataEx(_dm,hwnd, addr_range, data, step, multi_thread, mode); + } + + public int EnableRealMouse(int en,int mousedelay,int mousestep) + { + return EnableRealMouse(_dm,en, mousedelay, mousestep); + } + + public int EnableRealKeypad(int en) + { + return EnableRealKeypad(_dm,en); + } + + public int SendStringIme(string str) + { + return SendStringIme(_dm,str); + } + + public int FoobarDrawLine(int hwnd,int x1,int y1,int x2,int y2,string color,int style,int width) + { + return FoobarDrawLine(_dm,hwnd, x1, y1, x2, y2, color, style, width); + } + + public string FindStrEx(int x1,int y1,int x2,int y2,string str,string color,double sim) + { + return FindStrEx(_dm,x1, y1, x2, y2, str, color, sim); + } + + public int IsBind(int hwnd) + { + return IsBind(_dm,hwnd); + } + + public int SetDisplayDelay(int t) + { + return SetDisplayDelay(_dm,t); + } + + public int GetDmCount(){ + return GetDmCount(_dm); + } + + public int DisableScreenSave(){ + return DisableScreenSave(_dm); + } + + public int DisablePowerSave(){ + return DisablePowerSave(_dm); + } + + public int SetMemoryHwndAsProcessId(int en) + { + return SetMemoryHwndAsProcessId(_dm,en); + } + + public int FindShape(int x1,int y1,int x2,int y2,string offset_color,double sim,int dir, out object x, out object y) + { + return FindShape(_dm,x1, y1, x2, y2, offset_color, sim, dir, out x, out y); + } + + public string FindShapeE(int x1,int y1,int x2,int y2,string offset_color,double sim,int dir) + { + return FindShapeE(_dm,x1, y1, x2, y2, offset_color, sim, dir); + } + + public string FindShapeEx(int x1,int y1,int x2,int y2,string offset_color,double sim,int dir) + { + return FindShapeEx(_dm,x1, y1, x2, y2, offset_color, sim, dir); + } + + public string FindStrS(int x1,int y1,int x2,int y2,string str,string color,double sim, out object x, out object y) + { + return FindStrS(_dm,x1, y1, x2, y2, str, color, sim, out x, out y); + } + + public string FindStrExS(int x1,int y1,int x2,int y2,string str,string color,double sim) + { + return FindStrExS(_dm,x1, y1, x2, y2, str, color, sim); + } + + public string FindStrFastS(int x1,int y1,int x2,int y2,string str,string color,double sim, out object x, out object y) + { + return FindStrFastS(_dm,x1, y1, x2, y2, str, color, sim, out x, out y); + } + + public string FindStrFastExS(int x1,int y1,int x2,int y2,string str,string color,double sim) + { + return FindStrFastExS(_dm,x1, y1, x2, y2, str, color, sim); + } + + public string FindPicS(int x1,int y1,int x2,int y2,string pic_name,string delta_color,double sim,int dir, out object x, out object y) + { + return FindPicS(_dm,x1, y1, x2, y2, pic_name, delta_color, sim, dir, out x, out y); + } + + public string FindPicExS(int x1,int y1,int x2,int y2,string pic_name,string delta_color,double sim,int dir) + { + return FindPicExS(_dm,x1, y1, x2, y2, pic_name, delta_color, sim, dir); + } + + public int ClearDict(int index) + { + return ClearDict(_dm,index); + } + + public string GetMachineCodeNoMac(){ + return GetMachineCodeNoMac(_dm); + } + + public int GetClientRect(int hwnd, out object x1, out object y1, out object x2, out object y2) + { + return GetClientRect(_dm,hwnd, out x1, out y1, out x2, out y2); + } + + public int EnableFakeActive(int en) + { + return EnableFakeActive(_dm,en); + } + + public int GetScreenDataBmp(int x1,int y1,int x2,int y2, out object data, out object size) + { + return GetScreenDataBmp(_dm,x1, y1, x2, y2, out data, out size); + } + + public int EncodeFile(string file_,string pwd) + { + return EncodeFile(_dm,file_, pwd); + } + + public string GetCursorShapeEx(int type_) + { + return GetCursorShapeEx(_dm,type_); + } + + public int FaqCancel(){ + return FaqCancel(_dm); + } + + public string IntToData(int int_value,int type_) + { + return IntToData(_dm,int_value, type_); + } + + public string FloatToData(Single float_value) + { + return FloatToData(_dm,float_value); + } + + public string DoubleToData(double double_value) + { + return DoubleToData(_dm,double_value); + } + + public string StringToData(string string_value,int type_) + { + return StringToData(_dm,string_value, type_); + } + + public int SetMemoryFindResultToFile(string file_) + { + return SetMemoryFindResultToFile(_dm,file_); + } + + public int EnableBind(int en) + { + return EnableBind(_dm,en); + } + + public int SetSimMode(int mode) + { + return SetSimMode(_dm,mode); + } + + public int LockMouseRect(int x1,int y1,int x2,int y2) + { + return LockMouseRect(_dm,x1, y1, x2, y2); + } + + public int SendPaste(int hwnd) + { + return SendPaste(_dm,hwnd); + } + + public int IsDisplayDead(int x1,int y1,int x2,int y2,int t) + { + return IsDisplayDead(_dm,x1, y1, x2, y2, t); + } + + public int GetKeyState(int vk) + { + return GetKeyState(_dm,vk); + } + + public int CopyFile(string src_file,string dst_file,int over) + { + return CopyFile(_dm,src_file, dst_file, over); + } + + public int IsFileExist(string file_) + { + return IsFileExist(_dm,file_); + } + + public int DeleteFile(string file_) + { + return DeleteFile(_dm,file_); + } + + public int MoveFile(string src_file,string dst_file) + { + return MoveFile(_dm,src_file, dst_file); + } + + public int CreateFolder(string folder_name) + { + return CreateFolder(_dm,folder_name); + } + + public int DeleteFolder(string folder_name) + { + return DeleteFolder(_dm,folder_name); + } + + public int GetFileLength(string file_) + { + return GetFileLength(_dm,file_); + } + + public string ReadFile(string file_) + { + return ReadFile(_dm,file_); + } + + public int WaitKey(int key_code,int time_out) + { + return WaitKey(_dm,key_code, time_out); + } + + public int DeleteIni(string section,string key,string file_) + { + return DeleteIni(_dm,section, key, file_); + } + + public int DeleteIniPwd(string section,string key,string file_,string pwd) + { + return DeleteIniPwd(_dm,section, key, file_, pwd); + } + + public int EnableSpeedDx(int en) + { + return EnableSpeedDx(_dm,en); + } + + public int EnableIme(int en) + { + return EnableIme(_dm,en); + } + + public int Reg(string code,string Ver) + { + return Reg(_dm,code, Ver); + } + + public string SelectFile(){ + return SelectFile(_dm); + } + + public string SelectDirectory(){ + return SelectDirectory(_dm); + } + + public int LockDisplay(int lock1) + { + return LockDisplay(_dm,lock1); + } + + public int FoobarSetSave(int hwnd,string file_,int en,string header) + { + return FoobarSetSave(_dm,hwnd, file_, en, header); + } + + public string EnumWindowSuper(string spec1,int flag1,int type1,string spec2,int flag2,int type2,int sort) + { + return EnumWindowSuper(_dm,spec1, flag1, type1, spec2, flag2, type2, sort); + } + + public int DownloadFile(string url,string save_file,int timeout) + { + return DownloadFile(_dm,url, save_file, timeout); + } + + public int EnableKeypadMsg(int en) + { + return EnableKeypadMsg(_dm,en); + } + + public int EnableMouseMsg(int en) + { + return EnableMouseMsg(_dm,en); + } + + public int RegNoMac(string code,string Ver) + { + return RegNoMac(_dm,code, Ver); + } + + public int RegExNoMac(string code,string Ver,string ip) + { + return RegExNoMac(_dm,code, Ver, ip); + } + + public int SetEnumWindowDelay(int delay) + { + return SetEnumWindowDelay(_dm,delay); + } + + public int FindMulColor(int x1,int y1,int x2,int y2,string color,double sim) + { + return FindMulColor(_dm,x1, y1, x2, y2, color, sim); + } + + public string GetDict(int index,int font_index) + { + return GetDict(_dm,index, font_index); + } + + + + + + #region 继承释放接口方法 + public void Dispose() + { + //必须为true + Dispose(true); + //通知垃圾回收机制不再调用终结器(析构器) + GC.SuppressFinalize(this); + } + + public void Close() + { + Dispose(); + } + + ~CDmSoft() + { + //必须为false + Dispose(false); + } + + protected virtual void Dispose(bool disposing) + { + if (disposed) + { + return; + } + if (disposing) + { + // 清理托管资源 + //if (managedResource != null) + //{ + // managedResource.Dispose(); + // managedResource = null; + //} + } + // 清理非托管资源 + if (_dm != IntPtr.Zero) + { + UnBindWindow(); + _dm = IntPtr.Zero; + int ret = FreeDM(); + } + //让类型知道自己已经被释放 + disposed = true; + } + #endregion + } +} diff --git a/基础类库/HuizhongLibrary/Camera.cs b/基础类库/HuizhongLibrary/Camera.cs new file mode 100644 index 0000000..79c72de --- /dev/null +++ b/基础类库/HuizhongLibrary/Camera.cs @@ -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 + + /// graph builder interface. + private IFilterGraph2 m_FilterGraph = null; + private IMediaControl m_mediaCtrl = null; + + /// so we can wait for the async job to finish + private ManualResetEvent m_PictureReady = null; + + /// Set by async routine when it captures an image + private volatile bool m_bGotOne = false; + + /// Indicates the status of the graph + private bool m_bRunning = false; + + /// Dimensions of the image, calculated once in constructor. + 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 + + /// Use capture device zero, default frame rate and size + public Camera() + { + _Capture(0, 0, 0, 0); + } + /// Use specified capture device, default frame rate and size + public Camera(int iDeviceNum) + { + _Capture(iDeviceNum, 0, 0, 0); + } + /// Use specified capture device, specified frame rate and default size + public Camera(int iDeviceNum, int iFrameRate) + { + _Capture(iDeviceNum, iFrameRate, 0, 0); + } + /// Use specified capture device, specified frame rate and size + 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 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 + + + + /// release everything. + 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; + } + } + /// capture the next image + 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; + } + } + + /// build the capture graph for grabber. + 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; + } + + /// Shut down capture + 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; + } + } + + /// sample callback, NOT USED. + 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; + } + + /// buffer callback, COULD BE FROM FOREIGN THREAD. + 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; + } + } +} diff --git a/基础类库/HuizhongLibrary/Config.cs b/基础类库/HuizhongLibrary/Config.cs new file mode 100644 index 0000000..96ee474 --- /dev/null +++ b/基础类库/HuizhongLibrary/Config.cs @@ -0,0 +1,170 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace HuizhongLibrary.Common.Configuration +{ + public class Config + { + private string m_Key; + /// + /// 键 + /// + public string Key + { + get { return m_Key; } + set { m_Key = value; } + } + private string m_Value; + /// + /// 值 + /// + public string Value + { + get { return m_Value; } + set { m_Value = value; } + } + private string m_Namespace; + /// + /// 命名空间 + /// + public string Namespace + { + get { return m_Namespace; } + set { m_Namespace = value; } + } + } + + public class ConfigCollection:IList + { + public List items = new List(); + + #region IList 成员 + + 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 成员 + + 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 成员 + + public IEnumerator GetEnumerator() + { + return items.GetEnumerator(); + } + + #endregion + + #region IEnumerable 成员 + + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() + { + return items.GetEnumerator(); + } + + #endregion + } + + + +} diff --git a/基础类库/HuizhongLibrary/ConfigurationSourceSection.cs b/基础类库/HuizhongLibrary/ConfigurationSourceSection.cs new file mode 100644 index 0000000..fc74cbd --- /dev/null +++ b/基础类库/HuizhongLibrary/ConfigurationSourceSection.cs @@ -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 读取数据库连接 + /// + /// 读取数据库连接 + /// + /// 属性名称 + 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 读取数据库连接 + /// + /// 读取数据库连接 + /// + /// 属性名称 + 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配置文件-属性值 + /// + /// 返回指点节点指点属性的值,AttributeName属性名称 + /// + /// 配置文件路径 + /// 属性名称 + 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配置文件 + /// + ///AttributeName属性名称,AttributeValue属性值 + /// + /// 属性名称 + /// 属性值 + /// 是否加密 + 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 查询服务器上所有数据库 + /// + ///查询服务器上所有数据库 + /// + 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 查询数据库中所有表名 + /// + ///查询数据库中所有表名 + /// + 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 查询数据库中所有表名 + /// + ///查询数据库中所有表名 + /// + 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 查询数据库中所有视图名 + /// + ///查询数据库中所有视图名 + /// + 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配置文件-属性值" + /// + /// 返回指点节点指点属性的值,AttributeName属性名称 + /// + /// 配置文件路径 + /// 属性名称 + 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配置文件" + /// + ///AttributeName属性名称,AttributeValue属性值 + /// + /// 属性名称 + /// 属性值 + /// 是否加密 + 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 + + + } +} diff --git a/基础类库/HuizhongLibrary/CustomIO.cs b/基础类库/HuizhongLibrary/CustomIO.cs new file mode 100644 index 0000000..090630b --- /dev/null +++ b/基础类库/HuizhongLibrary/CustomIO.cs @@ -0,0 +1,4180 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Windows.Forms; +using System.Drawing; +using System.IO; +using System.Diagnostics; +using System.Data; +using System.IO.Compression; +using Microsoft.Win32; +using System.Security.Cryptography; +using System.Web; +using System.Management; +using System.Xml.Linq; +using System.ServiceProcess; +using System.Configuration.Install; +using System.Collections; +using System.Net; +using System.Text.RegularExpressions; +using System.Reflection; +using System.Drawing.Imaging; +using System.Drawing.Drawing2D; +using System.Xml; +using HuizhongLibrary.Data; +using System.Data.Common; +using HuizhongLibrary.Log; +using HuizhongLibrary.Models; +using System.Threading; +using System.Globalization; +using System.Runtime.Serialization.Formatters.Binary; +using System.Xml.Serialization; +using System.Security.Cryptography.X509Certificates; +using System.Net.Security; +using O2S.Components.PDFRender4NET; +using HuizhongLibrary.Common.Configuration; +using System.Linq; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using Org.BouncyCastle.Crypto.Parameters; +using Org.BouncyCastle.Security; + +namespace HuizhongLibrary +{ + public class CustomIO + { + #region ͼƬתbate,MemoryStreamʾ + public static byte[] GetPhoto(string filePath) + { + if (File.Exists(filePath) == false) return null; + string ext = Path.GetExtension(filePath).ToLower(); + Bitmap bmp = new Bitmap(filePath); + MemoryStream ms = new MemoryStream(); + if (ext == ".jpg") + { + bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); + } + else + { + bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png); + } + bmp.Dispose(); + byte[] photo = new byte[ms.Length - 1]; + ms.Position = 0; + ms.Read(photo, 0, photo.Length - 1); + ms.Close(); + return photo; + } + #endregion + #region bateתͼƬ,MemoryStreamʾ + public static Bitmap GetPhoto(byte[] images) + { + if (images == null) return null; + MemoryStream ms = new MemoryStream(); + ms.Write(images, 0, images.Length); + Bitmap bmp = new Bitmap(ms); + ms.Close(); + return bmp; + } + #endregion + + #region ȡͼƬ + public static Bitmap GetBitmap(string FilePath) + { + Bitmap bmp = new Bitmap(FilePath); + Bitmap bmp2 = null; + //if (bmp.PixelFormat == System.Drawing.Imaging.PixelFormat.Undefined || bmp.PixelFormat == System.Drawing.Imaging.PixelFormat.DontCare || bmp.PixelFormat == System.Drawing.Imaging.PixelFormat.Format16bppArgb1555 || bmp.PixelFormat == System.Drawing.Imaging.PixelFormat.Format1bppIndexed || bmp.PixelFormat == System.Drawing.Imaging.PixelFormat.Format4bppIndexed || bmp.PixelFormat == System.Drawing.Imaging.PixelFormat.Format8bppIndexed) + //{ + // bmp2 = new Bitmap(bmp.Width, bmp.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); + //} + //else + //{ + // bmp2 = new Bitmap(bmp.Width, bmp.Height, bmp.PixelFormat); + //} + bmp2 = new Bitmap(bmp.Width, bmp.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); + bmp2.SetResolution(bmp.HorizontalResolution, bmp.VerticalResolution); + Graphics gp = Graphics.FromImage(bmp2); + 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; + gp.DrawImage(bmp, 0, 0); + gp.Dispose(); + bmp.Dispose(); + return bmp2; + } + #endregion + #region ȡͼƬ + public static Bitmap GetBitmap(string FilePath, int Width, int Height) + { + if (FilePath.IndexOf(":") == -1) FilePath = AppDomain.CurrentDomain.BaseDirectory + FilePath; + Bitmap bmp = new Bitmap(FilePath); + Bitmap bmp2 = null; + bmp2 = new Bitmap(Width, Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); + bmp2.SetResolution(bmp.HorizontalResolution, bmp.VerticalResolution); + Graphics gp = Graphics.FromImage(bmp2); + 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; + gp.DrawImage(bmp, 0, 0, Width, Height); + gp.Dispose(); + bmp.Dispose(); + return bmp2; + } + #endregion + #region ͼƬתbyte + public static byte[] GetPhoto(Bitmap bmp) + { + MemoryStream ms = new MemoryStream(); + bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); + byte[] photo = new byte[ms.Length - 1]; + ms.Position = 0; + ms.Read(photo, 0, photo.Length - 1); + ms.Close(); + return photo; + } + #endregion + #region ͼƬתbyte + public static byte[] GetPhoto(Bitmap bmp, System.Drawing.Imaging.ImageFormat fs) + { + MemoryStream ms = new MemoryStream(); + bmp.Save(ms, fs); + byte[] photo = new byte[ms.Length - 1]; + ms.Position = 0; + ms.Read(photo, 0, photo.Length - 1); + ms.Close(); + return photo; + } + #endregion + + #region ͼƬתbate,MemoryStreamʾ + public static byte[] GetPhoto(System.Drawing.Image img) + { + Bitmap bmp = new Bitmap(img); + MemoryStream ms = new MemoryStream(); + bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png); + bmp.Dispose(); + byte[] photo = new byte[ms.Length - 1]; + ms.Position = 0; + ms.Read(photo, 0, photo.Length - 1); + ms.Close(); + return photo; + } + #endregion + + #region ͼƬѹ_ + public static bool ImageCompress(string sFile, string outPath, int width, int height, int flag) + { + System.Drawing.Image iSource = System.Drawing.Image.FromFile(sFile); + System.Drawing.Image targetImg = new System.Drawing.Bitmap(width, height); + using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(targetImg)) + { + g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; + g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; + g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; + g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; + g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; + g.DrawImage(iSource, new System.Drawing.Rectangle(0, 0, width, height), new System.Drawing.Rectangle(0, 0, iSource.Width, iSource.Height), System.Drawing.GraphicsUnit.Pixel); + g.Dispose(); + } + if (flag == 100) + { + targetImg.Save(outPath, ImageFormat.Png); + iSource.Dispose(); + targetImg.Dispose(); + return true; + } + iSource.Dispose(); + //ImageFormat tFormat = iSource.RawFormat; + //´ΪͼƬʱѹ + EncoderParameters ep = new EncoderParameters(); + long[] qy = new long[1]; + qy[0] = flag;//ѹı1-100 + EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy); + ep.Param[0] = eParam; + try + { + ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders(); + ImageCodecInfo PngICIinfo = null; + for (int x = 0; x < arrayICI.Length; x++) + { + if (arrayICI[x].FormatDescription.Equals("Png")) + { + PngICIinfo = arrayICI[x]; + break; + } + } + if (PngICIinfo != null) + { + targetImg.Save(outPath, PngICIinfo, ep);//dFileѹ· + } + else + { + targetImg.Save(outPath, ImageFormat.Png); + } + return true; + } + catch + { + return false; + } + finally + { + targetImg.Dispose(); + } + } + #endregion + #region ͼƬѹ_ + public static bool ImageCompress2(string sFile, string outPath, int width, int height, int flag) + { + System.Drawing.Image iSource = System.Drawing.Image.FromFile(sFile); + double ratio = 0d; + double myThumbWidth = 0d; + double myThumbHeight = 0d; + int xx = 0; + int yy = 0; + Bitmap targetImg; + if ((iSource.Width / Convert.ToDouble(width)) > (iSource.Height / + Convert.ToDouble(height))) + ratio = Convert.ToDouble(iSource.Width) / Convert.ToDouble(width); + else + ratio = Convert.ToDouble(iSource.Height) / Convert.ToDouble(height); + myThumbHeight = Math.Ceiling(iSource.Height / ratio); + myThumbWidth = Math.Ceiling(iSource.Width / ratio); + Size thumbSize = new Size(width, height); + targetImg = new Bitmap(width, height); + xx = (width - thumbSize.Width) / 2; + yy = (height - thumbSize.Height); + System.Drawing.Graphics g = Graphics.FromImage(targetImg); + g.SmoothingMode = SmoothingMode.HighQuality; + g.InterpolationMode = InterpolationMode.HighQualityBicubic; + g.PixelOffsetMode = PixelOffsetMode.HighQuality; + Rectangle rect = new Rectangle(xx, yy, thumbSize.Width, thumbSize.Height); + g.DrawImage(iSource, rect, 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel); + + if (flag == 100) + { + targetImg.Save(outPath, ImageFormat.Png); + iSource.Dispose(); + targetImg.Dispose(); + return true; + } + iSource.Dispose(); + //ImageFormat tFormat = iSource.RawFormat; + //´ΪͼƬʱѹ + EncoderParameters ep = new EncoderParameters(); + long[] qy = new long[1]; + qy[0] = flag;//ѹı1-100 + EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy); + ep.Param[0] = eParam; + try + { + ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders(); + ImageCodecInfo PngICIinfo = null; + for (int x = 0; x < arrayICI.Length; x++) + { + if (arrayICI[x].FormatDescription.Equals("Png")) + { + PngICIinfo = arrayICI[x]; + break; + } + } + if (PngICIinfo != null) + { + targetImg.Save(outPath, PngICIinfo, ep);//dFileѹ· + } + else + { + targetImg.Save(outPath, ImageFormat.Png); + } + return true; + } + catch + { + return false; + } + finally + { + targetImg.Dispose(); + } + } + #endregion + #region ͼƬѹ_ֻѹ + public static bool ImageCompress3(string sFile, string outPath, int flag) + { + System.Drawing.Image iSource = System.Drawing.Image.FromFile(sFile); + ImageFormat tFormat = iSource.RawFormat; + //´ΪͼƬʱѹ + EncoderParameters ep = new EncoderParameters(); + long[] qy = new long[1]; + qy[0] = flag;//ѹı1-100 + EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy); + ep.Param[0] = eParam; + try + { + ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders(); + ImageCodecInfo PngICIinfo = null; + for (int x = 0; x < arrayICI.Length; x++) + { + if (arrayICI[x].FormatDescription.Equals("Png")) + { + PngICIinfo = arrayICI[x]; + break; + } + } + if (PngICIinfo != null) + { + iSource.Save(outPath, PngICIinfo, ep);//dFileѹ· + } + else + { + iSource.Save(outPath, tFormat); + } + return true; + } + catch + { + return false; + } + finally + { + iSource.Dispose(); + iSource.Dispose(); + } + } + #endregion + + #region ͼƬѹ_ + public static Image ImageCompress(Image iSource, int width, int height, int flag) + { + System.Drawing.Image targetImg = new System.Drawing.Bitmap(width, height); + using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(targetImg)) + { + g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; + g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; + g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; + g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; + g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; + g.DrawImage(iSource, new System.Drawing.Rectangle(0, 0, width, height), new System.Drawing.Rectangle(0, 0, iSource.Width, iSource.Height), System.Drawing.GraphicsUnit.Pixel); + g.Dispose(); + } + if (flag == 100) + { + //iSource.Dispose(); + return targetImg; + } + //iSource.Dispose(); + //ImageFormat tFormat = iSource.RawFormat; + //´ΪͼƬʱѹ + EncoderParameters ep = new EncoderParameters(); + long[] qy = new long[1]; + qy[0] = flag;//ѹı1-100 + EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy); + ep.Param[0] = eParam; + try + { + ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders(); + ImageCodecInfo PngICIinfo = null; + for (int x = 0; x < arrayICI.Length; x++) + { + if (arrayICI[x].FormatDescription.Equals("Png")) + { + PngICIinfo = arrayICI[x]; + break; + } + } + MemoryStream ms = new MemoryStream(); + if (PngICIinfo != null) + { + targetImg.Save(ms, PngICIinfo, ep);//dFileѹ· + } + else + { + targetImg.Save(ms, ImageFormat.Png); + } + Bitmap bmp = new Bitmap(ms); + return bmp; + } + catch + { + return null; + } + finally + { + targetImg.Dispose(); + } + } + #endregion + #region ͼƬѹ_ѹ + public static Image ImageRateCompress(Image iSource, int PixelRate, int flag, string imgtype) + { + //imgtype=PNG,JPEG + double rate = Convert.ToDouble(PixelRate) / 100; + int Width = Convert.ToInt32(Convert.ToDouble(iSource.Width) * rate); + int Height = Convert.ToInt32(Convert.ToDouble(iSource.Height) * rate); + System.Drawing.Image targetImg = new System.Drawing.Bitmap(Width, Height); + using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(targetImg)) + { + g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; + g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; + g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; + g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; + g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; + g.DrawImage(iSource, new System.Drawing.Rectangle(0, 0, Width, Height), new System.Drawing.Rectangle(0, 0, iSource.Width, iSource.Height), System.Drawing.GraphicsUnit.Pixel); + g.Dispose(); + } + if (flag == 100) + { + //iSource.Dispose(); + return targetImg; + } + //iSource.Dispose(); + //ImageFormat tFormat = iSource.RawFormat; + //´ΪͼƬʱѹ + EncoderParameters ep = new EncoderParameters(); + long[] qy = new long[1]; + qy[0] = flag;//ѹı1-100 + EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy); + ep.Param[0] = eParam; + try + { + ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders(); + ImageCodecInfo PngICIinfo = null; + for (int x = 0; x < arrayICI.Length; x++) + { + if (arrayICI[x].FormatDescription.Equals(imgtype)) + { + PngICIinfo = arrayICI[x]; + break; + } + } + MemoryStream ms = new MemoryStream(); + if (PngICIinfo != null) + { + targetImg.Save(ms, PngICIinfo, ep);//dFileѹ· + } + else + { + targetImg.Save(ms, ImageFormat.Png); + } + Bitmap bmp = new Bitmap(ms); + return bmp; + } + catch + { + return null; + } + finally + { + targetImg.Dispose(); + } + } + #endregion + + #region ļǷͼƬ + public static bool IsImage(string filename) + { + var extStart = filename.LastIndexOf("."); + var ext = filename.Substring(extStart).ToUpper(); + if (ext != ".BMP" && ext != ".PNG" && ext != ".GIF" && ext != ".JPG" && ext != ".JPEG") + { + return false; + } + else + { + return true; + } + } + #endregion + + #region ļͼƬ + public static string GetFileCheckCode(byte[] bytes) + { + System.Security.Cryptography.MD5CryptoServiceProvider oMD5Hasher = new System.Security.Cryptography.MD5CryptoServiceProvider(); + byte[] HeaderHash = oMD5Hasher.ComputeHash(bytes); + string CheckCode = ""; + foreach (byte item in HeaderHash) + { + CheckCode += item.ToString("x2"); + } + return CheckCode; + } + #endregion + + #region ͼƬť + public static void CreateImageButton(string BackgroundFilePath, string SaveFilePath, string ButtonText, string FontColor, string FontName, float FontSize) + { + if (File.Exists(SaveFilePath) == true) return; + Bitmap BackgroundImage = CustomIO.GetBitmap(BackgroundFilePath); + 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; + FontStyle style = FontStyle.Regular; + style = style | FontStyle.Bold; + Font f = new Font(FontName, FontSize, style); + TextFormatFlags flags = TextFormatFlags.TextBoxControl | TextFormatFlags.WordBreak | TextFormatFlags.NoPadding; + flags = flags | TextFormatFlags.HorizontalCenter; + flags = flags | TextFormatFlags.VerticalCenter; + Color TextColor = Color.FromName(FontColor); + Rectangle rect = new Rectangle(0, 0, BackgroundImage.Width, BackgroundImage.Height); + TextRenderer.DrawText(gp, ButtonText, f, rect, TextColor, flags); + BackgroundImage.Save(SaveFilePath, ImageFormat.Png); + gp.Dispose(); + BackgroundImage = null; + gp = null; + } + #endregion + #region ͼƬť + public static Bitmap CreateImageButton(int Width, int Height, string ButtonText, string FontColor, string FontName, float FontSize) + { + Bitmap BackgroundImage = new Bitmap(Width, Height); + 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; + FontStyle style = FontStyle.Regular; + style = style | FontStyle.Bold; + Font f = new Font(FontName, FontSize, style); + TextFormatFlags flags = TextFormatFlags.TextBoxControl | TextFormatFlags.WordBreak | TextFormatFlags.NoPadding; + flags = flags | TextFormatFlags.HorizontalCenter; + flags = flags | TextFormatFlags.VerticalCenter; + Color TextColor = Color.FromName(FontColor); + Rectangle rect = new Rectangle(0, 0, BackgroundImage.Width, BackgroundImage.Height); + TextRenderer.DrawText(gp, ButtonText, f, rect, TextColor, flags); + gp.Dispose(); + gp = null; + return BackgroundImage; + } + #endregion + #region ͼƬǩ + public static Bitmap CreateSignImage(int Width, int Height, string SignText, string FontColor, string FontName, float FontSize) + { + if (Width == 0) Width = 100; + if (Height == 0) Height = 20; + if (FontSize == 0) FontSize = 15; + if (FontColor == "") FontColor = "Red"; + if (FontName == "") FontName = "п"; + Bitmap BackgroundImage = new Bitmap(Width, Height); + Graphics gp = Graphics.FromImage(BackgroundImage); + gp.Clear(Color.Transparent); + 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; + FontStyle style = FontStyle.Regular; + style = style | FontStyle.Bold; + Font f = new Font(FontName, FontSize, style); + TextFormatFlags flags = TextFormatFlags.TextBoxControl | TextFormatFlags.WordBreak | TextFormatFlags.NoPadding; + flags = flags | TextFormatFlags.HorizontalCenter; + flags = flags | TextFormatFlags.VerticalCenter; + Color TextColor = Color.FromName(FontColor); + Rectangle rect = new Rectangle(0, 0, BackgroundImage.Width, BackgroundImage.Height); + TextRenderer.DrawText(gp, SignText, f, rect, TextColor, flags); + gp.Dispose(); + gp = null; + return BackgroundImage; + } + #endregion + + #region ȡĻDPI + public static PointF GetScreenDpi() + { + float dpiX = 0; + float dpiY = 0; + using (System.Drawing.Graphics graphics = System.Drawing.Graphics.FromHwnd(IntPtr.Zero)) + { + dpiX = graphics.DpiX; + dpiY = graphics.DpiY; + } + PointF p = new PointF(dpiX, dpiY); + return p; + } + #endregion + #region ת + public static float PixelToMillimeters(float px, float fDPI) + { + //תףpx * 25.4 / dpi + return (float)Math.Round(((px * 25.4f) / fDPI), 2); ; + } + #endregion + #region ת + public static float MillimetersToPixel(float mm, float fDPI) + { + //תأmm * dpi / 25.4 + return (float)Math.Round((mm * fDPI / 25.4f), 2); + } + #endregion + + #region ױ + public static System.Drawing.Bitmap CreateHorizontalRuler(int Width) + { + int Heigth = 15; + System.Drawing.PointF dpi = GetScreenDpi(); + int imgWidth = Convert.ToInt32(MillimetersToPixel(Width, dpi.X)); + int imgHeigth = Convert.ToInt32(MillimetersToPixel(Heigth, dpi.Y)); + System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(imgWidth, imgHeigth); + System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp); + g.FillRectangle(Brushes.White, 0, 0, imgWidth, imgHeigth); + for (int i = 1; i <= Width; i++) + { + int x = Convert.ToInt32(MillimetersToPixel(i, dpi.X)); + int y = imgHeigth - 15; + if (Math.IEEERemainder(i, 10) == 0) + { + y = imgHeigth - 25; + if (i <= Width) + { + string title = Convert.ToInt32(i / 10).ToString(); + int xx = x - 7; + if (title.Length > 1) xx = x - 11; + if (i < Width) g.DrawString(title, new System.Drawing.Font("", 12), System.Drawing.Brushes.Black, xx, y - 18); + } + } + g.DrawLine(System.Drawing.Pens.Black, x, imgHeigth, x, y); + } + return bmp; + } + #endregion + #region ױ + public static System.Drawing.Bitmap CreateVerticalRuler(int Heigth) + { + int Width = 15; + System.Drawing.PointF dpi = GetScreenDpi(); + int imgWidth = Convert.ToInt32(MillimetersToPixel(Width, dpi.X)); + int imgHeigth = Convert.ToInt32(MillimetersToPixel(Heigth, dpi.Y)); + System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(imgWidth, imgHeigth); + System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp); + g.FillRectangle(Brushes.White, 0, 0, imgWidth, imgHeigth); + //g.DrawLine(System.Drawing.Pens.Black, imgWidth - 15, 20, imgWidth, 20); + for (int i = 1; i <= Heigth; i++) + { + int x = imgWidth - 15; + int y = Convert.ToInt32(MillimetersToPixel(i, dpi.X)); + if (Math.IEEERemainder(i, 10) == 0) + { + x = imgWidth - 25; + if (i <= Heigth) + { + string title = Convert.ToInt32(i / 10).ToString(); + int yy = y - 7; + if (title.Length > 1) yy = y - 11; + if (i < Heigth) g.DrawString(title, new System.Drawing.Font("", 12), System.Drawing.Brushes.Black, x - 18, yy); + } + } + g.DrawLine(System.Drawing.Pens.Black, x, y, imgWidth, y); + } + return bmp; + } + #endregion + #region ͼƬ + public static void SaveImage(string outPath, Bitmap bmp, int Quality) + { + EncoderParameters ep = new EncoderParameters(); + long[] qy = new long[1]; + qy[0] = Quality;//ѹı1-100 + EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy); + ep.Param[0] = eParam; + + ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders(); + ImageCodecInfo PngICIinfo = null; + for (int x = 0; x < arrayICI.Length; x++) + { + if (arrayICI[x].FormatDescription.Equals("Png")) + { + PngICIinfo = arrayICI[x]; + break; + } + } + if (PngICIinfo != null) + { + bmp.Save(outPath, PngICIinfo, ep);//dFileѹ· + } + else + { + bmp.Save(outPath, ImageFormat.Png); + } + } + #endregion + + #region ά + public static string CreateQrCode(string Url, int Width, int Height) + { + try + { + ZXing.Common.EncodingOptions options = new ZXing.QrCode.QrCodeEncodingOptions + { + DisableECI = true, + CharacterSet = "UTF-8", + Width = Width, + Height = Height, + Margin=0 + }; + ZXing.BarcodeWriter writer = new ZXing.BarcodeWriter(); + writer.Format = ZXing.BarcodeFormat.QR_CODE; + writer.Options = options; + Bitmap bitmap = writer.Write(Url); + string fileName = "ServerCookies/" + Guid.NewGuid().ToString() + ".jpg"; + string TempFilePath = AppDomain.CurrentDomain.BaseDirectory + fileName; + bitmap.Save(TempFilePath, ImageFormat.Png); + bitmap.Dispose(); + return fileName; + } + catch (Exception ex) + { + ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message); + } + //w:287 h:291 + return ""; + } + #endregion + #region ά + public static string CreateQrCode2(string Url, int Width, int Height, string FilePath) + { + try + { + ZXing.Common.EncodingOptions options = new ZXing.QrCode.QrCodeEncodingOptions + { + DisableECI = true, + CharacterSet = "UTF-8", + Margin = 0, + Width = 300, + Height = 300 + }; + ZXing.BarcodeWriter writer = new ZXing.BarcodeWriter(); + writer.Format = ZXing.BarcodeFormat.QR_CODE; + + writer.Options = options; + Bitmap bitmap = writer.Write(Url); + + + //string fileName = "ServerCookies/" + Guid.NewGuid().ToString() + ".jpg"; + string TempFilePath = AppDomain.CurrentDomain.BaseDirectory + "attached/code/" + FilePath; + if (File.Exists(TempFilePath)) + { + return "attached/code/" + FilePath; + + } + string DirectoryName = System.AppDomain.CurrentDomain.BaseDirectory + "attached/code"; + + if (Directory.Exists(DirectoryName) == false) + Directory.CreateDirectory(DirectoryName); + + bitmap.Save(TempFilePath, ImageFormat.Png); + bitmap.Dispose(); + return "attached/code/" + FilePath; + } + catch (Exception ex) + { + ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message); + return ""; + } + //w:287 h:291 + return ""; + } + #endregion + #region ĸ + public static string CreateRandomLetter(int letter) + { + string str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < letter; i++) + { + sb.Append(str[new Random(Guid.NewGuid().GetHashCode()).Next(0, str.Length - 1)]); + } + return sb.ToString(); + } + #endregion + #region ַ + /// + ///ַ + /// + ///Ŀַij + ///Ƿ֣1=ĬΪ + ///ǷСдĸ1=ĬΪ + ///Ƿдĸ1=ĬΪ + ///Ƿַ1=ĬΪ + ///ҪԶֱַҪַб + ///ָȵַ + public static string GetRandomString(int length, bool useNum, bool useLow, bool useUpp, bool useSpe, string custom) + { + byte[] b = new byte[4]; + new System.Security.Cryptography.RNGCryptoServiceProvider().GetBytes(b); + Random r = new Random(BitConverter.ToInt32(b, 0)); + string s = null, str = custom; + if (useNum == true) { str += "0123456789"; } + if (useLow == true) { str += "abcdefghijklmnopqrstuvwxyz"; } + if (useUpp == true) { str += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; } + if (useSpe == true) { str += "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"; } + for (int i = 0; i < length; i++) + { + s += str.Substring(r.Next(0, str.Length - 1), 1); + } + return s; + } + #endregion + #region 滻һַ + public static string Replace(string source, string match, string replacement) + { + char[] sArr = source.ToCharArray(); + char[] mArr = match.ToCharArray(); + char[] rArr = replacement.ToCharArray(); + int idx = IndexOf(sArr, mArr); + if (idx == -1) + { + return source; + } + else + { + return new string(sArr.Take(idx).Concat(rArr).Concat(sArr.Skip(idx + mArr.Length)).ToArray()); + } + } + /// + /// ַһַƥλ + /// + /// Դַ + /// ƥַ + /// ƥλãδҵƥ򷵻-1 + private static int IndexOf(char[] source, char[] match) + { + int idx = -1; + for (int i = 0; i < source.Length - match.Length; i++) + { + if (source[i] == match[0]) + { + bool isMatch = true; + for (int j = 0; j < match.Length; j++) + { + if (source[i + j] != match[j]) + { + isMatch = false; + break; + } + } + if (isMatch) + { + idx = i; + break; + } + } + } + return idx; + } + #endregion + + #region ļתbate,MemoryStreamʾ + public static byte[] GetOffice(string filePath) + { + if (File.Exists(filePath) == false) return null; + FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read); + BinaryReader br = new BinaryReader(fs); + byte[] photo = br.ReadBytes(System.Convert.ToInt32(fs.Length)); + br.Close(); + fs.Close(); + return photo; + } + #endregion + + #region bateתļ,FileStreamʾ + public static void SetOffice(String filePath, byte[] photo) + { + try + { + FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write); + BinaryWriter br = new BinaryWriter(fs); + br.Write(photo); + br.Close(); + fs.Close(); + br = null; + fs = null; + } + catch (Exception ex) + { + ErrorFollow.TraceWriteError("ļ", ex, ""); + } + } + #endregion + #region bateתļ,FileStreamʾ + public static void SetImage(String filePath, byte[] photo) + { + try + { + MemoryStream buf = new MemoryStream(photo); + Image image = Image.FromStream(buf, true); + image.Save(filePath, image.RawFormat); + buf.Dispose(); + image.Dispose(); + } + catch (Exception ex) + { + ErrorFollow.TraceWrite("ͼƬ", "", ex.Message); + } + } + #endregion + #region bateתļ,FileStreamʾ + public static void SetImage(String filePath, string ImageBase64) + { + try + { + byte[] bytes = CustomIO.Base64ToBytes(ImageBase64); + CustomIO.SetImage(filePath, bytes); + } + catch (Exception ex) + { + ErrorFollow.TraceWrite("ͼƬ", "ImageBase64", ex.Message); + } + + } + #endregion + #region bateתļ,FileStreamʾ + public static void SetFile(String filePath, string ImageBase64) + { + try + { + byte[] bytes = CustomIO.Base64ToBytes(ImageBase64); + CustomIO.SetOffice(filePath, bytes); + bytes = null; + } + catch (Exception ex) + { + ErrorFollow.TraceWrite("ͼƬ", "ImageBase64", ex.Message); + } + + } + #endregion + + #region Accessݿ·滻 + public static string AccessReplacePath(string ConnectionString) + { + if (ConnectionString.Contains("Microsoft.Jet.OLEDB") == false) return ConnectionString; + string[] ss = ConnectionString.Split(';'); + foreach (string s in ss) + { + string[] tt = s.Split('='); + if (tt.Length < 2) continue; + if (tt[0] == "Data Source") + { + string dbname = tt[1]; + if (dbname.Contains(":") == false) + { + ConnectionString = ConnectionString.Replace(dbname, AppDomain.CurrentDomain.BaseDirectory + dbname); + } + break; + } + } + return ConnectionString; + } + #endregion + + #region תƴ + public static string ChineseToPinyin(string value) + { + EcanConvertToCh myConvert = new EcanConvertToCh(); + return myConvert.convertCh(value); + } + #endregion + + #region 鿴ļ + /// + /// ӦóĽ̲鿴ļ + /// + /// + public static void OpenFile(string fileName) + { + try + { + System.Diagnostics.Process process = new System.Diagnostics.Process(); + process.StartInfo.FileName = fileName; + process.StartInfo.Verb = "Open"; + process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal; + process.StartInfo.UseShellExecute = true; + process.Start(); + } + catch + { + System.Windows.Forms.MessageBox.Show("ļ𻵻Ȩ޲"); + } + } + #endregion + #region ýű + public static void ReStartService(string filePath) + { + if (File.Exists(filePath) == false) return; + ErrorFollow.TraceWrite("ڴ", "", ""); + Process proc = null; + try + { + + proc = new Process(); + proc.StartInfo.WorkingDirectory = Path.GetDirectoryName(filePath); + proc.StartInfo.FileName = Path.GetFileName(filePath); + proc.StartInfo.Arguments = string.Format("20"); + //proc.StartInfo.CreateNoWindow = true; + //proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;//DOSڲʾʵ + proc.Start(); + proc.WaitForExit(); + } + catch (Exception ex) + { + Console.WriteLine("Exception Occurred :{0},{1}", ex.Message, ex.StackTrace.ToString()); + } + } + #endregion + + #region ʱ仯 + public static int TimeToSecond(DateTime Date, int IsAddDay) + { + //0ǰ,1,2 + int a = 24 * 60 * 60;//һ86400 + int Hour = Date.Hour; //Сʱ + int Minute = Date.Minute; // + switch (IsAddDay) + { + case 0: + return (Hour * 60 + Minute) * 60; + case 1: + return (Hour * 60 + Minute) * 60 + a; + + default: + break; + } + return 0; + } + #endregion + #region 뻯ʱ + public static DateTime SecondToTime(int Date) + { + int a = 24 * 60 * 60;//һ86400 + int b = Date; + if (b >= a) b = b - a; + int Minute = b / 60; // + int Hour = Minute / 60; //Сʱ + Minute = Minute % 60;//ķ + return new DateTime(2000, 1, 1, Hour, Minute, 0, 0); + } + #endregion + #region ʱʽ(תַ) + public static string FormatElapsedMilliseconds(long ElapsedMilliseconds) + { + if (ElapsedMilliseconds < 1000) return ElapsedMilliseconds + ""; + long seconds = ElapsedMilliseconds / 1000; + if (seconds < 60) return seconds + ""; + long Minute = seconds / 60; + long second = seconds % 60;//ʣµ + if (Minute < 60) return Minute + "" + second + ""; + long Hour = Minute / 60; + long Minute2 = Minute % 60;//ʣµķ + return Hour + "Сʱ" + Minute2 + "" + second + ""; + } + #endregion + #region ʱʽ(תַ) + public static string FormatSeconds(long seconds) + { + if (seconds < 60) return seconds + ""; + long Minute = seconds / 60; + long second = seconds % 60;//ʣµ + if (Minute < 60) return Minute + "" + second + ""; + long Hour = Minute / 60; + long Minute2 = Minute % 60;//ʣµķ + return Hour + "Сʱ" + Minute2 + "" + second + ""; + } + #endregion + #region ȡ1-7 + public static int GetDateWeek(DateTime InDate) + { + int Week = 0; + switch (InDate.DayOfWeek) + { + case DayOfWeek.Sunday: + Week = 7; + break; + case DayOfWeek.Monday: + Week = 1; + break; + case DayOfWeek.Tuesday: + Week = 2; + break; + case DayOfWeek.Wednesday: + Week = 3; + break; + case DayOfWeek.Thursday: + Week = 4; + break; + case DayOfWeek.Friday: + Week = 5; + break; + case DayOfWeek.Saturday: + Week = 6; + break; + default: + break; + } + return Week; + } + #endregion + + #region 򿪱Ի + /// + /// 򿪱Ի + /// + /// ļѡгֵѡ + /// ļ + /// ļĬչ + /// + public static string ShowSaveFileDialog(string filter, string FileName, string DefaultExt) + { + System.Windows.Forms.SaveFileDialog dlg = new System.Windows.Forms.SaveFileDialog(); + dlg.AddExtension = true; + dlg.CheckPathExists = true; + dlg.RestoreDirectory = true; + dlg.DefaultExt = DefaultExt; + dlg.FilterIndex = 0; + dlg.Title = ""; + dlg.FileName = FileName; + dlg.Filter = filter; + dlg.ValidateNames = true; + string FileName2 = ""; + if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK) FileName2 = dlg.FileName; + dlg.Dispose(); + return FileName2; + } + #endregion + #region 򿪶ȡԻ + /// + /// 򿪶ȡԻ + /// + /// ļѡгֵѡtxt files (*.txt)|*.txt|All files (*.*)|*.* + /// ļĬչ + /// + public static string ShowOpenFileDialog(string filter, string InitialDirectory, string DefaultExt) + { + System.Windows.Forms.OpenFileDialog openfile = new System.Windows.Forms.OpenFileDialog(); + openfile.AddExtension = true; + openfile.RestoreDirectory = true; + openfile.InitialDirectory = InitialDirectory; + //openfile.DefaultExt = "xls"; + openfile.Filter = filter; + openfile.DefaultExt = DefaultExt; + //openfile.FilterIndex = 0; + if (openfile.ShowDialog() == System.Windows.Forms.DialogResult.Cancel) return ""; + return openfile.FileName; + } + #endregion + #region ɾļмļ + public static void DeleteFile(string Directory) + { + CustomIO obj = new CustomIO(); + obj.DeleteFileTree(Directory, true, 0); + foreach (string s in obj.files) + { + System.IO.Directory.Delete(s); + } + + } + + List files = new List(); + void DeleteFileTree(string dir, bool showFiles, int level) + { + try + { + if (showFiles == true) + { + foreach (string fname in Directory.GetFiles(dir)) + { + System.IO.File.Delete(fname); + } + } + + foreach (string subdir in Directory.GetDirectories(dir)) + { + DeleteFileTree(subdir, showFiles, level + 1); + } + + } + catch + { + + } + } + void GetDirectory(string dir, int level) + { + try + { + + foreach (string subdir in Directory.GetDirectories(dir)) + { + files.Insert(0, subdir); + GetDirectory(subdir, level + 1); + } + + } + catch + { + + } + } + #endregion + #region ȡļļ + public static void GetListFile(string dir, List ListModel) + { + if (Directory.Exists(dir) == false) return; + string[] files = Directory.GetFiles(dir); + foreach (string fname in files) + { + ListModel.Add(fname); + } + foreach (string subdir in Directory.GetDirectories(dir)) + { + GetListFile(subdir, ListModel); + } + } + #endregion + #region תλ + public static string FormatFileSize(long seek) + { + if (seek > 1024 * 1024 * 1024) + { + return Convert.ToDouble(Convert.ToDouble(seek) / Convert.ToDouble(1024) / Convert.ToDouble(1024) / Convert.ToDouble(1024)).ToString("f2") + "GB"; + } + if (seek > 1024 * 1024) + { + return Convert.ToDouble(Convert.ToDouble(seek) / Convert.ToDouble(1024) / Convert.ToDouble(1024)).ToString("f2") + "MB"; + } + if (seek > 1024) + { + return Convert.ToDouble(Convert.ToDouble(seek) / Convert.ToDouble(1024)).ToString("f2") + "KB"; + } + return seek.ToString() + "Byte"; + } + #endregion + + #region ļУ + public static string GetFileCheckCode(string FilePath) + { + MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); + FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read, 8192); + byte[] hash = md5.ComputeHash(fs); + StringBuilder sb = new StringBuilder(); + foreach (byte byt in hash) + { + sb.Append(String.Format("{0:X2}", byt)); + } + return sb.ToString(); + } + #endregion + #region У + public static string GetCheckCode(byte[] bytes) + { + MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); + MemoryStream fs = new MemoryStream(bytes); + byte[] hash = md5.ComputeHash(fs); + StringBuilder sb = new StringBuilder(); + foreach (byte byt in hash) + { + sb.Append(String.Format("{0:X2}", byt)); + } + return sb.ToString(); + } + #endregion + #region жϲϵͳ + public static string GetOSVersionString() + { + OperatingSystem os = System.Environment.OSVersion; + if (os.Version.Major == 5 && os.Version.Minor == 1) return "XP"; + if (os.Version.Major == 5 && os.Version.Minor == 2) return "2003"; + return ""; + } + #endregion + #region ȡUк + public static List GetUKey() + { + ManagementClass cimobject = new ManagementClass("Win32_DiskDrive"); + ManagementObjectCollection moc = cimobject.GetInstances(); + List listkey = new List(); + foreach (ManagementObject mo in moc) + { + if (mo.Properties["InterfaceType"].Value.ToString() != "USB") continue; + string[] info = mo.Properties["PNPDeviceID"].Value.ToString().Split('&'); + string[] xx = info[3].Split('\\'); + listkey.Add(xx[1]); + } + return listkey; + } + #endregion + #region + public static Bitmap CreateCodeLogo(string code) + { + + long len = code.Length; + string lastString = ""; + char[] list = new char[len + 1]; + + + list = code.ToCharArray(); + + for (int i = 0; i < list.Length; i++) + { + lastString += ConvertToBinaryString(list[i].ToString()); + } + + char[] numList = new char[lastString.Length + 1]; + numList = lastString.ToCharArray(); + + + Bitmap image = new Bitmap(200, 140); + Graphics g = Graphics.FromImage(image); + + g.Clear(Color.White); + + Pen penBlack = new Pen(Color.FromArgb(255, 0, 0, 0), 2.5F); + Pen penWhite = new Pen(Color.White, 2.5F); + + int j = 0; + + for (float k = 10; j < numList.Length; k += 2F, j++) + { + if (numList[j].ToString() == "1") + { + g.DrawLine(penBlack, k, 10, k, 110); + + } + else + { + g.DrawLine(penWhite, k, 10, k, 110); + } + + if (j % 4 == 0) + { + g.DrawString(list[j / 4].ToString(), new System.Drawing.Font("Courier New", 12), new SolidBrush(Color.Red), k, 112); + } + } + return image; + } + #endregion + #region + public static byte[] CreateCode(string code, int Width, int Heigth) + { + if (Width == 0) Width = 200; + if (Heigth == 0) Heigth = 50; + BarcodeLib.Barcode b = new BarcodeLib.Barcode(); + BarcodeLib.TYPE type = BarcodeLib.TYPE.CODE128; + b.IncludeLabel = true; + b.Encode(type, code, Width, 50); + byte[] CodeImage = b.GetImageData(BarcodeLib.SaveTypes.JPG); + return CodeImage; + } + #endregion + #region ֵַתΪֵַ + public static string ConvertToBinaryString(string buf) + { + int[] temp = new int[20]; + string binary; + int val = 0, i = 0, j; + + //ȽַתΪʮ + try + { + val = Convert.ToInt32(buf); + } + catch + { + val = 0; + } + + if (val == 0) + { + return ("0000"); + } + + i = 0; + while (val != 0) + { + temp[i++] = val % 2; + val /= 2; + } + + binary = ""; + + for (j = 0; j <= i - 1; j++) + { + binary += (char)(temp[i - j - 1] + 48); + } + + if (binary.Length < 4) //С4λ߲ + { + int len = 4 - binary.Length; + string str = ""; + + while (len > 0) + { + str += "0"; + len--; + } + + binary = str + binary; + } + + return (binary); + } + #endregion + #region תֵ + public static int ConvertInt32(string value) + { + return (int)Math.Floor(Convert.ToDecimal(value)); + } + #endregion + #region İƴDZʻ + public static string[] SortArray(string[] arr, int? type = 1) + { + // LCID0x00000804 + if (type.Value == 1) + { + CultureInfo PronoCi = new CultureInfo(2052); + Array.Sort(arr); + } + else + { + //ʻ LCID0x00020804 + CultureInfo StrokCi = new CultureInfo(133124); + Thread.CurrentThread.CurrentCulture = StrokCi; + Array.Sort(arr); + } + return arr; + } + #endregion + #region ż(˫)ж,Ƿ + public static bool IsOne(int n) + { + return Convert.ToBoolean(n % 2); + } + #endregion + + #region 16ת10(ÿ2λת) + public static string ConvertHex(string CardNo) + { + CardNo = CardNo.PadLeft(8, '0'); + string CardNo2 = CardNo.Substring(6, 2) + CardNo.Substring(4, 2) + CardNo.Substring(2, 2) + CardNo.Substring(0, 2); + return Convert.ToInt64(CardNo2, 16).ToString(); + } + #endregion + #region byteת16ַ + public static string byteToHexStr(byte[] b, int index, int count) + { + String hs = ""; + String stmp = ""; + int length = count + index; + for (int n = index; n < length; n++) + { + int a = b[n]; + stmp = Convert.ToString(a, 16); + if (stmp.Length == 1) + hs = hs + "0" + stmp; + else + hs = hs + stmp; + } + return hs.ToUpper(); + } + #endregion + #region ַĸ + public static string GetNumberAlpha(string source) + { + string pattern = "[A-Za-z0-9]"; + string strRet = ""; + MatchCollection results = Regex.Matches(source, pattern); + foreach (var v in results) + { + strRet += v.ToString(); + } + return strRet; + } + #endregion + #region ַ + public static string GetNumber(string source) + { + string pattern = "[0-9]"; + string strRet = ""; + MatchCollection results = Regex.Matches(source, pattern); + foreach (var v in results) + { + strRet += v.ToString(); + } + return strRet; + } + #endregion + #region ַ16תbyte + public static byte[] GetHexByte(string str) + { + byte[] Command_APDU = new byte[str.Length / 2]; + int index = 0; + for (int i = 0; i < Command_APDU.Length; i++) + { + string val = str.Substring(index, 2); + Command_APDU[i] = Convert.ToByte(val, 16); + index += 2; + } + return Command_APDU; + } + #endregion + #region MD5ǩ() + public static string Sign_MD5(string str, System.Text.Encoding en, bool IsLower) + { + Byte[] signbuff = en.GetBytes(str); + string sign = BitConverter.ToString(MD5.Create().ComputeHash(signbuff)); + sign = sign.Replace("-", ""); + if (IsLower == true) sign = sign.ToLower(); + return sign; + } + #endregion + #region RSAǩ() + public static string Sign_RSA(string str, string privateKey) + { + RsaPrivateCrtKeyParameters privateKeyParam = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateKey)); + var netKey = string.Format("{0}{1}

{2}

{3}{4}{5}{6}{7}
", + Convert.ToBase64String(privateKeyParam.Modulus.ToByteArrayUnsigned()), + Convert.ToBase64String(privateKeyParam.PublicExponent.ToByteArrayUnsigned()), + Convert.ToBase64String(privateKeyParam.P.ToByteArrayUnsigned()), + Convert.ToBase64String(privateKeyParam.Q.ToByteArrayUnsigned()), + Convert.ToBase64String(privateKeyParam.DP.ToByteArrayUnsigned()), + Convert.ToBase64String(privateKeyParam.DQ.ToByteArrayUnsigned()), + Convert.ToBase64String(privateKeyParam.QInv.ToByteArrayUnsigned()), + Convert.ToBase64String(privateKeyParam.Exponent.ToByteArrayUnsigned())); + + var rsa = new RSACryptoServiceProvider(); + rsa.FromXmlString(netKey); + var sha256 = new SHA256CryptoServiceProvider(); + var signData = Encoding.UTF8.GetBytes(str); + byte[] rgbHash = sha256.ComputeHash(signData); + RSAPKCS1SignatureFormatter formatter = new RSAPKCS1SignatureFormatter(rsa); + formatter.SetHashAlgorithm("SHA256");//˴Ҫǩhash㷨Ҫϱhashֵ㷨һ£Ȼᱨ + byte[] inArray = formatter.CreateSignature(rgbHash); + return Convert.ToBase64String(inArray); + + + //byte[] signature = rsa.SignData(signData, CryptoConfig.CreateFromName("SHA256")); + //var signStr = Convert.ToBase64String(signData); + //return signStr; + + //var rsa = FromXmlString(netKey); + //var rsaClear = new RSACryptoServiceProvider(); + //var paras = rsa.ExportParameters(true); + //rsaClear.ImportParameters(paras); //ǩ + //using (var sha256 = new SHA256CryptoServiceProvider()) + //{ + // var signData = rsa.SignData(Encoding.UTF8.GetBytes(str), sha256); + // var signStr=Convert.ToBase64String(signData); + // return signStr; + //} + } + #endregion + #region תjava + public static byte[] ConvertJavaByte(List bytes) + { + byte[] by = new byte[bytes.Count]; + for (int i = 0; i < bytes.Count; i++) + { + by[i] = Convert.ToByte(bytes[i] & 0xff); + } + return by; + } + #endregion + + #region ѹ + public static void ZipCompress(string filePath, string zipPath) + { + FileStream sourceFile = File.OpenRead(filePath); + FileStream destinationFile = File.Create(zipPath); + byte[] buffer = new byte[sourceFile.Length]; + GZipStream zip = null; + try + { + sourceFile.Read(buffer, 0, buffer.Length); + zip = new GZipStream(destinationFile, CompressionMode.Compress); + zip.Write(buffer, 0, buffer.Length); + } + catch + { } + finally + { + zip.Close(); + sourceFile.Close(); + destinationFile.Close(); + } + } + #endregion + #region ѹ + public static void ZipDecompress(string zipPath, string filePath) + { + FileStream sourceFile = File.OpenRead(zipPath); + string path = filePath.Replace(Path.GetFileName(filePath), ""); + + if (!Directory.Exists(path)) + Directory.CreateDirectory(path); + + FileStream destinationFile = File.Create(filePath); + GZipStream unzip = null; + byte[] buffer = new byte[sourceFile.Length]; + try + { + unzip = new GZipStream(sourceFile, CompressionMode.Decompress, true); + int numberOfBytes = unzip.Read(buffer, 0, buffer.Length); + + destinationFile.Write(buffer, 0, numberOfBytes); + } + catch + { + + } + finally + { + sourceFile.Close(); + destinationFile.Close(); + unzip.Close(); + } + } + #endregion + + #region ݿ + public static void BackDataBase(string databaseName, string filePath) + { + Database db = DatabaseFactory.CreateDatabase(); + db.DataBaseName = "master"; + DbCommand cmd = db.GetSqlStringCommand("BACKUP DATABASE [" + databaseName + "] TO DISK = N'" + filePath + "' WITH NOFORMAT, NOINIT, NAME = N'" + databaseName + "- ݿ ', SKIP, NOREWIND, NOUNLOAD, STATS = 10"); + cmd.CommandTimeout = int.MaxValue; + db.ExecuteNonQuery(cmd); + } + #endregion + #region ԭݿ + public static void RestoreDatabase(string databaseName, string filePath) + { + string filename = System.IO.Path.GetFileNameWithoutExtension(filePath); + string LogicalName_mdf = ""; + string LogicalName_ldf = ""; + string filePath_mdf = ""; + string filePath_ldf = ""; + KillSPID(databaseName); + + Database db = DatabaseFactory.CreateDatabase(); + db.DataBaseName = "master"; + DbCommand cmd = db.GetSqlStringCommand("select fileid,filename from sysaltfiles where dbid=(select dbid from sysdatabases where name=@name) order by fileid"); + db.AddInParameter(cmd, "@name", DbType.String, databaseName); + DataTable tb = db.ExecuteDataTable(cmd); + filePath_mdf = tb.Rows[0]["filename"].ToString().Trim(); + filePath_ldf = tb.Rows[1]["filename"].ToString().Trim(); + cmd = db.GetSqlStringCommand("RESTORE FILELISTONLY FROM DISK = N'" + filePath + "'"); + tb = db.ExecuteDataTable(cmd); + LogicalName_mdf = tb.Rows[0]["LogicalName"].ToString().Trim(); + LogicalName_ldf = tb.Rows[1]["LogicalName"].ToString().Trim(); + cmd = db.GetSqlStringCommand("RESTORE DATABASE [" + databaseName + "] FROM DISK = N'" + filePath + "' WITH MOVE '" + LogicalName_mdf + "' TO '" + filePath_mdf + "',MOVE '" + LogicalName_ldf + "' TO '" + filePath_ldf + "',FILE = 1, NOUNLOAD, REPLACE, STATS = 10"); + cmd.CommandTimeout = int.MaxValue; + db.ExecuteNonQuery(cmd); + } + #endregion + #region رյǰݿӽ + /// + /// رյǰݿӽ + /// + /// Ҫرս̵ݿ + public static void KillSPID(string databaseName) + { + Database db = DatabaseFactory.CreateDatabase(); + db.DataBaseName = "master"; + DbCommand cmd = db.GetSqlStringCommand("select spid from master..sysprocesses where dbid=db_id('" + databaseName + "')"); + cmd.CommandTimeout = int.MaxValue; + DataTable tb = db.ExecuteDataTable(cmd); + foreach (DataRow row in tb.Rows) + { + cmd = db.GetSqlStringCommand("kill " + row["spid"].ToString()); + db.ExecuteNonQuery(cmd); + } + } + #endregion + + #region ǷװWinrar + /// + /// ǷװWinrar + /// + /// + public static bool RarExists() + { + RegistryKey the_Reg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\WinRAR.exe"); + return !string.IsNullOrEmpty(the_Reg.GetValue("").ToString()); + } + #endregion + #region Rar + /// + /// Rar + /// + /// + /// + /// + public static void RarCompress(string patch, string rarPatch) + { + string the_rar = ""; + RegistryKey the_Reg; + object the_Obj; + string the_Info; + ProcessStartInfo the_StartInfo; + Process the_Process; + try + { + the_Reg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\WinRAR.exe"); + if (the_Reg != null) + { + the_Obj = the_Reg.GetValue(""); + the_rar = the_Obj.ToString(); + the_Reg.Close(); + } + //if (Directory.Exists(patch) == false) + //{ + // Directory.CreateDirectory(patch); + //} + // + //the_Info = " a " + rarName + " " + @"C:Test?70821.txt"; //ļѹ + //the_Info = "a \"" + rarPatch + "\" \"" + System.IO.Path.GetFileName(patch) + "\" -r"; + the_Info = "a " + rarPatch + " " + patch + " -r -ep1"; + if (string.IsNullOrEmpty(the_rar) == true) the_rar = "C:/Program Files/WinRAR/WinRAR.exe"; + the_StartInfo = new ProcessStartInfo(); + the_StartInfo.FileName = the_rar; + the_StartInfo.Arguments = the_Info; + the_StartInfo.WindowStyle = ProcessWindowStyle.Hidden; + //ļĿ¼ + the_StartInfo.WorkingDirectory = System.IO.Path.GetDirectoryName(patch); + the_StartInfo.UseShellExecute = false; + the_Process = new Process(); + the_Process.StartInfo = the_StartInfo; + the_Process.Start(); + the_Process.WaitForExit(); + the_Process.Close(); + } + catch (Exception ex) + { + HuizhongLibrary.Log.ErrorFollow.TraceWrite("RarCompress()", ex.StackTrace, ex.Message); + } + } + #endregion + #region ѹ + /// + /// ѹ + /// + /// + /// + /// + /// + public static void RarDecompress(string unRarPatch, string rarPatch, string rarName) + { + string the_rar; + RegistryKey the_Reg; + object the_Obj; + string the_Info; + + + try + { + the_Reg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\WinRAR.exe"); + the_Obj = the_Reg.GetValue(""); + the_rar = the_Obj.ToString(); + the_Reg.Close(); + //the_rar = the_rar.Substring(1, the_rar.Length - 7); + + if (Directory.Exists(unRarPatch) == false) + { + Directory.CreateDirectory(unRarPatch); + } + the_Info = "x \"" + rarName + "\" \"" + unRarPatch + "\" -y"; + + ProcessStartInfo the_StartInfo = new ProcessStartInfo(); + the_StartInfo.FileName = the_rar; + the_StartInfo.Arguments = the_Info; + the_StartInfo.WindowStyle = ProcessWindowStyle.Hidden; + the_StartInfo.WorkingDirectory = rarPatch;//ȡѹ· + + Process the_Process = new Process(); + the_Process.StartInfo = the_StartInfo; + the_Process.Start(); + the_Process.WaitForExit(); + the_Process.Close(); + } + catch (Exception ex) + { + HuizhongLibrary.Log.ErrorFollow.TraceWrite("RarDecompress()", ex.StackTrace, ex.Message); + } + } + #endregion + + + #region ļ + public static void DownFile(HttpResponse Response, string FilePath, string Name) + { + if (FilePath == "") return; + if (FilePath.Substring(0, 1) == "/") FilePath = AppDomain.CurrentDomain.BaseDirectory + FilePath.Substring(1); + if (FilePath.Substring(0, 3) == "../") FilePath = AppDomain.CurrentDomain.BaseDirectory + FilePath.Substring(3); + //FilePath = AppDomain.CurrentDomain.BaseDirectory + FilePath; + Response.Clear(); + Response.ClearHeaders(); + Response.Buffer = true; + Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(Name, System.Text.Encoding.GetEncoding("utf-8"))); + Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); //Ϊ + Response.ContentType = "application/octet-stream"; + if (Path.GetExtension(FilePath) == ".doc") Response.ContentType = "application/ms-word"; + if (Path.GetExtension(FilePath) == ".xls") Response.ContentType = "application/ms-excel"; + if (System.IO.File.Exists(FilePath) == true) + { + FileInfo fi = new FileInfo(FilePath); + FileStream fs = null; + byte[] buffer = new Byte[10000]; + int length; + long dataToRead; + try + { + fs = fi.Open(FileMode.Open, FileAccess.Read, FileShare.Read); + Response.AppendHeader("Content-Length", fs.Length.ToString()); + dataToRead = fs.Length; + while (dataToRead > 0) + { + if (Response.IsClientConnected) + { + length = fs.Read(buffer, 0, 10000); + Response.OutputStream.Write(buffer, 0, length); + Response.Flush(); + buffer = new Byte[10000]; + dataToRead = dataToRead - length; + } + else + { + dataToRead = -1; + } + } + Response.End(); + } + catch { } + finally + { + if (fs != null) + { + fs.Close(); + } + Response.End(); + } + + } + } + #endregion + #region httpļ + /// + /// httpļ + /// + /// ļַ + /// ļŵַļ + /// + public static string DownFile(string url, out string error) + { + error = ""; + CheckSSL(url); + string tempPath = AppDomain.CurrentDomain.BaseDirectory + @"ServerCookies/"; + if (System.IO.Directory.Exists(tempPath) == false) System.IO.Directory.CreateDirectory(tempPath); //ʱļĿ¼ + string tempFile = tempPath + Path.GetFileName(url); //ʱļ + if (System.IO.File.Exists(tempFile)) + { + System.IO.File.Delete(tempFile); //ɾ + } + try + { + FileStream fs = new FileStream(tempFile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite); + // ò + HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; + //󲢻ȡӦӦ + HttpWebResponse response = request.GetResponse() as HttpWebResponse; + //ֱrequest.GetResponse()ſʼĿҳPost + Stream responseStream = response.GetResponseStream(); + //ļд + //Stream stream = new FileStream(tempFile, FileMode.Create); + byte[] bArr = new byte[1024]; + int size = responseStream.Read(bArr, 0, (int)bArr.Length); + while (size > 0) + { + //stream.Write(bArr, 0, size); + fs.Write(bArr, 0, size); + size = responseStream.Read(bArr, 0, (int)bArr.Length); + } + //stream.Close(); + fs.Close(); + responseStream.Close(); + return tempFile; + } + catch (Exception ex) + { + ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message); + error = ex.Message; + return ""; + } + } + #endregion + #region httpļ + /// + /// httpļ + /// + /// ļַ + /// ļŵַļ + /// + public static string DownFile2(string url, out string error) + { + error = ""; + CheckSSL(url); + string tempPath = AppDomain.CurrentDomain.BaseDirectory + @"ServerCookies/"; + if (System.IO.Directory.Exists(tempPath) == false) System.IO.Directory.CreateDirectory(tempPath); //ʱļĿ¼ + string tempFile = tempPath + Path.GetFileName(url); //ʱļ + if (System.IO.File.Exists(tempFile)) + { + System.IO.File.Delete(tempFile); //ɾ + } + try + { + FileStream fs = new FileStream(tempFile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite); + // ò + HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; + //󲢻ȡӦӦ + HttpWebResponse response = request.GetResponse() as HttpWebResponse; + //ֱrequest.GetResponse()ſʼĿҳPost + Stream responseStream = response.GetResponseStream(); + //ļд + //Stream stream = new FileStream(tempFile, FileMode.Create); + byte[] bArr = new byte[1024]; + int size = responseStream.Read(bArr, 0, (int)bArr.Length); + while (size > 0) + { + //stream.Write(bArr, 0, size); + fs.Write(bArr, 0, size); + size = responseStream.Read(bArr, 0, (int)bArr.Length); + } + //stream.Close(); + fs.Close(); + responseStream.Close(); + return "ServerCookies/" + Path.GetFileName(url); + } + catch (Exception ex) + { + ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message); + error = ex.Message; + return ""; + } + } + #endregion + + #region SSLЭ֤ + public static void CheckSSL(string surl) + { + var url = surl.ToLower(); + if (url.Substring(0, 8) == "https://") + { + string path = AppDomain.CurrentDomain.BaseDirectory + "Setup.ini"; + string sslURL = ConfigurationSourceSection.LoadXml_Attribute(path, "sslURL"); + if (string.IsNullOrEmpty(sslURL) == true) return; + sslURL=sslURL.ToLower(); + string[] ss = sslURL.Split(','); + bool IsSSL = false; + foreach (var item in ss) + { + if (string.IsNullOrEmpty(item)) continue; + if (url.Contains(item) == true) + { + IsSSL = true; + break; + } + } + if (IsSSL == true) + { + ServicePointManager.ServerCertificateValidationCallback += (s, cert, chain, sslPolicyErrors) => true;//һ + System.Net.ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;//ڶУҪ + ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); + } + } + } + #endregion + #region Http + public static string HttpRequest(string url, string Method, string ContentType, List ListHeader, Version ver, byte[] bytes, out string ErrorMessage, string Accept = "*/*") + { + try + { + CheckSSL(url); + ErrorMessage = ""; + //System.Net.ServicePointManager.DefaultConnectionLimit =200; + if (string.IsNullOrEmpty(ContentType) == true) ContentType = "application/x-www-form-urlencoded"; + HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url); + myRequest.Method = Method; //GET,POST + myRequest.ContentType = ContentType; + myRequest.KeepAlive = true; + + //myRequest.Accept = "text/html"; + myRequest.Accept = Accept; + myRequest.UserAgent = + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36"; + myRequest.Headers.Add("Accept-Language: zh-CN"); + myRequest.Headers["Pragma"] = "no-cache"; //û + myRequest.Headers["Cache-Control"] = "no-cache"; //û + //myRequest.Timeout = 3 * 60 * 1000; + myRequest.Timeout = 15000; + myRequest.ReadWriteTimeout = 3 * 60 * 1000; + if (ver != null) + myRequest.ProtocolVersion = ver; + if (ListHeader != null) + { + foreach (var item in ListHeader) + { + myRequest.Headers.Add(item); + } + } + if (Method.ToUpper() == "POST" && (bytes == null || bytes.Length == 0)) + { + bytes = new byte[1]; + } + if (bytes != null && bytes.Length > 0) + { + //myRequest.GetRequestStream().Write(bytes, 0, bytes.Length); + Stream stream = myRequest.GetRequestStream(); + stream.Write(bytes, 0, bytes.Length); + stream.Close(); + + } + + //ýӿڷֵ + HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse(); + string str = myResponse.ToString(); + Stream myResponseStream = myResponse.GetResponseStream(); + StreamReader reader = new StreamReader(myResponseStream, Encoding.UTF8); + string content = reader.ReadToEnd(); + reader.Close(); + + myResponseStream.Close(); + myRequest.Abort(); + myResponse.Close(); + reader = null; + myResponseStream = null; + myRequest = null; + myResponse = null; + return content; + } + catch (WebException e) + { + if (e.Response == null) + { + ErrorMessage = e.Message; + } + else + { + Stream myResponseStream = e.Response.GetResponseStream(); + StreamReader reader = new StreamReader(myResponseStream, Encoding.UTF8); + ErrorMessage = reader.ReadToEnd(); + myResponseStream.Close(); + reader.Close(); + reader = null; + if (ErrorMessage == "") ErrorMessage = e.Message; + } + } + return ""; + } + #endregion + #region Httpļϴ + public static string HttpFileRequest(string url, List ListModel, out string ErrorMessage) + { + try + { + CheckSSL(url); + var memStream = new MemoryStream(); + // ߽ + var boundary = "---------------" + DateTime.Now.Ticks.ToString("x"); + // ߽ + var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n"); + // Ľ + var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n"); + memStream.Write(beginBoundary, 0, beginBoundary.Length); + for (int i = 0; i < ListModel.Count; i++) + { + PostDateClass temp = ListModel[i]; + if (temp.Type == 1) + { + var fileStream = new FileStream(temp.Value, FileMode.Open, FileAccess.Read); + // дļ + const string filePartHeader = + "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\";filelength=\"{2}\";\r\n" + + "Content-Type: application/octet-stream\r\n\r\n"; + var header = string.Format(filePartHeader, temp.Key, temp.Value, fileStream.Length); + var headerbytes = Encoding.UTF8.GetBytes(header); + memStream.Write(headerbytes, 0, headerbytes.Length); + var buffer = new byte[1024]; + int bytesRead; // =0 + while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) + { + memStream.Write(buffer, 0, bytesRead); + } + string end = "\r\n"; + headerbytes = Encoding.UTF8.GetBytes(end); + memStream.Write(headerbytes, 0, headerbytes.Length); + fileStream.Close(); + } + else if (temp.Type == 0) + { + // дַKey + var stringKeyHeader = "Content-Disposition: form-data; name=\"{0}\"" + + "\r\n\r\n{1}\r\n"; + var header = string.Format(stringKeyHeader, temp.Key, temp.Value); + var headerbytes = Encoding.UTF8.GetBytes(header); + memStream.Write(headerbytes, 0, headerbytes.Length); + } + if (i != ListModel.Count - 1) + memStream.Write(beginBoundary, 0, beginBoundary.Length); + else + // дĽ߽ + memStream.Write(endBoundary, 0, endBoundary.Length); + } + + ErrorMessage = ""; + HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url); + myRequest.Method = "POST"; //GET,POST + myRequest.Timeout = 10000; + myRequest.ContentType = "multipart/form-data; boundary=" + boundary; + myRequest.ContentLength = memStream.Length; + var requestStream = myRequest.GetRequestStream(); + memStream.Position = 0; + var tempBuffer = new byte[memStream.Length]; + memStream.Read(tempBuffer, 0, tempBuffer.Length); + memStream.Close(); + requestStream.Write(tempBuffer, 0, tempBuffer.Length); + requestStream.Close(); + + //ýӿڷֵ + HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse(); + Stream myResponseStream = myResponse.GetResponseStream(); + StreamReader reader = new StreamReader(myResponseStream, Encoding.UTF8); + string content = reader.ReadToEnd(); + reader.Close(); + + myResponseStream.Close(); + myRequest.Abort(); + myResponse.Close(); + return content; + } + catch (Exception ex) + { + ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message); + ErrorMessage = ex.Message; + } + return ""; + } + #endregion + + + #region Httpļϴ + public static string HttpFileRequest(string url, List ListModel, List Head, out string ErrorMessage) + { + try + { + CheckSSL(url); + var memStream = new MemoryStream(); + // ߽ + var boundary = "---------------" + DateTime.Now.Ticks.ToString("x"); + // ߽ + var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n"); + // Ľ + var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n"); + memStream.Write(beginBoundary, 0, beginBoundary.Length); + for (int i = 0; i < ListModel.Count; i++) + { + PostDateClass temp = ListModel[i]; + if (temp.Type == 1) + { + var fileStream = new FileStream(temp.Value, FileMode.Open, FileAccess.Read); + // дļ + const string filePartHeader = + "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\";filelength=\"{2}\";\r\n" + + "Content-Type: application/octet-stream\r\n\r\n"; + var header = string.Format(filePartHeader, temp.Key, temp.Value, fileStream.Length); + var headerbytes = Encoding.UTF8.GetBytes(header); + memStream.Write(headerbytes, 0, headerbytes.Length); + var buffer = new byte[1024]; + int bytesRead; // =0 + while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) + { + memStream.Write(buffer, 0, bytesRead); + } + string end = "\r\n"; + headerbytes = Encoding.UTF8.GetBytes(end); + memStream.Write(headerbytes, 0, headerbytes.Length); + fileStream.Close(); + } + else if (temp.Type == 0) + { + // дַKey + var stringKeyHeader = "Content-Disposition: form-data; name=\"{0}\"" + + "\r\n\r\n{1}\r\n"; + var header = string.Format(stringKeyHeader, temp.Key, temp.Value); + var headerbytes = Encoding.UTF8.GetBytes(header); + memStream.Write(headerbytes, 0, headerbytes.Length); + } + if (i != ListModel.Count - 1) + memStream.Write(beginBoundary, 0, beginBoundary.Length); + else + // дĽ߽ + memStream.Write(endBoundary, 0, endBoundary.Length); + } + + ErrorMessage = ""; + HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url); + myRequest.Method = "POST"; //GET,POST + myRequest.Timeout = 10000; + myRequest.ContentType = "multipart/form-data; boundary=" + boundary; + myRequest.ContentLength = memStream.Length; + + if (Head != null) + { + foreach (string strHead in Head) + { + myRequest.Headers.Add(strHead); + } + } + + + + + var requestStream = myRequest.GetRequestStream(); + memStream.Position = 0; + var tempBuffer = new byte[memStream.Length]; + memStream.Read(tempBuffer, 0, tempBuffer.Length); + memStream.Close(); + requestStream.Write(tempBuffer, 0, tempBuffer.Length); + requestStream.Close(); + + //ýӿڷֵ + HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse(); + Stream myResponseStream = myResponse.GetResponseStream(); + StreamReader reader = new StreamReader(myResponseStream, Encoding.UTF8); + string content = reader.ReadToEnd(); + reader.Close(); + + myResponseStream.Close(); + myRequest.Abort(); + myResponse.Close(); + return content; + } + catch (Exception ex) + { + ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message); + ErrorMessage = ex.Message; + } + return ""; + } + #endregion + + #region HttpFormData + public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) + { + return true; //ǽ + } + public static string HttpFormRequest(string url, string Method, List ListHeader, Version ver, ref CookieContainer cookieContainer, string Accept, string UserAgent, Dictionary ListFormData, out string ErrorMessage) + { + ErrorMessage = ""; + //cookie = ""; + try + { + CheckSSL(url); + // ߽ + var boundary = "---------------" + DateTime.Now.Ticks.ToString("x"); + // ߽ + var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n"); + // Ľ + var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n"); + //FormDataģ + string dataFormdataTemplate = + "Content-Disposition: form-data; name=\"{0}\"" + + "\r\n\r\n{1}\r\n"; + var memStream = new MemoryStream(); + if (ListFormData != null && ListFormData.Count > 0) + { + int index = 0; + foreach (var item in ListFormData) + { + string formdata = string.Format( + dataFormdataTemplate, + item.Key, + item.Value); + var headerbytes = Encoding.UTF8.GetBytes(formdata); + memStream.Write(headerbytes, 0, headerbytes.Length); + if (index != ListFormData.Count - 1) + { + memStream.Write(beginBoundary, 0, beginBoundary.Length); + } + else + { + // дĽ߽ + memStream.Write(endBoundary, 0, endBoundary.Length); + } + index++; + } + } + HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url); + myRequest.Method = Method; //GET,POST + //myRequest.ContentType = ContentType; + myRequest.KeepAlive = true; + if (string.IsNullOrEmpty(Accept) == false) myRequest.Accept = Accept; + if (string.IsNullOrEmpty(UserAgent) == false) myRequest.UserAgent = UserAgent; + //myRequest.Accept = "text/html"; + //myRequest.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; qihu theworld)"; + myRequest.Headers.Add("Accept-Language: zh-CN"); + myRequest.Headers["Pragma"] = "no-cache"; //û + myRequest.Headers["Cache-Control"] = "no-cache"; //û + myRequest.Timeout = 3 * 60 * 1000; + if (ver != null) + myRequest.ProtocolVersion = ver; + if (ListHeader != null) + { + foreach (var item in ListHeader) + { + myRequest.Headers.Add(item); + } + } + //if (string.IsNullOrEmpty(cookieContainer) == false)myRequest.Headers.Add("Cookie:" + cookieContainer); + //byte[] b = memStream.ToArray(); + + myRequest.CookieContainer = cookieContainer; + //string s = System.Text.Encoding.UTF8.GetString(b, 0, b.Length); + myRequest.ContentType = "multipart/form-data; boundary=" + boundary; + myRequest.ContentLength = memStream.Length; + var requestStream = myRequest.GetRequestStream(); + memStream.Position = 0; + var tempBuffer = new byte[memStream.Length]; + memStream.Read(tempBuffer, 0, tempBuffer.Length); + memStream.Close(); + requestStream.Write(tempBuffer, 0, tempBuffer.Length); + requestStream.Close(); + + //ýӿڷֵ + HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse(); + //CookieContainer cookieContainer2 = new CookieContainer(10); + myResponse.Cookies = cookieContainer.GetCookies(myResponse.ResponseUri); + Stream myResponseStream = myResponse.GetResponseStream(); + StreamReader reader = new StreamReader(myResponseStream, Encoding.UTF8); + string content = reader.ReadToEnd(); + reader.Close(); + + //cookie = myResponse.Headers.Get("Set-Cookie"); + + myResponseStream.Close(); + myRequest.Abort(); + myResponse.Close(); + return content; + } + catch (WebException e) + { + if (e.Response == null) + { + ErrorMessage = e.Message; + } + else + { + Stream myResponseStream = e.Response.GetResponseStream(); + StreamReader reader = new StreamReader(myResponseStream, Encoding.UTF8); + ErrorMessage = reader.ReadToEnd(); + if (ErrorMessage == "") ErrorMessage = e.Message; + } + } + return ""; + } + #endregion + #region תUrlַ + public static string param(TResult T) where TResult : class + { + Type type = typeof(TResult); + string ss = ""; + Array.ForEach(type.GetProperties(), item => + { + //Type columnType = item.PropertyType; + //if (item.PropertyType.IsGenericType && item.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>)) + //{ + // columnType = item.PropertyType.GetGenericArguments()[0]; + //} + string value = Convert.ToString(item.GetValue(T, null)); + if (string.IsNullOrEmpty(value) == false) + { + value = System.Web.HttpUtility.UrlEncode(value, Encoding.GetEncoding("utf-8")); + ss += "&" + item.Name + "=" + value; + } + + }); + ss = ss.Substring(1); + return ss; + } + #endregion + #region תUrlַ + public static string param2(TResult T, string EncodeName) where TResult : class + { + Type type = typeof(TResult); + string ss = ""; + Array.ForEach(type.GetProperties(), item => + { + //Type columnType = item.PropertyType; + //if (item.PropertyType.IsGenericType && item.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>)) + //{ + // columnType = item.PropertyType.GetGenericArguments()[0]; + //} + string value = Convert.ToString(item.GetValue(T, null)); + if (string.IsNullOrEmpty(value) == false) + { + value = System.Web.HttpUtility.UrlEncode(value, Encoding.GetEncoding(EncodeName)); + ss += "&" + item.Name + "=" + value; + } + + }); + ss = ss.Substring(1); + return ss; + } + #endregion + #region תUrlַ + public static string param(Dictionary ListModel, string EncodeName) + { + string ss = ""; + foreach (var item in ListModel) + { + string value = Convert.ToString(item.Value); + if (string.IsNullOrEmpty(value) == false) + { + value = System.Web.HttpUtility.UrlEncode(value, Encoding.GetEncoding(EncodeName)); + ss += "&" + item.Key + "=" + value; + } + } + ss = ss.Substring(1); + return ss; + } + #endregion + #region жַǷԷ + public static bool CheckPageUrl(string url) + { + bool result = false; + try + { + if (url.IndexOf("http").Equals(-1)) + { + url = "http://" + url; + // Console.WriteLine(url); + } + HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url); + myHttpWebRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko"; + myHttpWebRequest.Method = "GET"; + myHttpWebRequest.Timeout = 3000; + HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse(); + if (myHttpWebResponse.StatusCode == HttpStatusCode.OK) + { + result = true; + } + myHttpWebResponse.Close(); + } + catch + { + result = false; + } + return result; + } + #endregion + + #region ļĿ¼Ŀ¼ + public static void CopyDirectory(string OldDirectory, string NewDirectory) + { + if (Directory.Exists(NewDirectory) == false) Directory.CreateDirectory(NewDirectory); + string[] files = Directory.GetFiles(OldDirectory); + foreach (string fname in files) + { + string fileName = Path.GetFileName(fname); + string newFileName = NewDirectory + "/" + fileName; + File.Copy(fname, newFileName, true); + } + foreach (string subdir in Directory.GetDirectories(OldDirectory)) + { + string NewDirectory2 = NewDirectory + subdir.Substring(OldDirectory.Length); + CopyDirectory(subdir, NewDirectory2); + } + } + #endregion + + #region ȡXMLֵ + public static string GetXmlAttribute(XElement doc, string Name) + { + if (doc == null || doc.Attribute(Name) == null) return ""; + return doc.Attribute(Name).Value.Trim(); + } + #endregion + #region ȡXMLֵ + public static string GetXmlAttribute(XmlNode doc, string Name) + { + if (doc.Attributes[Name] == null) return ""; + return doc.Attributes[Name].Value.Trim(); + } + #endregion + #region ȡXMLֵ + public static string GetXmlElement(XElement doc, string Name) + { + if (doc.Element(Name) == null) return ""; + return doc.Element(Name).Value.Trim(); + } + #endregion + #region XMLݷض + public static TResult CreateObject_XElement(XElement doc) + { + Type t = typeof(TResult); + TResult model = Activator.CreateInstance(); + PropertyInfo[] propertyInfo = t.GetProperties(); + if (propertyInfo.Length > 0) + { + foreach (PropertyInfo info in propertyInfo) + { + String str = CustomIO.GetXmlElement(doc, info.Name); + if (string.IsNullOrEmpty(str) == false) + { + if (info.PropertyType == typeof(byte) || info.PropertyType == typeof(Nullable)) + { + info.SetValue(model, Convert.ToByte(str), null); + } + else if (info.PropertyType == typeof(Int16) || info.PropertyType == typeof(Nullable)) + { + info.SetValue(model, Convert.ToInt16(str), null); + } + else if (info.PropertyType == typeof(int) || info.PropertyType == typeof(Nullable)) + { + info.SetValue(model, Convert.ToInt32(str), null); + } + else if (info.PropertyType == typeof(Int64) || info.PropertyType == typeof(Nullable)) + { + info.SetValue(model, Convert.ToInt64(str), null); + } + else if (info.PropertyType == typeof(bool) || info.PropertyType == typeof(Nullable)) + { + info.SetValue(model, Convert.ToBoolean(str), null); + } + else if (info.PropertyType == typeof(decimal) || info.PropertyType == typeof(Nullable)) + { + info.SetValue(model, Convert.ToDecimal(str), null); + } + else if (info.PropertyType == typeof(Double) || info.PropertyType == typeof(Nullable)) + { + info.SetValue(model, Convert.ToDouble(str), null); + } + else if (info.PropertyType == typeof(Single) || info.PropertyType == typeof(Nullable)) + { + info.SetValue(model, Convert.ToSingle(str), null); + } + else if (info.PropertyType == typeof(DateTime) || info.PropertyType == typeof(Nullable)) + { + info.SetValue(model, Convert.ToDateTime(str), null); + } + else if (info.PropertyType == typeof(byte[])) + { + + } + else + { + info.SetValue(model, str, null); + } + } + else + { + if (info.PropertyType == typeof(string)) + { + info.SetValue(model, str, null); + } + else + { + info.SetValue(model, null, null); + } + } + } + } + return model; + } + #endregion + #region XMLԷض + public static TResult CreateObject_XmlAttribute(XElement doc) + { + Type t = typeof(TResult); + TResult model = Activator.CreateInstance(); + PropertyInfo[] propertyInfo = t.GetProperties(); + if (propertyInfo.Length > 0) + { + foreach (PropertyInfo info in propertyInfo) + { + String str = CustomIO.GetXmlAttribute(doc, info.Name); + if (string.IsNullOrEmpty(str) == false) + { + if (info.PropertyType == typeof(byte) || info.PropertyType == typeof(Nullable)) + { + info.SetValue(model, Convert.ToByte(str), null); + } + else if (info.PropertyType == typeof(Int16) || info.PropertyType == typeof(Nullable)) + { + info.SetValue(model, Convert.ToInt16(str), null); + } + else if (info.PropertyType == typeof(int) || info.PropertyType == typeof(Nullable)) + { + info.SetValue(model, Convert.ToInt32(str), null); + } + else if (info.PropertyType == typeof(Int64) || info.PropertyType == typeof(Nullable)) + { + info.SetValue(model, Convert.ToInt64(str), null); + } + else if (info.PropertyType == typeof(bool) || info.PropertyType == typeof(Nullable)) + { + info.SetValue(model, Convert.ToBoolean(str), null); + } + else if (info.PropertyType == typeof(decimal) || info.PropertyType == typeof(Nullable)) + { + info.SetValue(model, Convert.ToDecimal(str), null); + } + else if (info.PropertyType == typeof(Double) || info.PropertyType == typeof(Nullable)) + { + info.SetValue(model, Convert.ToDouble(str), null); + } + else if (info.PropertyType == typeof(Single) || info.PropertyType == typeof(Nullable)) + { + info.SetValue(model, Convert.ToSingle(str), null); + } + else if (info.PropertyType == typeof(DateTime) || info.PropertyType == typeof(Nullable)) + { + info.SetValue(model, Convert.ToDateTime(str), null); + } + else if (info.PropertyType == typeof(byte[])) + { + + } + else + { + info.SetValue(model, str, null); + } + } + else + { + info.SetValue(model, str, null); + } + } + } + return model; + } + #endregion + #region XML + public static string CreateXmlElement(string key, string value) + { + if (value == null) value = ""; + return "<" + key + ">" + value + ""; + } + #endregion + #region XML + public static void CreateXmlElement(StringBuilder sb, string key, string value) + { + if (value == null) value = ""; + sb.Append("<" + key + ">" + value + ""); + } + #endregion + #region XMLתַ + /// + /// XMLתַ + /// + public static string ConvertXml(string xml) + { + xml = xml.Replace("<", "<"); + xml = xml.Replace(">", ">"); + xml = xml.Replace("&", "&"); + xml = xml.Replace("'", "'"); + xml = xml.Replace(""", "\""); + return xml; + } + #endregion + + #region ȡKey + public static string GetKeyValues(Dictionary ReceiveModel, string key) + { + string val = ""; + key = key.ToUpper(); + ReceiveModel.TryGetValue(key, out val); + if (val == null) val = ""; + return val; + } + #endregion + + #region װ + public static void InstallService(string filepath) + { + try + { + AssemblyInstaller myAssemblyInstaller = new AssemblyInstaller(); + myAssemblyInstaller.UseNewContext = true; + myAssemblyInstaller.Path = filepath; + Hashtable stateSaver = new System.Collections.Hashtable(); + myAssemblyInstaller.Install(stateSaver); + myAssemblyInstaller.Commit(stateSaver); + myAssemblyInstaller.Dispose(); + } + catch (Exception ex) + { + MessageBox.Show("װʧ!"); + } + } + #endregion + + #region ͳijֵַĴ + public static int SubstringCount(string str, string substring) + { + if (str.Contains(substring) == true) + { + string str2 = str.Replace(substring, ""); + return (str.Length - str2.Length) / substring.Length; + } + return 0; + } + #endregion + + #region ϴļ + public static string CheckUploadFile(string fileName) + { + //ϴļչ + String fileTypes = "gif,jpg,jpeg,png,bmp,swf,pdf,rar,zip,doc,docx,xls,xlsx,ppt,pptx,mp4,xml,apk,txt"; + String fileExt = Path.GetExtension(fileName).ToLower(); + ArrayList fileTypeList = ArrayList.Adapter(fileTypes.Split(',')); + if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(fileTypes.Split(','), fileExt.Substring(1).ToLower()) == -1) + { + return "ϴļչDzչ"; + } + return ""; + } + #endregion + + + #region ȡFTPļ + public static void FtpGetDirectory(string Url, string UserName, string PassWord, out List ListDirectory, out List ListFile) + { + if (Url.Substring(0, 3).ToLower() != "ftp") Url = "ftp://" + Url; + List ListModel = new List(); + List ListModel2 = new List(); + FtpWebRequest ftp; + ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(Url)); + ftp.Credentials = new NetworkCredential(UserName, PassWord); + ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails; + WebResponse response = ftp.GetResponse(); + StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding("GB2312")); + Regex replaceSpace = new Regex(@"\s{1,}", RegexOptions.IgnoreCase); + string line = ""; + while (true) + { + line = reader.ReadLine(); + if (line == null) break; + int index = line.IndexOf(""); + line = replaceSpace.Replace(line, ",").Trim(); + string[] ss = line.Split(','); + line = ""; + for (int i = 3; i < ss.Length; i++) + { + line += ss[i] + " "; + } + line = line.TrimEnd(); + if (index == -1) + { + ListModel.Add(line); + } + else + { + ListModel2.Add(line); + } + } + reader.Close(); + response.Close(); + ListDirectory = ListModel2; + ListFile = ListModel; + } + #endregion + #region FTPļ + public static void FtpCreateDirectory(string Url, string UserName, string PassWord) + { + if (Url.Substring(0, 3).ToLower() != "ftp") Url = "ftp://" + Url; + FtpWebRequest ser; + ser = (FtpWebRequest)FtpWebRequest.Create(new Uri(Url)); + ser.Method = WebRequestMethods.Ftp.MakeDirectory; + ser.Credentials = new NetworkCredential(UserName, PassWord); + FtpWebResponse response = (FtpWebResponse)ser.GetResponse(); + response.Close(); + } + #endregion + #region FTPļ + public static void FtpReFileName(string Url, string UserName, string PassWord, string FileName, string newFileName) + { + if (Url.Substring(0, 3).ToLower() != "ftp") Url = "ftp://" + Url; + FtpWebRequest ser; + ser = (FtpWebRequest)FtpWebRequest.Create(new Uri(Url + "/" + FileName)); + ser.Method = WebRequestMethods.Ftp.Rename; + ser.Credentials = new NetworkCredential(UserName, PassWord); + ser.RenameTo = newFileName; + FtpWebResponse response = (FtpWebResponse)ser.GetResponse(); + response.Close(); + } + #endregion + #region FTPɾĿ¼ + public static void FtpDeleteDirectory(string Url, string UserName, string PassWord) + { + if (Url.Substring(0, 3).ToLower() != "ftp") Url = "ftp://" + Url; + FtpWebRequest ser; + ser = (FtpWebRequest)FtpWebRequest.Create(new Uri(Url)); + ser.Method = WebRequestMethods.Ftp.RemoveDirectory; + ser.Credentials = new NetworkCredential(UserName, PassWord); + FtpWebResponse response = (FtpWebResponse)ser.GetResponse(); + response.Close(); + } + #endregion + #region FTPɾļ + public static void FtpDeleteFile(string Url, string UserName, string PassWord, string FileName) + { + if (Url.Substring(0, 3).ToLower() != "ftp") Url = "ftp://" + Url; + FtpWebRequest ser; + ser = (FtpWebRequest)FtpWebRequest.Create(new Uri(Url + "/" + FileName)); + ser.Method = WebRequestMethods.Ftp.DeleteFile; + ser.Credentials = new NetworkCredential(UserName, PassWord); + FtpWebResponse response = (FtpWebResponse)ser.GetResponse(); + response.Close(); + } + #endregion + #region FTPϴļ + public static void FtpUploadFile(string Url, string UserName, string PassWord, string FilePath) + { + if (Url.Substring(0, 3).ToLower() != "ftp") Url = "ftp://" + Url; + FileStream fileStream = File.Open(FilePath, FileMode.Open); + FtpWebRequest ser; + ser = (FtpWebRequest)FtpWebRequest.Create(new Uri(Url + "/" + Path.GetFileName(FilePath))); + ser.Method = WebRequestMethods.Ftp.UploadFile; + ser.Credentials = new NetworkCredential(UserName, PassWord); + ser.UseBinary = true; + ser.KeepAlive = false; + Stream requestStream = ser.GetRequestStream(); + ser.ContentLength = fileStream.Length; + + byte[] buffer = new byte[1024]; + int bytesRead; + while (true) + { + bytesRead = fileStream.Read(buffer, 0, buffer.Length); + if (bytesRead == 0) + break; + requestStream.Write(buffer, 0, bytesRead); + } + requestStream.Close(); + fileStream.Close(); + } + #endregion + #region FTPļ + public static void FtpDownloadFile(string Url, string UserName, string PassWord, string FileName, string SaveDirectory) + { + if (Url.Substring(0, 3).ToLower() != "ftp") Url = "ftp://" + Url; + FtpWebRequest ser; + ser = (FtpWebRequest)FtpWebRequest.Create(new Uri(Url + "/" + FileName)); + ser.Method = WebRequestMethods.Ftp.DownloadFile; + ser.Credentials = new NetworkCredential(UserName, PassWord); + FtpWebResponse response = (FtpWebResponse)ser.GetResponse(); + Stream requestStream = response.GetResponseStream(); + FileStream outputStream = new FileStream(SaveDirectory + "/" + FileName, FileMode.Create); + long cl = response.ContentLength; + int bufferSize = 2048; + int readCount; + byte[] buffer = new byte[bufferSize]; + + readCount = requestStream.Read(buffer, 0, bufferSize); + while (readCount > 0) + { + outputStream.Write(buffer, 0, readCount); + readCount = requestStream.Read(buffer, 0, bufferSize); + } + requestStream.Close(); + outputStream.Close(); + response.Close(); + } + #endregion + + #region Ѷлɼֵ + public static string SerializeKeyValue(T Model) + { + return ""; + } + #endregion + + #region ļ· + public static void CreateDirectory(string FilePath) + { + string dir = Path.GetDirectoryName(FilePath); + if (string.IsNullOrEmpty(dir) == true) return; + dir = dir.Replace("\\", "/"); + string[] ss = dir.Split('/'); + string dir2 = ""; + foreach (string item in ss) + { + if (string.IsNullOrEmpty(item) == true) continue; + if (dir2 == "") { dir2 += item; } + else { dir2 += "/" + item; } + if (Directory.Exists(dir2) == false) Directory.CreateDirectory(dir2); + } + } + #endregion + + #region Զ + public static void AutoRunExe(string key, string filePath, bool IsRun) + { + try + { + RegistryKey HKLM = Registry.LocalMachine; + RegistryKey Run = HKLM.CreateSubKey(@"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Run"); + if (Run != null) + { + if (IsRun == true) + { + Run.SetValue(key, filePath); + } + else + { + object obj = Run.GetValue(key); + if (obj != null) Run.DeleteValue(key); + } + } + Run = HKLM.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run"); + if (Run == null) return; + if (IsRun == true) + { + Run.SetValue(key, filePath); + } + else + { + object obj = Run.GetValue(key); + if (obj != null) Run.DeleteValue(key); + } + } + catch (Exception ex) + { + ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message); + } + + } + #endregion + #region ת + public static string ConvertWeek(DayOfWeek Week) + { + switch (Week) + { + case DayOfWeek.Sunday: + return ""; + case DayOfWeek.Monday: + return "һ"; + case DayOfWeek.Tuesday: + return ""; + case DayOfWeek.Wednesday: + return ""; + case DayOfWeek.Thursday: + return ""; + case DayOfWeek.Friday: + return ""; + case DayOfWeek.Saturday: + return ""; + default: + break; + } + return ""; + } + #endregion + #region Զ¼ + public static void CheckUpdate(string UpdateFileName) + { + try + { + string SetupPath = AppDomain.CurrentDomain.BaseDirectory + "Setup.ini"; + string VersionPath = AppDomain.CurrentDomain.BaseDirectory + "Version.ini"; + string CilentName = ConfigurationSourceSection.LoadXml_Attribute(SetupPath, "CilentName"); + string UpdateDirectory = ConfigurationSourceSection.LoadXml_Attribute(SetupPath, "UpdateDirectory"); + string UpdateUrl = ConfigurationSourceSection.LoadXml_Attribute(SetupPath, "UpdateUrl"); + if (string.IsNullOrEmpty(CilentName) == true) + { + System.Net.IPHostEntry IpEntry = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()); + if (IpEntry.AddressList.Length > 0) + { + for (int i = IpEntry.AddressList.Length - 1; i >= 0; i--) + { + System.Net.IPAddress ip = IpEntry.AddressList[i]; + if (ip.IsIPv6LinkLocal == true || ip.IsIPv6SiteLocal == true || ip.IsIPv6Multicast == true || ip.IsIPv6Teredo == true) continue; + CilentName += ip.ToString(); + break; + } + } + } + decimal Version = 0; + string ver = ConfigurationSourceSection.LoadXml_Attribute(VersionPath, "Version"); + if (string.IsNullOrEmpty(ver) == false) Version = Convert.ToDecimal(ver); + US.UpdateService ser = new US.UpdateService(); + ser.Url = UpdateUrl; + bool bk = ser.CheckVer(CilentName, UpdateDirectory, Version); + if (bk == true) + { + ConfigurationSourceSection.SaveXml_Attribute(SetupPath, "IsInit", "1", false); + string hzexe = AppDomain.CurrentDomain.BaseDirectory + UpdateFileName + ".exe"; + OpenFile(hzexe); + System.Diagnostics.Process.GetCurrentProcess().Kill(); + } + else + { + ErrorFollow.DeleteTempFile(7); + string hzexe2 = AppDomain.CurrentDomain.BaseDirectory + UpdateFileName + "2.exe"; + if (File.Exists(hzexe2) == false) return; + string hzexe = AppDomain.CurrentDomain.BaseDirectory + UpdateFileName + ".exe"; + while (true) + { + if (SystemInfo.IsProcessRunning(UpdateFileName) == false) + { + File.Delete(hzexe); + File.Move(hzexe2, hzexe); + return; + } + Thread.Sleep(2000); + } + } + } + catch (Exception ex) + { + ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message); + ErrorFollow.DeleteTempFile(7); + } + } + #endregion + + #region Base64ıתͨı + /// + /// Base64ıתͨı + /// + /// Base64ı + /// + public static string Base64StringToString(string base64) + { + //char[] charBuffer = base64.ToCharArray(); + //byte[] bytes = Convert.FromBase64CharArray(charBuffer, 0, charBuffer.Length); + //return (new UnicodeEncoding()).GetString(bytes); + try + { + + byte[] c = Convert.FromBase64String(base64); + string a = System.Text.Encoding.UTF8.GetString(c); + a = a.Replace("sel0ect", "select").Replace("whe0re", "where").Replace("fro0m", "from").Replace("lef0t", "left").Replace("inn0er", "inner").Replace("joi0n", "join"); + return a; + } + catch (Exception ex) + { + return base64; + } + } + #endregion + #region ͨıתBase64ı + /// + /// ͨıתBase64ı + /// + /// Base64ı + /// + public static string StringToBase64String(string base64) + { + //base64 = ""; + byte[] bytes = Encoding.UTF8.GetBytes(base64); + string str = Convert.ToBase64String(bytes); + //ErrorFollow.TraceWrite("StringToBase64String", "", str); + return str; + } + #endregion + + + #region Base64ıתByte[] + /// + /// Base64ıתByte[] + /// + /// Base64ı + /// + public static Byte[] Base64ToBytes(string base64) + { + char[] charBuffer = base64.ToCharArray(); + byte[] bytes = Convert.FromBase64CharArray(charBuffer, 0, charBuffer.Length); + return bytes; + } + #endregion + #region Byte[]תBase64ı + /// + /// Base64ıתByte[] + /// + /// Base64ı + /// + public static string BytesToBase64(byte[] charBuffer) + { + string a = Convert.ToBase64String(charBuffer); + return a; + } + #endregion + #region ͼƬתbase64 + public static string bitmapToBase64(string filePath) + { + //Bitmap bmp = new Bitmap(filePath); + //BinaryFormatter binFormatter = new BinaryFormatter(); + //MemoryStream memStream = new MemoryStream(); + //binFormatter.Serialize(memStream, bmp); + //byte[] bytes = memStream.GetBuffer(); + byte[] bytes = GetOffice(filePath); + //string s = ""; + //int index = 0; + //foreach (var item in bytes) + //{ + // if (index > 10) break; + // index++; + // s += item.ToString() + ","; + //} + //ErrorFollow.TraceWrite("StringToBase64String", "", s); + //ErrorFollow.TraceWrite("StringToBase64String", "鳤", bytes.Length.ToString()); + string base64 = Convert.ToBase64String(bytes); + //ErrorFollow.TraceWrite("StringToBase64String", "ַ", base64.Length.ToString()); + return base64; + } + #endregion + #region base64תͼƬ + public static Bitmap Base64ToBitmap(string ImageBase64) + { + try + { + byte[] bytes = CustomIO.Base64ToBytes(ImageBase64); + Bitmap bmp = CustomIO.GetPhoto(bytes); + return bmp; + } + catch (Exception ex) + { + ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message); + } + return null; + } + #endregion + + #region תд + public static string ConvertUpperNumer(string x) + { + string strChnNames = "һ߰˾"; + string strNumNames = "0123456789"; + int index = strNumNames.IndexOf(x); + if (index < 0) return ""; + return Convert.ToString(strChnNames[index]); + } + #endregion + #region дת + public static string ConvertUpperNumer2(string x) + { + string strChnNames = "һ߰˾"; + string strNumNames = "0123456789"; + int index = strChnNames.IndexOf(x); + if (index < 0) return ""; + return Convert.ToString(strNumNames[index]); + } + #endregion + + #region UTCתʱ + public static DateTime ConvertTimeStampToDateTime(long timeStamp) + { + DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // ʱ + DateTime dt = startTime.AddMilliseconds(timeStamp); + return dt; + } + #endregion + #region ʱתUTC + public static long GetTimeStamp(DateTime dt) + { + TimeSpan ts = dt.AddHours(-8) - new DateTime(1970, 1, 1, 0, 0, 0, 0); + return Convert.ToInt64(ts.TotalMilliseconds); + } + #endregion + #region ʱתUTC + public static long GetTimeStamp(DateTime dt, string TimeType) + { + TimeSpan ts = dt.AddHours(-8) - new DateTime(1970, 1, 1, 0, 0, 0, 0); + if (TimeType == "TotalSeconds") return Convert.ToInt64(ts.TotalSeconds); + return Convert.ToInt64(ts.TotalMilliseconds); + } + #endregion + + #region תĴд + /// + /// תĴд + /// + /// eg:10.74 + /// + public static string MoneyToUpper(string LowerMoney) + { + string functionReturnValue = null; + bool IsNegative = false; // ǷǸ + if (LowerMoney.Trim().Substring(0, 1) == "-") + { + // ǸתΪ + LowerMoney = LowerMoney.Trim().Remove(0, 1); + IsNegative = true; + } + string strLower = null; + string strUpart = null; + string strUpper = null; + int iTemp = 0; + // λС 123.489123.49123.4123.4 + LowerMoney = Math.Round(double.Parse(LowerMoney), 2).ToString(); + if (LowerMoney.IndexOf(".") > 0) + { + if (LowerMoney.IndexOf(".") == LowerMoney.Length - 2) + { + LowerMoney = LowerMoney + "0"; + } + } + else + { + LowerMoney = LowerMoney + ".00"; + } + strLower = LowerMoney; + iTemp = 1; + strUpper = ""; + while (iTemp <= strLower.Length) + { + switch (strLower.Substring(strLower.Length - iTemp, 1)) + { + case ".": + strUpart = "Բ"; + break; + case "0": + strUpart = ""; + break; + case "1": + strUpart = "Ҽ"; + break; + case "2": + strUpart = ""; + break; + case "3": + strUpart = ""; + break; + case "4": + strUpart = ""; + break; + case "5": + strUpart = ""; + break; + case "6": + strUpart = "½"; + break; + case "7": + strUpart = ""; + break; + case "8": + strUpart = ""; + break; + case "9": + strUpart = ""; + break; + } + + switch (iTemp) + { + case 1: + strUpart = strUpart + ""; + break; + case 2: + strUpart = strUpart + ""; + break; + case 3: + strUpart = strUpart + ""; + break; + case 4: + strUpart = strUpart + ""; + break; + case 5: + strUpart = strUpart + "ʰ"; + break; + case 6: + strUpart = strUpart + ""; + break; + case 7: + strUpart = strUpart + "Ǫ"; + break; + case 8: + strUpart = strUpart + ""; + break; + case 9: + strUpart = strUpart + "ʰ"; + break; + case 10: + strUpart = strUpart + ""; + break; + case 11: + strUpart = strUpart + "Ǫ"; + break; + case 12: + strUpart = strUpart + ""; + break; + case 13: + strUpart = strUpart + "ʰ"; + break; + case 14: + strUpart = strUpart + ""; + break; + case 15: + strUpart = strUpart + "Ǫ"; + break; + case 16: + strUpart = strUpart + ""; + break; + default: + strUpart = strUpart + ""; + break; + } + + strUpper = strUpart + strUpper; + iTemp = iTemp + 1; + } + + strUpper = strUpper.Replace("ʰ", ""); + strUpper = strUpper.Replace("", ""); + strUpper = strUpper.Replace("Ǫ", ""); + strUpper = strUpper.Replace("", ""); + strUpper = strUpper.Replace("", ""); + strUpper = strUpper.Replace("", ""); + strUpper = strUpper.Replace("", ""); + strUpper = strUpper.Replace("", ""); + strUpper = strUpper.Replace("Բ", "Բ"); + strUpper = strUpper.Replace("Բ", "Բ"); + strUpper = strUpper.Replace("", ""); + strUpper = strUpper.Replace("Բ", "Բ"); + strUpper = strUpper.Replace("", ""); + strUpper = strUpper.Replace("", ""); + strUpper = strUpper.Replace("Բ", "Բ"); + strUpper = strUpper.Replace("", ""); + + // ҼԲµĽĴ + if (strUpper.Substring(0, 1) == "Բ") + { + strUpper = strUpper.Substring(1, strUpper.Length - 1); + } + if (strUpper.Substring(0, 1) == "") + { + strUpper = strUpper.Substring(1, strUpper.Length - 1); + } + if (strUpper.Substring(0, 1) == "") + { + strUpper = strUpper.Substring(1, strUpper.Length - 1); + } + if (strUpper.Substring(0, 1) == "") + { + strUpper = strUpper.Substring(1, strUpper.Length - 1); + } + if (strUpper.Substring(0, 1) == "") + { + strUpper = "Բ"; + } + functionReturnValue = strUpper; + + if (IsNegative == true) + { + return "" + functionReturnValue; + } + else + { + return functionReturnValue; + } + } + #endregion + + #region webHTTP + public static string GetWebService(string url, string methodName, Dictionary param, string Namespace, out string ErrorMessage) + { + ErrorMessage = ""; + if (string.IsNullOrEmpty(url) == true) + { + ErrorFollow.TraceWrite("", methodName, "url"); + return "url"; + } + if (string.IsNullOrEmpty(Namespace) == true) Namespace = "http://tempuri.org/"; + string ex = url.Substring(url.Length - 5); + + try + { + StringBuilder requestBuider = new StringBuilder(); + requestBuider.Append(""); + if (ex == ".asmx") + { + requestBuider.Append(""); + requestBuider.Append(""); + requestBuider.Append("<").Append(methodName).Append(" xmlns=\"" + Namespace + "\">"); + } + else + { + //requestBuider.Append(""); + ////requestBuider.Append(""); + //requestBuider.Append(""); + //requestBuider.Append(""); + requestBuider.Append(""); + requestBuider.Append(""); + requestBuider.Append("<").Append(methodName).Append(" xmlns=\"" + Namespace + "\">"); + + } + foreach (KeyValuePair item in param) + { + if (item.Value == "") + { + if (ex == ".asmx") + { + requestBuider.Append("<").Append(item.Key).Append(" />"); + } + else + { + requestBuider.Append("<").Append(item.Key).Append(" xmlns=\"\" />"); + } + } + else + { + if (ex == ".asmx") + { + requestBuider.Append("<").Append(item.Key).Append(">"); + } + else + { + requestBuider.Append("<").Append(item.Key).Append(" xmlns=\"\" >"); + } + requestBuider.Append(item.Value); + requestBuider.Append(""); + } + } + if (ex == ".asmx") + { + requestBuider.Append(""); + requestBuider.Append(""); + requestBuider.Append(""); + } + else + { + //requestBuider.Append(""); + //requestBuider.Append(""); + //requestBuider.Append(""); + requestBuider.Append(""); + requestBuider.Append(""); + requestBuider.Append(""); + } + + string val = requestBuider.ToString(); + XmlDocument docdata = new XmlDocument(); + docdata.LoadXml(val); + byte[] data = Encoding.UTF8.GetBytes(docdata.OuterXml); + HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url); + myRequest.Method = "POST"; //GET,POST + if (ex == ".asmx") + { + myRequest.ContentType = "text/xml; charset=utf-8;"; + } + else + { + myRequest.ContentType = "application/soap+xml;charset=utf-8;action=\"" + Namespace + methodName + "\""; + } + + myRequest.Credentials = CredentialCache.DefaultCredentials; + myRequest.KeepAlive = true; + myRequest.Timeout = 600000; + myRequest.Headers.Add("Accept-Language: zh-CN"); + if (Namespace.EndsWith("/") == false) Namespace += "/"; + if (ex == ".asmx") + { + myRequest.Headers.Add("SOAPAction:\"" + Namespace + methodName + "\""); + } + Stream stream = myRequest.GetRequestStream(); + stream.Write(data, 0, data.Length); + stream.Close(); + + //ýӿڷֵ + HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse(); + Stream myResponseStream = myResponse.GetResponseStream(); + StreamReader reader = new StreamReader(myResponseStream, Encoding.UTF8); + string content = reader.ReadToEnd(); + reader.Close(); + myResponseStream.Close(); + myRequest.Abort(); + myResponse.Close(); + XmlDocument doc = new XmlDocument(); + doc.LoadXml(content); + return doc.InnerText; + } + catch (WebException e) + { + if (e.Response == null) + { + ErrorMessage = e.Message; + } + else + { + Stream myResponseStream = e.Response.GetResponseStream(); + StreamReader reader = new StreamReader(myResponseStream, Encoding.UTF8); + ErrorMessage = reader.ReadToEnd(); + if (ErrorMessage == "") ErrorMessage = e.Message; + } + } + return ""; + } + #endregion + #region webHTTP1.2 + public static string GetWebService2(string url, string methodName, Dictionary param, string Namespace, string SOAPAction, out string ErrorMessage) + { + ErrorMessage = ""; + if (string.IsNullOrEmpty(url) == true) + { + ErrorFollow.TraceWrite("", methodName, "url"); + return "url"; + } + if (string.IsNullOrEmpty(Namespace) == true) Namespace = "http://tempuri.org/"; + //string ex = url.Substring(url.Length - 5); + + try + { + StringBuilder requestBuider = new StringBuilder(); + requestBuider.Append(""); + requestBuider.Append(""); + requestBuider.Append(""); + requestBuider.Append(""); + requestBuider.Append(""); + foreach (KeyValuePair item in param) + { + if (item.Value == "") + { + requestBuider.Append("<").Append(item.Key).Append(" xmlns=\"\" />"); + } + else + { + requestBuider.Append("<").Append(item.Key).Append(" xmlns=\"\" >"); + requestBuider.Append(item.Value); + requestBuider.Append(""); + } + } + requestBuider.Append(""); + requestBuider.Append(""); + requestBuider.Append(""); + + string val = requestBuider.ToString(); + XmlDocument docdata = new XmlDocument(); + docdata.LoadXml(val); + byte[] data = Encoding.UTF8.GetBytes(docdata.OuterXml); + HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url); + myRequest.Method = "POST"; //GET,POST + myRequest.ContentType = "text/xml;charset=utf-8;"; + myRequest.Headers.Add("SOAPAction:\"" + SOAPAction + "\""); + myRequest.Credentials = CredentialCache.DefaultCredentials; + myRequest.KeepAlive = true; + myRequest.Timeout = 600000; + myRequest.Headers.Add("Accept-Language: zh-CN"); + Stream stream = myRequest.GetRequestStream(); + stream.Write(data, 0, data.Length); + stream.Close(); + + //ýӿڷֵ + HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse(); + Stream myResponseStream = myResponse.GetResponseStream(); + StreamReader reader = new StreamReader(myResponseStream, Encoding.UTF8); + string content = reader.ReadToEnd(); + reader.Close(); + myResponseStream.Close(); + myRequest.Abort(); + myResponse.Close(); + XmlDocument doc = new XmlDocument(); + doc.LoadXml(content); + return doc.InnerText; + } + catch (WebException e) + { + if (e.Response == null) + { + ErrorMessage = e.Message; + } + else + { + Stream myResponseStream = e.Response.GetResponseStream(); + StreamReader reader = new StreamReader(myResponseStream, Encoding.UTF8); + ErrorMessage = reader.ReadToEnd(); + if (ErrorMessage == "") ErrorMessage = e.Message; + } + } + return ""; + } + #endregion + #region xmlת + public static string XmlFilter(string value) + { + string str = value.Replace("&", "&"); + str = str.Replace("<", "<"); + str = str.Replace(">", ">"); + str = str.Replace("'", "'"); + str = str.Replace("\"", """); + return str; + } + #endregion + #region ַתutf-8 + public static string StringToUTF8(String str) + { + char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; + + Encoding utf8 = Encoding.UTF8; + + StringBuilder result = new StringBuilder(); + + for (int i = 0; i < str.Length; i++) + { + string sub = str.Substring(i, 1); + byte[] bytes = utf8.GetBytes(sub); + + if (bytes.Length == 1) //ͨӢĸ + { + result.Append(sub); + } + else //ַתΪ + { + for (int j = 0; j < bytes.Length; j++) + { + result.Append("%" + hexDigits[bytes[j] >> 4] + hexDigits[bytes[j] & 0XF]); + } + } + } + return result.ToString(); + } + #endregion + #region URLת + /// + /// ѯַתΪֵ. + /// + /// + /// + /// + public static Dictionary GetQueryString(string queryString, Encoding encoding) + { + if (encoding != null) queryString = HttpUtility.UrlDecode(queryString, encoding); + var result = new Dictionary(); + int sindex = queryString.IndexOf("?"); + result["url"] = queryString.Substring(0, sindex); + queryString = queryString.Substring(sindex + 1); + if (!string.IsNullOrEmpty(queryString)) + { + int count = queryString.Length; + for (int i = 0; i < count; i++) + { + int startIndex = i; + int index = -1; + while (i < count) + { + char item = queryString[i]; + if (item == '=') + { + if (index < 0) + { + index = i; + } + } + else if (item == '&') + { + break; + } + i++; + } + string key = null; + string value = null; + if (index >= 0) + { + key = queryString.Substring(startIndex, index - startIndex); + value = queryString.Substring(index + 1, (i - index) - 1); + } + else + { + key = queryString.Substring(startIndex, i - startIndex); + } + result[key] = value; + if ((i == (count - 1)) && (queryString[i] == '&')) + { + result[key] = string.Empty; + } + } + } + return result; + } + #endregion + + #region PDFתͼƬ + /// + /// PDFĵתΪͼƬķ + /// + /// PDFļ· + /// ͼƬ· + /// ͼƬ + /// PDFĵĵڼҳʼת + /// PDFĵĵڼҳʼֹͣת + /// ͼƬʽ + /// ͼƬȣԽԽ + public static void ConvertPDF2Image(string pdfInputPath, string imageOutputPath, + string imageName, int startPageNum, int endPageNum, ImageFormat imageFormat, int quality) + { + PDFFile pdfFile = PDFFile.Open(pdfInputPath); + + if (!Directory.Exists(imageOutputPath)) + { + Directory.CreateDirectory(imageOutputPath); + } + + // validate pageNum + if (startPageNum <= 0) + { + startPageNum = 1; + } + + if (endPageNum > pdfFile.PageCount) + { + endPageNum = pdfFile.PageCount; + } + + if (startPageNum > endPageNum) + { + int tempPageNum = startPageNum; + startPageNum = endPageNum; + endPageNum = startPageNum; + } + + // start to convert each page + for (int i = startPageNum; i <= endPageNum; i++) + { + Bitmap pageImage = pdfFile.GetPageImage(i - 1, 56 * quality); + pageImage.Save(imageOutputPath + imageName + i.ToString() + "." + imageFormat.ToString(), imageFormat); + pageImage.Dispose(); + } + pdfFile.Dispose(); + } + #endregion + + #region ȡ· + public static int GetMonthDays(string YearMonth) + { + DateTime dtNow = Convert.ToDateTime(YearMonth + "-01"); + int days = DateTime.DaysInMonth(dtNow.Year, dtNow.Month); + return days; + } + #endregion + + #region ֵ̬ + public static void ModelProperty(T model, string PropertyName, object value) + { + Type t = typeof(T); + PropertyInfo info = t.GetProperty(PropertyName); + info.SetValue(model, value, null); + } + #endregion + #region --ڵ + public static string PadString(string key, int Layer) + { + if (Layer <= 0) return ""; + string str = ""; + for (int i = 0; i < Layer; i++) + { + str += key; + } + return str; + } + #endregion + + //#region DateTimeתΪʱ(ֵ) + //public static long DateToTicks(DateTime? time) + //{ + // return ((time.HasValue ? time.Value.Ticks : DateTime.Parse("1990-01-01").Ticks) - 621355968000000000) / 10000; + //} + //#endregion + + //#region ʱ(ֵ)StringתΪDateTimeת + //public static DateTime TicksToDate(string time) + //{ + // return new DateTime((Convert.ToInt64(time) * 10000) + 621355968000000000); + //} + //#endregion + + #region ߵµͼweb + public static void MathRange_Amap(string webkey, decimal CurrentPositionX, decimal CurrentPositionY, decimal TargetPositionX, decimal TargetPositionY, out long Range, out string RangeName) + { + Range = 0; + RangeName = ""; + string url = "https://restapi.amap.com/v3/direction/driving?key=" + webkey + "&origin=" + CurrentPositionX + "," + CurrentPositionY + "&destination=" + TargetPositionX + "," + TargetPositionY + "&originid=&destinationid=&extensions=base&strategy=0&waypoints=&avoidpolygons=&avoidroad="; + string ErrorMessage = ""; + string jsonContent = CustomIO.HttpRequest(url, "GET", "application/x-www-form-urlencoded", null, System.Net.HttpVersion.Version10, null, out ErrorMessage); + if (string.IsNullOrEmpty(ErrorMessage) == false) + { + ErrorFollow.TraceWrite("ߵµͼ", "", ErrorMessage); + return; + } + var joRoot = (JObject)JsonConvert.DeserializeObject(jsonContent); + JArray jArray = JArray.Parse(joRoot["route"]["paths"].ToString()); + Range = jArray.First.Value("distance"); + if (Range < 1000) { RangeName = Range + ""; return; } + double a = Convert.ToDouble(Range) / Convert.ToDouble(1000); + RangeName = a.ToString("0.##") + ""; + } + #endregion + + + + #region AES + /// + /// AES + /// + /// ַ + /// Կ + /// ƫ + /// ָҪڼܵĿģʽ + /// ָϢݿڼֽܲʱҪӦõ + /// + public static byte[] AesEncrypt(byte[] str, byte[] key, byte[] iv, CipherMode mode, PaddingMode padding) + { + if (str == null || str.Length == 0) return null; + + RijndaelManaged toEncrypt = new RijndaelManaged(); + toEncrypt.Key = key; + toEncrypt.Mode = mode; + toEncrypt.Padding = padding; + toEncrypt.IV = iv; + + ICryptoTransform cTransform = toEncrypt.CreateEncryptor(); + byte[] resultArray = cTransform.TransformFinalBlock(str, 0, str.Length); + + return resultArray; + } + #endregion + #region AES + /// + /// AES + /// + /// ģܣ + /// Կ + /// ƫ + /// ָҪڼܵĿģʽ + /// ָϢݿڼֽܲʱҪӦõ + /// + public static byte[] AesDecrypt(byte[] str, byte[] key, byte[] iv, CipherMode mode, PaddingMode padding) + { + if (str == null || str.Length == 0) return null; + + RijndaelManaged toDecrypt = new RijndaelManaged(); + toDecrypt.Key = key; + toDecrypt.Mode = mode; + toDecrypt.Padding = padding; + toDecrypt.IV = iv; + + ICryptoTransform cTransform = toDecrypt.CreateDecryptor(); + Byte[] resultArray = cTransform.TransformFinalBlock(str, 0, str.Length); + + return resultArray; + } + #endregion + + #region ֤Ϣ + public static BirthdayAgeSex GetBirthdayAgeSex(string identityCard) + { + try + { + if (string.IsNullOrEmpty(identityCard)) + { + return null; + } + else + { + if (identityCard.Length != 18)//ֻ֤Ϊ15λ18λϷ + { + return null; + } + } + + BirthdayAgeSex entity = new BirthdayAgeSex(); + string strSex = string.Empty; + entity.Birthday = identityCard.Substring(6, 4) + "-" + identityCard.Substring(10, 2) + "-" + identityCard.Substring(12, 2); + strSex = identityCard.Substring(16, 1); + + entity.Age = CalculateAge(entity.Birthday);//ռ + if (IsOne(int.Parse(strSex)) == false)//ԱΪżŮΪ + { + entity.Sex = "Ů"; + } + else + { + entity.Sex = ""; + } + return entity; + } + catch (Exception ex) + { + ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message); + } + return new BirthdayAgeSex(); + } + public static int CalculateAge(string birthDay) + { + DateTime birthDate = DateTime.Parse(birthDay); + DateTime nowDateTime = DateTime.Now; + int age = nowDateTime.Year - birthDate.Year; + //ٿ¡ + if (nowDateTime.Month < birthDate.Month || (nowDateTime.Month == birthDate.Month && nowDateTime.Day < birthDate.Day)) + { + age--; + } + return age; + } + #endregion + + #region ȡֵ + public static dynamic GetPropertyValue(T obj, PropertyInfo info, string propertyName) + { + //var info = obj.GetType().GetProperty(propertyName); + if (info == null) return null; + object value = info.GetValue(obj, null); + if (value == null) return null; + if (info.PropertyType == typeof(byte[])) return (byte[])info.GetValue(obj, null); + if (info.PropertyType == typeof(string)) return Convert.ToString(info.GetValue(obj, null)); + if (info.PropertyType == typeof(byte) || info.PropertyType == typeof(Nullable)) return Convert.ToByte(info.GetValue(obj, null)); + if (info.PropertyType == typeof(Int16) || info.PropertyType == typeof(Nullable)) return Convert.ToInt16(info.GetValue(obj, null)); + if (info.PropertyType == typeof(int) || info.PropertyType == typeof(Nullable)) return Convert.ToInt32(info.GetValue(obj, null)); + if (info.PropertyType == typeof(Int64) || info.PropertyType == typeof(Nullable)) return Convert.ToInt64(info.GetValue(obj, null)); + if (info.PropertyType == typeof(bool) || info.PropertyType == typeof(Nullable)) return Convert.ToBoolean(info.GetValue(obj, null)); + if (info.PropertyType == typeof(decimal) || info.PropertyType == typeof(Nullable)) return Convert.ToBoolean(info.GetValue(obj, null)); + if (info.PropertyType == typeof(Double) || info.PropertyType == typeof(Nullable)) return Convert.ToBoolean(info.GetValue(obj, null)); + if (info.PropertyType == typeof(Single) || info.PropertyType == typeof(Nullable)) return Convert.ToBoolean(info.GetValue(obj, null)); + if (info.PropertyType == typeof(DateTime) || info.PropertyType == typeof(Nullable)) return Convert.ToBoolean(info.GetValue(obj, null)); + return info.GetValue(obj, null); + } + #endregion + #region SQLؼּ + public static bool CheckSQL(string str, bool IsSort) + { + var str2 = str.ToLower(); + if (CheckKey(str2, "delete")) return false; + if (CheckKey(str2, "update")) return false; + if (str2.Contains("--")) return false; + if (str2.Contains(";")) return false; + if (CheckKey(str2, "insert")) return false; + if (str2.Contains("drop table")) return false; + if (IsSort == true && str2.Contains("select")) return false; + return true; + } + public static bool CheckKey(string str, string key) + { + int index = 0; + var str2 = str; + while (index >= 0) + { + if (index > 0) str2 = str2.Substring(index); + index = str2.IndexOf(key); + if (index == -1) return false; + string st = ""; + string et = ""; + if (index > 0) st = str2.Substring(index - 1, 1); + if (index + key.Length < str2.Length) et = str2.Substring(index + key.Length, 1); + if (st == "\n" || st == " ") st = ""; + if (et == "\n" || et == " ") et = ""; + if (st == "" && et == "") return true; + index += key.Length; + } + return false; + } + #endregion + + #region Dictionary + public static void DictionaryAdd(Dictionary pdata1, string key, WordText value) + { + if (pdata1.ContainsKey(key)==true) + { + var e = pdata1[key]; + if (string.IsNullOrEmpty(e.Text)==true) + { + pdata1.Remove(key); + ErrorFollow.TraceWrite("DictionaryѾ", "key:" + key, "ȥԭֵʹ:" + value.ToJsonString()); + } + else + { + ErrorFollow.TraceWrite("DictionaryѾ", "key:" + key, "ʹ:" + e.ToJsonString() + ";:" + value.ToJsonString()); + return; + } + } + pdata1.Add(key, value); + } + #endregion + #region Dictionary + public static void DictionaryAdd(Dictionary pdata1, string key, string value) + { + if (pdata1.ContainsKey(key) == true) + { + var e = pdata1[key]; + if (string.IsNullOrEmpty(e) == true) + { + pdata1.Remove(key); + ErrorFollow.TraceWrite("DictionaryѾ", "key:" + key, "ȥԭֵʹ:" + value); + } + else + { + ErrorFollow.TraceWrite("DictionaryѾ", "key:" + key,"ʹ:"+ e + ";:" + value); + return; + } + } + pdata1.Add(key, value); + } + #endregion + + } + + + + #region ϴļϢ + public class UserFileInfo + { + private string m_OldFileName; + /// + /// Ŀ¼+ļ + /// + public string OldFileName + { + get { return m_OldFileName; } + set { m_OldFileName = value; } + } + private string m_FileName; + /// + /// Ŀ¼+ļ + /// + public string FileName + { + get { return m_FileName; } + set { m_FileName = value; } + } + private string m_Extension; + /// + /// ļչ + /// + public string Extension + { + get { return m_Extension; } + set { m_Extension = value; } + } + /// + /// ļС + /// + public string FileSizeName + { + get { return ConvertByte(FileSize); } + } + private long m_FileSize; + /// + /// ļС + /// + public long FileSize + { + get { return m_FileSize; } + set { m_FileSize = value; } + } + + #region תλ + string ConvertByte(long seek) + { + if (seek > 1024 * 1024 * 1024) + { + return Convert.ToDouble(Convert.ToDouble(seek) / Convert.ToDouble(1024) / Convert.ToDouble(1024) / Convert.ToDouble(1024)).ToString("f2") + "GB"; + } + if (seek > 1024 * 1024) + { + return Convert.ToDouble(Convert.ToDouble(seek) / Convert.ToDouble(1024) / Convert.ToDouble(1024)).ToString("f2") + "MB"; + } + if (seek > 1024) + { + return Convert.ToDouble(Convert.ToDouble(seek) / Convert.ToDouble(1024)).ToString("f2") + "KB"; + } + return seek.ToString() + "Byte"; + } + #endregion + + + #region + public static List GetUserFileInfo(string infoString, string NewDirectoryName) + { + //ļв,ļ + string ServerDirectoryPath = AppDomain.CurrentDomain.BaseDirectory + NewDirectoryName; + if (!Directory.Exists(ServerDirectoryPath)) + { + Directory.CreateDirectory(ServerDirectoryPath); + } + + List list = new List(); + string[] ss = infoString.Split(','); + foreach (string s in ss) + { + string[] sss = s.Split(Convert.ToChar("")); + string filePath = AppDomain.CurrentDomain.BaseDirectory + sss[0]; + string ServerfilePath = AppDomain.CurrentDomain.BaseDirectory + NewDirectoryName + "/" + System.IO.Path.GetFileName(sss[0]); + if (filePath != ServerfilePath) System.IO.File.Move(filePath, ServerfilePath); + FileInfo file = new FileInfo(filePath); + UserFileInfo uf = new UserFileInfo(); + uf.OldFileName = sss[1]; + uf.FileName = NewDirectoryName + "/" + System.IO.Path.GetFileName(sss[0]); + uf.FileSize = file.Length; + uf.Extension = file.Extension; + list.Add(uf); + } + return list; + } + #endregion + + #region () + public static List GetUserFileInfo_ForGuangJi(string infoString, string NewDirectoryName) + { + //ļв,ļ + string ServerDirectoryPath = AppDomain.CurrentDomain.BaseDirectory + NewDirectoryName; + if (!Directory.Exists(ServerDirectoryPath)) + { + Directory.CreateDirectory(ServerDirectoryPath); + } + + List list = new List(); + string[] ss = infoString.Split(','); + foreach (string s in ss) + { + string[] sss = s.Split(Convert.ToChar("")); + string filePath = AppDomain.CurrentDomain.BaseDirectory + sss[0]; + + string OldName = System.IO.Path.GetFileName(sss[1]); + int index1 = OldName.LastIndexOf('.'); + string NewFileName = OldName.Substring(0, index1) + DateTime.Now.ToString().Replace(':', '-') + OldName.Substring(index1); + string ServerfilePath = AppDomain.CurrentDomain.BaseDirectory + NewDirectoryName + "/" + NewFileName; + UserFileInfo uf = new UserFileInfo(); + FileInfo file = new FileInfo(filePath); + uf.OldFileName = sss[1]; + uf.FileName = NewDirectoryName + "/" + NewFileName; + uf.FileSize = file.Length; + uf.Extension = file.Extension; + if (filePath != ServerfilePath) System.IO.File.Move(filePath, ServerfilePath); + list.Add(uf); + } + return list; + } + #endregion + } + #endregion + #region ֤Ϣ + public class BirthdayAgeSex + { + public string Birthday { get; set; } + public int Age { get; set; } + public string Sex { get; set; } + } + #endregion + + +} diff --git a/基础类库/HuizhongLibrary/DataCache.cs b/基础类库/HuizhongLibrary/DataCache.cs new file mode 100644 index 0000000..11d88e5 --- /dev/null +++ b/基础类库/HuizhongLibrary/DataCache.cs @@ -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 DataConnection = new Dictionary(); + public static int ConnectNumber = 0; + public static int MaxConnectNumber = 0; + + } +} diff --git a/基础类库/HuizhongLibrary/DataConvert.cs b/基础类库/HuizhongLibrary/DataConvert.cs new file mode 100644 index 0000000..d4d30d3 --- /dev/null +++ b/基础类库/HuizhongLibrary/DataConvert.cs @@ -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)) + { + /* + * 最好把所有的特殊HTML标记都找出来,然后把与其相对应的Unicode字符一起影射到Hash表内,最后一起都替换掉 + */ + + //先单独测试,成功后,再把所有模式合并 + + //注:这两个必须单独处理 + //去掉嵌套了HTML标记的JavaScript:() + //去掉css标记:() + //去掉css标记:\\..*\\{[\\s\\S]*\\} + htmlStream = Regex.Replace(htmlStream, "()|()", " ", RegexOptions.IgnoreCase); + //htmlStream = RemoveTag(htmlStream, "script"); + //htmlStream = RemoveTag(htmlStream, "style"); + + //去掉普通HTML标记:<[^>]+> + //替换空格: |&|­| |­ + htmlStream = Regex.Replace(htmlStream, "<[^>]+>| |&|­| |­|•|<|>", " ", RegexOptions.IgnoreCase); + //htmlStream = RemoveTag(htmlStream); + + //替换左尖括号 + //htmlStream = Regex.Replace(htmlStream, "<", "<"); + + //替换右尖括号 + //htmlStream = Regex.Replace(htmlStream, ">", ">"); + + //替换空行 + //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 where = new Dictionary(); + where.Add(@"

", ""); + where.Add(@"

", ""); + where.Add(@"

", ""); + where.Add(@"", ""); + where.Add(@"", ""); + where.Add(@"", ""); + where.Add(@"", ""); + where.Add(@"", ""); + where.Add(@"", ""); + where.Add(@"", ""); + where.Add(@"", ""); + where.Add(@"", ""); + where.Add(@"", ""); + where.Add(@"", ""); + where.Add(@"", ""); + where.Add(@"", ""); + where.Add(@"", ""); + where.Add(@"", ""); + where.Add(@"", ""); + where.Add(@"", ""); + where.Add(@"<.xml:namespace .+?>", ""); + where.Add(@"", ""); + where.Add(@"", ""); + where.Add(@"\r", ""); + where.Add(@"\n", ""); + where.Add(@"\t", ""); + where.Add(@" ", " "); + where.Add(@"<", "<"); + where.Add(@">", ">"); + foreach (string s in where.Keys) + { + value = Regex.Replace(value, s, where[s], RegexOptions.IgnoreCase); + } + return value; + } + #endregion + + /// + /// 转换空值 + /// + /// 校验值 + /// 如果是空值,那么用这个值替换 + /// + 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(); + } + + + /// + /// 十六进制转换到十进制 + /// + /// + /// + 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; + } + } + + /// + /// 从十进制转换到十六进制 + /// + /// + /// + 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 ""; + } + } + + } +} diff --git a/基础类库/HuizhongLibrary/DataEventArgs.cs b/基础类库/HuizhongLibrary/DataEventArgs.cs new file mode 100644 index 0000000..b7f015b --- /dev/null +++ b/基础类库/HuizhongLibrary/DataEventArgs.cs @@ -0,0 +1,84 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data; + +namespace HuizhongLibrary.Data +{ + /// + /// ݴ + /// + /// + public class DataEventArgs: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; + /// + /// + /// + public T Data + { + get { return m_Data; } + set { m_Data = value; } + + } + + private string m_TypeName; + /// + /// ص + /// + public string TypeName + { + get { return m_TypeName; } + set { m_TypeName = value; } + } + private string m_StackTrace; + /// + /// Ϣ + /// + public string StackTrace + { + get { return m_StackTrace; } + set { m_StackTrace = value; } + } + private string m_ErrorMsg; + /// + /// Ϣ + /// + public string ErrorMsg + { + get { return m_ErrorMsg; } + set { m_ErrorMsg = value; } + } + private bool m_IsError = false; + /// + /// Ƿ + /// + public bool IsError + { + get { return m_IsError; } + set { m_IsError = value; } + } + + } + + + +} diff --git a/基础类库/HuizhongLibrary/DataGridRadioButton.cs b/基础类库/HuizhongLibrary/DataGridRadioButton.cs new file mode 100644 index 0000000..7d78134 --- /dev/null +++ b/基础类库/HuizhongLibrary/DataGridRadioButton.cs @@ -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>"),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", ""); +// 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 + + + } + } diff --git a/基础类库/HuizhongLibrary/DataRegex.cs b/基础类库/HuizhongLibrary/DataRegex.cs new file mode 100644 index 0000000..0cd7a1d --- /dev/null +++ b/基础类库/HuizhongLibrary/DataRegex.cs @@ -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; + } + + /// + /// 验证日期格式 + /// + /// + /// {0格式正确}{1空值}{2日期格式错误}{3日期超出范围1900-1-1至3000-1-1} + 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; + } + + /// + /// 验证是否是整数 + /// + /// + /// 验证是否可为负,true验证不能为负,flase可为负 + /// + 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; + } + + /// + /// 验证是否是整数 + /// + /// + /// + 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; + } + + /// + /// 验证是否是整数 + /// + public static bool IsNumberInteger(string value) + { + if (value == "") return true; + try + { + Convert.ToInt32(value); + } + catch + { + return false; + } + return true; + } + + /// + /// 验证是否是浮点数 + /// + 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; + } + + /// + /// 验证是否是浮点数 + /// + public static bool IsNumberDouble(string value) + { + if (value == "") return true; + try + { + Convert.ToDouble(value); + } + catch + { + return false; + } + return true; + } + + /// + /// 验证是否是浮点数,并且小数位不能超过N位 + /// + 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; + } + + /// + /// 验证Email地址 + /// + 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; + } + + /// + /// 验证身份证号码 + /// + 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; + } + + /// + /// 验证邮政编码 + /// + public static bool IsPostalcode(string value) + { + if (value == "") return true; + if (Regex.Matches(value, @"^\d{6}$").Count == 0) return false; + return true; + } + + /// + /// 验证电话号码 + /// + 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; + } + + /// + /// 验证IP地址 + /// + 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; + } + + /// + /// 验证Url地址 + /// + public static bool IsUrlAddress(string value) + { + if (value == "") return true; + if (Regex.Matches(value, @"^http://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?$").Count == 0) return false; + return true; + } + + /// + /// 验证时间 + /// + 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; + } + } +} \ No newline at end of file diff --git a/基础类库/HuizhongLibrary/DataTableReport.cs b/基础类库/HuizhongLibrary/DataTableReport.cs new file mode 100644 index 0000000..f836c08 --- /dev/null +++ b/基础类库/HuizhongLibrary/DataTableReport.cs @@ -0,0 +1,5246 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Drawing; +using System.Drawing.Printing; +using System.Data; +using System.Windows.Forms; +using System.Diagnostics; +using System.Collections; +using System.Text.RegularExpressions; +using System.IO; + +namespace HuizhongLibrary.ReportPrint +{ + + #region ӡ_ݷҳӡ + public class PrintReport + { + private MyReport m_Report; + public MyReport Report + { + get { return m_Report; } + set + { + m_Report = value; + SetPageRecordNumber(Convert.ToInt32(value.Width), Convert.ToInt32(value.Height)); + } + } + private PrintDocument m_Document; + public PrintDocument Document + { + get { return m_Document; } + set { m_Document = value; } + } + private Kind m_Kind; + public Kind Kind + { + get { return m_Kind; } + set { m_Kind = value; } + } + private Int16 m_Copies; + /// + /// + /// + public Int16 Copies + { + get { return m_Copies; } + set { m_Copies = value; } + } + + private bool m_IsFixHeaderFooter = false; + /// + /// Ƿ̶ҳüβ + /// + public virtual bool IsFixHeaderFooter + { + get { return m_IsFixHeaderFooter; } + set + { + m_IsFixHeaderFooter = value; + } + } + private bool m_Collate = true; + public virtual bool Collate + { + get { return m_Collate; } + set + { + m_Collate = value; + } + } + private float m_ColumnWidthRectify = 0; + /// + /// ΢п + /// + public virtual float ColumnWidthRectify + { + get { return m_ColumnWidthRectify; } + set + { + m_ColumnWidthRectify = value; + } + } + private int m_PageCount = 1; + /// + /// һӡҳ + /// + public int PageCount + { + get { return m_PageCount; } + set + { + m_PageCount = value; + if (m_PageCount == 0) m_PageCount = 1; + } + } + int CurrentPageNumber = 0; //ǰҳ + public int StartPageNumber = 0; //ҳ + public int StopPageNumber = 0; //ҳ + private bool m_IsFillBlank = false; + /// + /// Ƿ + /// + public virtual bool IsFillBlank + { + get { return m_IsFillBlank; } + set + { + m_IsFillBlank = value; + } + } + private int m_Index; + public int Index + { + get { return m_Index; } + set { m_Index = value; } + } + public event EventHandler EndPrint; + int startIndex = 0; //Դк + + + + public PrintReport(MyReport report) + { + Copies = 1; + m_Document = new PrintDocument(); + m_Document.PrintPage += new PrintPageEventHandler(pd_PrintPage); + m_Document.BeginPrint += new PrintEventHandler(m_Document_BeginPrint); + m_Document.QueryPageSettings += new QueryPageSettingsEventHandler(m_Document_QueryPageSettings); + m_Document.EndPrint += new PrintEventHandler(m_Document_EndPrint); + this.Report = report; + this.Kind = this.Report.PagerKind[0]; + } + public PrintReport() + { + Copies = 1; + m_Document = new PrintDocument(); + m_Document.PrintPage += new PrintPageEventHandler(pd_PrintPage); + m_Document.BeginPrint += new PrintEventHandler(m_Document_BeginPrint); + m_Document.QueryPageSettings += new QueryPageSettingsEventHandler(m_Document_QueryPageSettings); + m_Document.EndPrint += new PrintEventHandler(m_Document_EndPrint); + + } + + private void MathRowHeight(Table tb) + { + if (tb.Rows.Count == 0) return; + Font CurrentFont = this.Report.Font; + foreach (TableRow row in tb.Rows) + { + if (row.Height > MeasureString("Ը߶", CurrentFont).Height) continue; + int RowNumber = 1; + float WidthCount = 0; + foreach (TableColumn col in tb.Columns) + { + int index = tb.Columns.IndexOf(col); + if (row.Cells[index].Font != null) CurrentFont = row.Cells[index].Font; + string value1 = Regex.Replace(row.Cells[index].Text, "", "", RegexOptions.IgnoreCase); + value1 = Regex.Replace(value1, "", "", RegexOptions.IgnoreCase); + value1 = Regex.Replace(value1, "", "", RegexOptions.IgnoreCase); + value1 = Regex.Replace(value1, "", "", RegexOptions.IgnoreCase); + if (Regex.IsMatch(value1, "
", RegexOptions.IgnoreCase) == false) + { + WidthCount = MeasureString(value1, CurrentFont).Width; + int CurrentRowNumber = 1; + try + { + CurrentRowNumber = Convert.ToInt32(Math.Ceiling(WidthCount / (col.Width * row.Cells[index].ColumnSpan))); + } + catch { } + if (CurrentRowNumber == 0) CurrentRowNumber = 1; + if (CurrentRowNumber > RowNumber) RowNumber = CurrentRowNumber; + } + else + { + int MaxRowNumber = 0; + string[] ss = Regex.Split(value1, "
", RegexOptions.IgnoreCase); + foreach (string s in ss) + { + WidthCount = MeasureString(s, CurrentFont).Width; + int CurrentRowNumber = 1; + try + { + CurrentRowNumber = Convert.ToInt32(Math.Ceiling(WidthCount / col.Width * row.Cells[index].ColumnSpan)); + } + catch { } + if (CurrentRowNumber == 0) CurrentRowNumber = 1; + MaxRowNumber = MaxRowNumber + CurrentRowNumber; + } + if (MaxRowNumber > RowNumber) RowNumber = MaxRowNumber; + } + } + row.RowSpan = RowNumber; + row.Height = MeasureString("Ը߶", CurrentFont).Height; + } + } + private void MathRowHeight(PageRows Rows) + { + Font CurrentFont = this.Report.Font; + float WidthCount = 0; + foreach (PageRow row in Rows) + { + if (row.Font != null) CurrentFont = row.Font; + row.Height = 0; + float Height = Convert.ToSingle(MeasureString(row.Text, CurrentFont).Height); + float charHeight = Convert.ToSingle(MeasureString("Ը߶", CurrentFont).Height); + if (Height == 0) { row.Height = charHeight; continue; } + float cellWidth = Convert.ToSingle(this.Report.Width - Report.Left - Report.Right); + + string value1 = Regex.Replace(row.Text, "", "", RegexOptions.IgnoreCase); + value1 = Regex.Replace(value1, "", "", RegexOptions.IgnoreCase); + value1 = Regex.Replace(value1, "", "", RegexOptions.IgnoreCase); + value1 = Regex.Replace(value1, "", "", RegexOptions.IgnoreCase); + if (Regex.IsMatch(value1, "
", RegexOptions.IgnoreCase) == false) + { + WidthCount = MeasureString(value1, CurrentFont).Width; + int CurrentRowNumber = 1; + try + { + CurrentRowNumber = Convert.ToInt32(Math.Ceiling(WidthCount / cellWidth)); + } + catch { } + if (CurrentRowNumber == 0) CurrentRowNumber = 1; + row.Height = Height * CurrentRowNumber; + } + else + { + string[] ss = Regex.Split(value1, "
", RegexOptions.IgnoreCase); + foreach (string s in ss) + { + WidthCount = MeasureString(s, CurrentFont).Width; + int CurrentRowNumber = 1; + try + { + CurrentRowNumber = Convert.ToInt32(Math.Ceiling(WidthCount / cellWidth)); + } + catch { } + if (CurrentRowNumber == 0) CurrentRowNumber = 1; + row.Height = row.Height + Height * CurrentRowNumber; + } + } + } + } + + public SizeF MeasureString(string Text, Font font) + { + Bitmap bmp = new Bitmap(100, 100); + Graphics g = Graphics.FromImage(bmp); + g.PageUnit = font.Unit; + SizeF s = g.MeasureString(Text, font); + return s; + } + public SizeF MeasureString(string Text, Font font,GraphicsUnit unit) + { + Bitmap bmp = new Bitmap(100, 100); + Graphics g = Graphics.FromImage(bmp); + g.PageUnit = unit; + SizeF s = g.MeasureString(Text, font); + return s; + } + + + public void SetPageRecordNumber(int width, int height) + { + if (Report.AutoMathPageRecordNumber == false) + { + if (this.ColumnWidthRectify != 0) + { + foreach (TableColumn col in Report.Group.LeftItem.Columns) + { + col.Width = col.Width + this.ColumnWidthRectify; + } + foreach (TableColumn col in Report.Group.Header.Columns) + { + col.Width = col.Width + this.ColumnWidthRectify; + } + foreach (TableColumn col in Report.Group.Footer.Columns) + { + col.Width = col.Width + this.ColumnWidthRectify; + } + foreach (TableColumn col in Report.Group.DataItem.Columns) + { + col.Width = col.Width + this.ColumnWidthRectify; + } + foreach (TableColumn col in Report.Group.RightItem.Columns) + { + col.Width = col.Width + this.ColumnWidthRectify; + } + } + MathRowHeight(Report.Header.TableItem); + MathRowHeight(Report.Footer.TableItem); + MathRowHeight(Report.Group.Footer); + MathRowHeight(Report.Group.Header); + MathRowHeight(Report.Group.LeftItem); + MathRowHeight(Report.Group.RightItem); + MathRowHeight(Report.Group.DataItem); + MathRowHeight(Report.Header.Rows); + MathRowHeight(Report.Footer.Rows); + return; + } + //߶ + // float Original + Report.Group.Height = Convert.ToSingle(height) - Report.Header.Height - Report.Footer.Height - Report.Top - Report.Bottom; + Report.Group.Width = Convert.ToSingle(width - Report.Left - Report.Right);// + float DataWidth = 0; + foreach (TableColumn col in Report.Group.Header.Columns) + { + DataWidth = DataWidth + col.Width; + } + float w = (Report.Group.Width - DataWidth - this.Report.Group.LeftItem.Width - this.Report.Group.RightItem.Width) / Convert.ToSingle(Report.Group.Header.Columns.Count); + if (w > 0) + { + foreach (TableColumn col in Report.Group.Header.Columns) + { + col.Width = col.Width + w; + } + foreach (TableColumn col in Report.Group.DataItem.Columns) + { + col.Width = col.Width + w; + } + foreach (TableColumn col in Report.Group.Footer.Columns) + { + col.Width = col.Width + w; + } + } + if (this.ColumnWidthRectify != 0) + { + foreach (TableColumn col in Report.Group.LeftItem.Columns) + { + col.Width = col.Width + this.ColumnWidthRectify; + } + foreach (TableColumn col in Report.Group.DataItem.Columns) + { + col.Width = col.Width + this.ColumnWidthRectify; + } + foreach (TableColumn col in Report.Group.Header.Columns) + { + col.Width = col.Width + this.ColumnWidthRectify; + } + foreach (TableColumn col in Report.Group.Footer.Columns) + { + col.Width = col.Width + this.ColumnWidthRectify; + } + foreach (TableColumn col in Report.Group.RightItem.Columns) + { + col.Width = col.Width + this.ColumnWidthRectify; + } + } + MathRowHeight(Report.Header.TableItem); + MathRowHeight(Report.Footer.TableItem); + MathRowHeight(Report.Group.Footer); + MathRowHeight(Report.Group.Header); + MathRowHeight(Report.Group.LeftItem); + MathRowHeight(Report.Group.RightItem); + MathRowHeight(Report.Group.DataItem); + MathRowHeight(Report.Header.Rows); + MathRowHeight(Report.Footer.Rows); + + } + + + public int GetPagerCount() + { + return this.PageCount; + } + + + + private void m_Document_QueryPageSettings(object sender, QueryPageSettingsEventArgs e) + { + e.PageSettings.Margins = new Margins(0, 0, 0, 0); + //e.PageSettings.PrinterSettings.DefaultPageSettings.Margins = e.PageSettings.Margins; + e.PageSettings.PrinterSettings.Copies = this.Copies; + e.PageSettings.PrinterSettings.Collate = this.Collate; + if (this.Report.RotatePoint > 0) { e.PageSettings.Landscape = true; } + else { e.PageSettings.Landscape = this.Kind.Landscape; } + + //e.PageSettings.PrinterSettings.DefaultPageSettings.Landscape = e.PageSettings.Landscape; + + PaperSize CustomPaperSize = null; + PaperSize PaperSizeItem = null; + foreach (PaperSize item in e.PageSettings.PrinterSettings.PaperSizes) + { + if (item.PaperName == this.Kind.Name) + { + PaperSizeItem = item; + break; + } + if (item.Kind == PaperKind.Custom) CustomPaperSize = item; + } + if (PaperSizeItem != null) { e.PageSettings.PaperSize = PaperSizeItem; } + else { + if (CustomPaperSize != null) + { + e.PageSettings.PaperSize = new PaperSize(CustomPaperSize.PaperName, System.Drawing.Printing.PrinterUnitConvert.Convert(this.Kind.Width * 10, PrinterUnit.TenthsOfAMillimeter, PrinterUnit.Display), System.Drawing.Printing.PrinterUnitConvert.Convert(this.Kind.Height * 10, PrinterUnit.TenthsOfAMillimeter, PrinterUnit.Display)); + e.PageSettings.PaperSize.RawKind = CustomPaperSize.RawKind; + } + } + //e.PageSettings.PrinterSettings.DefaultPageSettings.PaperSize = e.PageSettings.PaperSize; + if (Report.PageLayout == PageLayoutType.GridLayout) e.PageSettings.PrinterSettings.PrintRange = PrintRange.SomePages; + e.PageSettings.PrinterSettings.FromPage = this.CurrentPageNumber; + e.PageSettings.PrinterSettings.ToPage = this.StopPageNumber; + + + } + + public void MathPageCount() + { + if (Report.Group.DataItem == null || Report.Group.DataItem.Rows.Count == 0) { this.PageCount = 1; return; } + if (this.Report.AutoMathPageRecordNumber == false) + { + this.PageCount = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(Report.Group.DataItem.Rows.Count) / Convert.ToDouble(Report.PageRecordNumber))); //һӡҳ + } + else + { + this.PageCount = 1; + float currentHeigt = 0; + Font CurrentFont = this.Report.Font; + //ҳü߶ + + float y = this.Report.Top; + foreach (TableRow row in this.Report.Group.Header.Rows) + { + y = y + row.Height * row.RowSpan + Report.TableRowHeightReviseNumber; + } + foreach (TableRow row in this.Report.Group.Footer.Rows) + { + y = y + row.Height * row.RowSpan + Report.TableRowHeightReviseNumber; + } + + //ҳ + foreach (TableRow row in this.Report.Group.DataItem.Rows) + { + //߶ + int RowIndex = this.Report.Group.DataItem.Rows.IndexOf(row); + float maxRowHeight = row.Height * row.RowSpan + Report.TableRowHeightReviseNumber; + currentHeigt = currentHeigt + maxRowHeight; + if (currentHeigt + y + this.Report.Header.Height + this.Report.Group.Footer.Height > this.Report.Group.Height + this.Report.Header.Height + this.Report.Top) { this.PageCount++; currentHeigt = maxRowHeight; }//ѻ߶+ǰ軭ĸ߶ȳԤƣôҳ+1 + + } + } + } + + private void m_Document_BeginPrint(object sender, PrintEventArgs e) + { + + if (this.Kind.Landscape == false) { SetPageRecordNumber(this.Kind.Width, this.Kind.Height); } + else { SetPageRecordNumber(this.Kind.Height, this.Kind.Width); } + m_Document.DocumentName = Convert.ToString(this.StopPageNumber - this.StartPageNumber); + if (this.Report.PageRecordNumber > 0 || this.StartPageNumber == 1) return; + this.CurrentPageNumber = this.StartPageNumber; + this.PageCount = 1; + float currentHeigt = 0; + Font CurrentFont = this.Report.Font; + //ҳü߶ + + float y = this.Report.Top; + foreach (TableRow row in this.Report.Group.Header.Rows) + { + y = y + row.Height * row.RowSpan + Report.TableRowHeightReviseNumber; + } + foreach (TableRow row in this.Report.Group.Footer.Rows) + { + y = y + row.Height * row.RowSpan + Report.TableRowHeightReviseNumber; + } + + //ҳ + foreach (TableRow row in this.Report.Group.DataItem.Rows) + { + //߶ + int RowIndex = this.Report.Group.DataItem.Rows.IndexOf(row); + float maxRowHeight = row.Height * row.RowSpan + Report.TableRowHeightReviseNumber; + currentHeigt = currentHeigt + maxRowHeight; + if (currentHeigt + y + this.Report.Header.Height + this.Report.Group.Footer.Height > this.Report.Group.Height + this.Report.Header.Height + this.Report.Top) + {//ѻ߶+ǰ軭ĸ߶ȳԤƣôҳ+1 + this.PageCount++; currentHeigt = maxRowHeight; + if (this.PageCount == this.CurrentPageNumber + 1) this.startIndex = RowIndex; + } + + } + } + + private void pd_PrintPage(object sender, PrintPageEventArgs e) + { + Graphics g = e.Graphics; + //RectangleF picRect = new RectangleF(10, 10, e.MarginBounds.Height, e.MarginBounds.Width); + //float y=picRect.Y + picRect.Height / 2; + //float x = picRect.X + picRect.Width / 2; + //g.TranslateTransform(y / 2, y - picRect.Height / 2); + ////תĽǶ + //g.RotateTransform(90.0F); + + if (this.Report.RotatePoint > 0) + { + //תĽǶ + if (this.Report.RotateX == 0) this.Report.RotateX = e.MarginBounds.Width / 4; + g.TranslateTransform(this.Report.RotateX, this.Report.RotateY); + g.RotateTransform(this.Report.RotatePoint); + } + + g.PageUnit = GraphicsUnit.Millimeter; + DrawStringObject(g); + DrawLines(g); + DrawRectangles(g); + DrawImages(g); + if (this.Report.PageRecordNumber != 0) startIndex = Report.PageRecordNumber * this.CurrentPageNumber; + DrawHeader(g, Report.Left, Report.Top); + float dpiy = DrawGroups(g, startIndex, Report.Left, Report.Header.Height + this.Report.Top); + DrawFooter(g, Report.Left, dpiy + 2); + //startIndex += Report.PageRecordNumber; + CurrentPageNumber++; + + if (CurrentPageNumber < this.StopPageNumber) + { + e.HasMorePages = true; + } + else + { + e.HasMorePages = false; + startIndex = 0; + CurrentPageNumber = 0; + } + } + + void DrawStringObject(Graphics g) + { + foreach (StringObject item in Report.PageStringObjects) + { + Font CurrentFont = this.Report.Font; + if (item.Font != null) CurrentFont = item.Font; + if (item.TextAlign == "Left") + { + g.DrawString(item.Text, CurrentFont, Brushes.Black, item.Left, item.Top); + } + if (item.TextAlign == "Center") + { + if (item.Height == 0) item.Height = MeasureString(item.Text, CurrentFont, GraphicsUnit.Millimeter).Height; + StringFormat sf = new StringFormat(); + sf.Alignment = StringAlignment.Center; + sf.LineAlignment = StringAlignment.Center; + RectangleF rf = new RectangleF(item.Left, item.Top, item.Width, item.Height); + g.DrawString(item.Text, CurrentFont, Brushes.Black,rf,sf); + } + if (item.TextAlign == "Right") + { + StringFormat sf = new StringFormat(); + sf.Alignment = StringAlignment.Near; + sf.LineAlignment = StringAlignment.Center; + RectangleF rf = new RectangleF(item.Left, item.Top, item.Width, item.Height); + g.DrawString(item.Text, CurrentFont, Brushes.Black, rf, sf); + } + } + } + + void DrawLines(Graphics g) + { + g.PageUnit = GraphicsUnit.Point; + foreach (Line lin in Report.PageLines) + { + g.DrawLine(new Pen(Brushes.Black, lin.BrushWidth), lin.Pt1, lin.Pt2); + } + g.PageUnit = GraphicsUnit.Millimeter; + } + void DrawImages(Graphics g) + { + //g.PageUnit = GraphicsUnit.Pixel; + foreach (ImageObject img in Report.PageImageObjects) + { + if (img.IsZoom == false) { g.DrawImage(img.MemoryImage, img.Left, img.Top); } + else { g.DrawImage(img.MemoryImage, img.Left, img.Top, img.Width, img.Height); } + } + //g.PageUnit = GraphicsUnit.Millimeter; + } + void DrawRectangles(Graphics g) + { + g.PageUnit = GraphicsUnit.Point; + foreach (Rectangle gx in Report.PageRectangles) + { + g.DrawRectangle(new Pen(Brushes.Black, gx.BrushWidth), gx.X, gx.Y, gx.Width, gx.Height); + } + g.PageUnit = GraphicsUnit.Millimeter; + } + float DrawHeader(Graphics g, float dpix, float dpiy) + { + float x = dpix; + float y = dpiy; + StringFormat SF = null; + Font CurrentFont = this.Report.Font; + + foreach (PageRow row in Report.Header.Rows) + { + if (row.Text == "") { y = y + row.Height; continue; } + CurrentFont = this.Report.Font; + if (row.Font != null) CurrentFont = row.Font; + + SF = new StringFormat(); + SF.LineAlignment = row.LineAlignment; + SF.Alignment = row.Alignment; + SF.FormatFlags = row.FormatFlags; + if (this.Kind.Landscape == false) + { + // g.DrawString(row.Text, CurrentFont, Brushes.Black, new RectangleF(x, y, Convert.ToSingle(this.Kind.Width-Report.Left-Report.Right), Convert.ToSingle(RowHeight)), SF); + float cellWidth = Convert.ToSingle(this.Kind.Width - Report.Left - Report.Right); + float cellHeight = row.Height; + this.DrawString(g, CurrentFont, x, y, cellWidth, cellHeight, SF, row.Text, cellWidth, row.Height); + } + else + { + // g.DrawString(row.Text, CurrentFont, Brushes.Black, new RectangleF(x, y, Convert.ToSingle(this.Kind.Height-Report.Left-Report.Right), Convert.ToSingle(RowHeight)), SF); + float cellWidth = Convert.ToSingle(this.Kind.Height - Report.Left - Report.Right); + float cellHeight = row.Height; + this.DrawString(g, CurrentFont, x, y, cellWidth, cellHeight, SF, row.Text, cellWidth, row.Height); + } + y = y + row.Height; + } + + if (Report.Header.TableItem.Rows.Count > 0) y = y + Report.TableRowHeightReviseNumber; + foreach (TableRow row in Report.Header.TableItem.Rows) + { + int rowIndex = Report.Header.TableItem.Rows.IndexOf(row); + for (int i = 0; i < row.Cells.Count; i++) + { + TableCell cell = row.Cells[i]; + if (row.Cells[i].Visible == true) + { + float cellWidth = 0, cellHeight = 0; + if (cell.RowSpan > 1) + { + for (int k = 0; k < cell.RowSpan; k++) + { + cellHeight = cellHeight + Report.Header.TableItem.Rows[rowIndex + k].Height * Report.Header.TableItem.Rows[rowIndex + k].RowSpan + Report.TableRowHeightReviseNumber; + } + } + else { cellHeight = row.Height * row.RowSpan + Report.TableRowHeightReviseNumber; } + if (cell.ColumnSpan > 1) + { + for (int k = 0; k < cell.ColumnSpan; k++) + { + cellWidth = cellWidth + Report.Header.TableItem.Columns[i + k].Width; + } + } + else { cellWidth = Report.Header.TableItem.Columns[i].Width; } + + if (Report.Header.TableItem.ShowLine == true) g.DrawRectangle(new Pen(Color.Black, cell.BorderWidth), x, y, cellWidth, cellHeight); + SF = new StringFormat(); + SF.LineAlignment = cell.LineAlignment; + SF.Alignment = cell.Alignment; + SF.FormatFlags = cell.FormatFlags; + CurrentFont = this.Report.Font; + if (cell.Font != null) CurrentFont = cell.Font; + // g.DrawString(cell.Text, CurrentFont, Brushes.Black, new RectangleF(x, y, cellWidth, cellHeight), SF); + this.DrawString(g, CurrentFont, x, y, cellWidth, cellHeight, SF, cell.Text, cellWidth, row.Height); + } + x = x + Convert.ToSingle(Report.Header.TableItem.Columns[i].Width); + } + y = y + row.Height * row.RowSpan + Report.TableRowHeightReviseNumber; + x = dpix; + } + return y; + } + void DrawFooter(Graphics g, float dpix, float dpiy) + { + float x = dpix; + float y = dpiy; + StringFormat SF = null; + Font CurrentFont = this.Report.Font; + + foreach (TableRow row in Report.Footer.TableItem.Rows) + { + int rowIndex = Report.Footer.TableItem.Rows.IndexOf(row); + for (int i = 0; i < row.Cells.Count; i++) + { + TableCell cell = row.Cells[i]; + if (row.Cells[i].Visible == true) + { + float cellWidth = 0, cellHeight = 0; + if (cell.RowSpan > 1) + { + for (int k = 0; k < cell.RowSpan; k++) + { + cellHeight = cellHeight + Report.Footer.TableItem.Rows[rowIndex + k].Height * Report.Footer.TableItem.Rows[rowIndex + k].RowSpan + Report.TableRowHeightReviseNumber; + } + } + else { cellHeight = row.Height * row.RowSpan + Report.TableRowHeightReviseNumber; } + if (cell.ColumnSpan > 1) + { + for (int k = 0; k < cell.ColumnSpan; k++) + { + cellWidth = cellWidth + Report.Footer.TableItem.Columns[i + k].Width; + } + } + else { cellWidth = Report.Footer.TableItem.Columns[i].Width; } + + if (Report.Footer.TableItem.ShowLine == true) g.DrawRectangle(new Pen(Color.Black, cell.BorderWidth), x, y, cellWidth, cellHeight); + SF = new StringFormat(); + SF.LineAlignment = cell.LineAlignment; + SF.Alignment = cell.Alignment; + SF.FormatFlags = cell.FormatFlags; + CurrentFont = this.Report.Font; + if (cell.Font != null) CurrentFont = cell.Font; + // g.DrawString(cell.Text, CurrentFont, Brushes.Black, new RectangleF(x, y, cellWidth, cellHeight), SF); + this.DrawString(g, CurrentFont, x, y, cellWidth, cellHeight, SF, cell.Text, cellWidth, row.Height); + } + x = x + Convert.ToSingle(Report.Footer.TableItem.Columns[i].Width); + } + y = y + row.Height * row.RowSpan + Report.TableRowHeightReviseNumber; + x = dpix; + } + + if (Report.Footer.TableItem.Rows.Count > 0) y = y + Report.TableRowHeightReviseNumber; + foreach (PageRow row in Report.Footer.Rows) + { + if (row.Text == "") { y = y + row.Height; continue; } + CurrentFont = this.Report.Font; + if (row.Font != null) CurrentFont = row.Font; + + SF = new StringFormat(); + SF.LineAlignment = row.LineAlignment; + SF.Alignment = row.Alignment; + SF.FormatFlags = row.FormatFlags; + + if (this.Kind.Landscape == false) + { + // g.DrawString(row.Text, CurrentFont, Brushes.Black, new RectangleF(x, y, Convert.ToSingle(this.Kind.Width-Report.Left-Report.Right), Convert.ToSingle(RowHeight)),SF); + float cellWidth = Convert.ToSingle(this.Kind.Width - Report.Left - Report.Right); + float cellHeight = row.Height; + this.DrawString(g, CurrentFont, x, y, cellWidth, cellHeight, SF, row.Text, cellWidth, row.Height); + + } + else + { + // g.DrawString(row.Text, CurrentFont, Brushes.Black, new RectangleF(x, y, Convert.ToSingle(this.Kind.Height-Report.Left-Report.Right), Convert.ToSingle(RowHeight)),SF); + float cellWidth = Convert.ToSingle(this.Kind.Height - Report.Left - Report.Right); + float cellHeight = row.Height; + this.DrawString(g, CurrentFont, x, y, cellWidth, cellHeight, SF, row.Text, cellWidth, row.Height); + + } + y = y + row.Height; + } + + if (this.Report.ShowPagerNumber == true) + { + SF = new StringFormat(); + SF.LineAlignment = StringAlignment.Center; + SF.Alignment = StringAlignment.Center; + string PagerNumberString = "" + Convert.ToString(this.CurrentPageNumber + 1) + "ҳ," + this.PageCount + "ҳ"; + float PagerNumberHeight = Report.MeasureString(PagerNumberString, this.Report.Font).Height; + if (this.Kind.Landscape == false) + { + g.DrawString(PagerNumberString, this.Report.Font, Brushes.Black, new RectangleF(x, y, Convert.ToSingle(this.Kind.Width - Report.Left - Report.Right), PagerNumberHeight), SF); + } + else + { + g.DrawString(PagerNumberString, this.Report.Font, Brushes.Black, new RectangleF(x, y, Convert.ToSingle(this.Kind.Height - Report.Left - Report.Right), PagerNumberHeight), SF); + } + } + } + + + float DrawGroups(Graphics g, int startIndex, float dpix, float dpiy) + { + float x = dpix; + float y = dpiy; + StringFormat SF = null; + Font CurrentFont = this.Report.Font; + + // + foreach (TableRow row in Report.Group.LeftItem.Rows) + { + int rowIndex = Report.Group.LeftItem.Rows.IndexOf(row); + for (int i = 0; i < row.Cells.Count; i++) + { + TableCell cell = row.Cells[i]; + if (row.Cells[i].Visible == true) + { + float cellWidth = 0, cellHeight = 0; + if (cell.RowSpan > 1) + { + for (int k = 0; k < cell.RowSpan; k++) + { + cellHeight = cellHeight + Report.Group.LeftItem.Rows[rowIndex + k].Height * Report.Group.LeftItem.Rows[rowIndex + k].RowSpan + Report.TableRowHeightReviseNumber; + } + } + else { cellHeight = row.Height * row.RowSpan + Report.TableRowHeightReviseNumber; } + if (cell.ColumnSpan > 1) + { + for (int k = 0; k < cell.ColumnSpan; k++) + { + cellWidth = cellWidth + Report.Group.LeftItem.Columns[i + k].Width; + } + } + else { cellWidth = Report.Group.LeftItem.Columns[i].Width; } + + if (Report.Group.LeftItem.ShowLine == true) g.DrawRectangle(new Pen(Color.Black, cell.BorderWidth), x, y, cellWidth, cellHeight); + SF = new StringFormat(); + SF.LineAlignment = cell.LineAlignment; + SF.Alignment = cell.Alignment; + SF.FormatFlags = cell.FormatFlags; + CurrentFont = this.Report.Font; + if (cell.Font != null) CurrentFont = cell.Font; + // g.DrawString(cell.Text, CurrentFont, Brushes.Black, new RectangleF(x, y, cellWidth, cellHeight), SF); + this.DrawString(g, CurrentFont, x, y, cellWidth, cellHeight, SF, cell.Text, cellWidth, row.Height); + } + x = x + Convert.ToSingle(Report.Group.LeftItem.Columns[i].Width); + } + y = y + row.Height * row.RowSpan + Report.TableRowHeightReviseNumber; + x = dpix; + } + + if (Report.Group.Header.Rows.Count > 0 || Report.Group.DataItem.Rows.Count > 0 || Report.Group.Footer.Rows.Count > 0) + { + x = dpix + Report.Group.LeftItem.Width; + y = dpiy; + } + + //бͷ + foreach (TableRow row in Report.Group.Header.Rows) + { + int rowIndex = Report.Group.Header.Rows.IndexOf(row); + for (int i = 0; i < row.Cells.Count; i++) + { + TableCell cell = row.Cells[i]; + if (row.Cells[i].Visible == true) + { + float cellWidth = 0, cellHeight = 0; + if (cell.RowSpan > 1) + { + for (int k = 0; k < cell.RowSpan; k++) + { + cellHeight = cellHeight + Report.Group.Header.Rows[rowIndex + k].Height * Report.Group.Header.Rows[rowIndex + k].RowSpan + this.Report.TableRowHeightReviseNumber; + } + } + else { cellHeight = row.Height * row.RowSpan + this.Report.TableRowHeightReviseNumber; } + if (cell.ColumnSpan > 1) + { + for (int k = 0; k < cell.ColumnSpan; k++) + { + cellWidth = cellWidth + Report.Group.Header.Columns[i + k].Width; + } + } + else { cellWidth = Report.Group.Header.Columns[i].Width; } + + if (Report.Group.Header.ShowLine == true) g.DrawRectangle(new Pen(Color.Black, cell.BorderWidth), x, y, cellWidth, cellHeight); + SF = new StringFormat(); + SF.LineAlignment = cell.LineAlignment; + SF.Alignment = cell.Alignment; + SF.FormatFlags = cell.FormatFlags; + CurrentFont = this.Report.Font; + if (cell.Font != null) CurrentFont = cell.Font; + // g.DrawString(cell.Text, CurrentFont, Brushes.Black, new RectangleF(x, y, cellWidth, cellHeight), SF); + this.DrawString(g, CurrentFont, x, y, cellWidth, cellHeight, SF, cell.Text, cellWidth, row.Height); + } + x = x + Convert.ToSingle(Report.Group.Header.Columns[i].Width); + } + y = y + row.Height * row.RowSpan + Report.TableRowHeightReviseNumber; + x = dpix + Report.Group.LeftItem.Width; + + } + + + //Ŀ + if (Report.Group.DataItem.Rows.Count > 0) + { + if (this.Report.AutoMathPageRecordNumber == true) + { + for (int j = startIndex; j < Report.Group.DataItem.Rows.Count; j++) + { + //߶ + float maxRowHeight = Report.Group.DataItem.Rows[j].Height * Report.Group.DataItem.Rows[j].RowSpan + this.Report.TableRowHeightReviseNumber; + for (int i = 0; i < Report.Group.DataItem.Columns.Count; i++) + { + // TableCell cell = Report.Group.DataItem.Rows[j].Cells[i]; + if (Report.Group.DataItem.Rows[j].Cells[i].Visible == false) continue; + float cellRowHeight = 0; + if (Report.Group.DataItem.Rows[j].Cells[i].RowSpan > 1) + { + for (int k = 0; k < Report.Group.DataItem.Rows[j].Cells[i].RowSpan; k++) + { + // cellRowHeight = cellRowHeight + (Report.Group.DataItem.Rows[j + k].Height+Report.TableRowHeightReviseNumber)*Report.Group.DataItem.Rows[j + k].RowSpan; + cellRowHeight = cellRowHeight + Report.Group.DataItem.Rows[j + k].Height * Report.Group.DataItem.Rows[j + k].RowSpan + this.Report.TableRowHeightReviseNumber; + } + } + if (cellRowHeight > maxRowHeight) maxRowHeight = cellRowHeight; + } + if (y + maxRowHeight + this.Report.Group.Footer.Height > this.Report.Group.Height + this.Report.Header.Height + this.Report.Top) { this.startIndex = j; break; }//ѻ߶+ǰ軭ĸ߶ȳԤƣô˳ѭ + + for (int i = 0; i < Report.Group.DataItem.Columns.Count; i++) + { + TableCell cell = Report.Group.DataItem.Rows[j].Cells[i]; + if (Report.Group.DataItem.Rows[j].Cells[i].Visible == true) + { + float cellWidth = 0, cellHeight = 0; + if (cell.RowSpan > 1) + { + for (int k = 0; k < cell.RowSpan; k++) + { + //cellHeight = cellHeight + (Report.Group.DataItem.Rows[j + k].Height+Report.TableRowHeightReviseNumber)*Report.Group.DataItem.Rows[j + k].RowSpan; + cellHeight = cellHeight + Report.Group.DataItem.Rows[j + k].Height * Report.Group.DataItem.Rows[j + k].RowSpan + this.Report.TableRowHeightReviseNumber; + } + } + else { cellHeight = Report.Group.DataItem.Rows[j].Height * Report.Group.DataItem.Rows[j].RowSpan + this.Report.TableRowHeightReviseNumber; } + if (cell.ColumnSpan > 1) + { + for (int k = 0; k < cell.ColumnSpan; k++) + { + cellWidth = Report.Group.DataItem.Columns[i + k].Width; + } + } + else { cellWidth = Report.Group.DataItem.Columns[i].Width; } + + if (Report.Group.DataItem.ShowLine == true) g.DrawRectangle(new Pen(Color.Black, cell.BorderWidth), x, y, cellWidth, cellHeight); + SF = new StringFormat(); + SF.LineAlignment = cell.LineAlignment; + SF.Alignment = cell.Alignment; + SF.FormatFlags = cell.FormatFlags; + CurrentFont = this.Report.Font; + if (cell.Font != null) CurrentFont = cell.Font; + // g.DrawString(cell.Text, CurrentFont, Brushes.Black, new RectangleF(x, y, cellWidth, cellHeight), SF); + this.DrawString(g, CurrentFont, x, y, cellWidth, cellHeight, SF, cell.Text, cellWidth, Report.Group.DataItem.Rows[j].Height); + } + x = x + Report.Group.DataItem.Columns[i].Width; + } + y = y + Report.Group.DataItem.Rows[j].Height * Report.Group.DataItem.Rows[j].RowSpan + this.Report.TableRowHeightReviseNumber; + x = dpix + Report.Group.LeftItem.Width; + + // + if (j == this.Report.Group.DataItem.Rows.Count - 1) + { + this.startIndex = j; + // + if (this.IsFillBlank == true) + { + while (true) + { + if (y + this.Report.Group.Footer.Height > this.Report.Group.Height + this.Report.Header.Height + this.Report.Top) break;//ѻ߶+ǰ軭ĸ߶ȳԤƣô˳ѭ + for (int i = 0; i < Report.Group.DataItem.Columns.Count; i++) + { + g.DrawRectangle(new Pen(Color.Black, Report.Group.DataItem.Rows[j].Cells[i].BorderWidth), x, y, Report.Group.DataItem.Columns[i].Width, Report.Group.DataItem.Rows[j].Height + Report.TableRowHeightReviseNumber); + x = x + Report.Group.DataItem.Columns[i].Width; + } + y = y + Report.Group.DataItem.Rows[j].Height + Report.TableRowHeightReviseNumber; + x = dpix + Report.Group.LeftItem.Width; + } + } + } + + } + } + else + { //趨ѭ + if (startIndex + Report.PageRecordNumber > this.Report.Group.DataItem.Rows.Count && this.IsFillBlank == true) + { + int modSl = Report.Group.DataItem.Rows.Count % Report.PageRecordNumber; //ȡ + TableRow row = null; + if (modSl != 0) + { + for (int ii = 0; ii < Report.PageRecordNumber - modSl; ii++) + { + row = Report.Group.DataItem.NewRow(); + row.Height = Report.Group.DataItem.Rows[Report.Group.DataItem.Rows.Count - 1].Height; + Report.Group.DataItem.Rows.Add(row); + } + } + } + for (int j = startIndex; j < startIndex + Report.PageRecordNumber; j++) + { + for (int i = 0; i < Report.Group.DataItem.Columns.Count; i++) + { + TableCell cell = Report.Group.DataItem.Rows[j].Cells[i]; + if (Report.Group.DataItem.Rows[j].Cells[i].Visible == true) + { + float cellWidth = 0, cellHeight = 0; + if (cell.RowSpan > 1) + { + for (int k = 0; k < cell.RowSpan; k++) + { + cellHeight = cellHeight + Report.Group.DataItem.Rows[j + k].Height * Report.Group.DataItem.Rows[j + k].RowSpan + Report.TableRowHeightReviseNumber; + } + } + else { cellHeight = Report.Group.DataItem.Rows[j].Height * Report.Group.DataItem.Rows[j].RowSpan + Report.TableRowHeightReviseNumber; } + if (cell.ColumnSpan > 1) + { + for (int k = 0; k < cell.ColumnSpan; k++) + { + cellWidth = Report.Group.DataItem.Columns[i + k].Width; + } + } + else { cellWidth = Report.Group.DataItem.Columns[i].Width; } + + if (Report.Group.DataItem.ShowLine == true) g.DrawRectangle(new Pen(Color.Black, cell.BorderWidth), x, y, cellWidth, cellHeight); + SF = new StringFormat(); + SF.LineAlignment = cell.LineAlignment; + SF.Alignment = cell.Alignment; + SF.FormatFlags = cell.FormatFlags; + CurrentFont = this.Report.Font; + if (cell.Font != null) CurrentFont = cell.Font; + // g.DrawString(cell.Text, CurrentFont, Brushes.Black, new RectangleF(x, y, cellWidth, cellHeight), SF); + this.DrawString(g, CurrentFont, x, y, cellWidth, cellHeight, SF, cell.Text, cellWidth, Report.Group.DataItem.Rows[j].Height); + } + x = x + Report.Group.DataItem.Columns[i].Width; + } + y = y + Report.Group.DataItem.Rows[j].Height * Report.Group.DataItem.Rows[j].RowSpan + Report.TableRowHeightReviseNumber; + x = dpix + Report.Group.LeftItem.Width; + } + } + + } + + //бβ + foreach (TableRow row in Report.Group.Footer.Rows) + { + int rowIndex = Report.Group.Footer.Rows.IndexOf(row); + for (int i = 0; i < row.Cells.Count; i++) + { + TableCell cell = row.Cells[i]; + if (row.Cells[i].Visible == true) + { + float cellWidth = 0, cellHeight = 0; + if (cell.RowSpan > 1) + { + for (int k = 0; k < cell.RowSpan; k++) + { + cellHeight = cellHeight + Report.Group.Footer.Rows[rowIndex + k].Height * Report.Group.Footer.Rows[rowIndex + k].RowSpan + Report.TableRowHeightReviseNumber; + } + } + else { cellHeight = Report.Group.Footer.Rows[rowIndex].Height * Report.Group.Footer.Rows[rowIndex].RowSpan + Report.TableRowHeightReviseNumber; } + if (cell.ColumnSpan > 1) + { + for (int k = 0; k < cell.ColumnSpan; k++) + { + cellWidth = cellWidth + Report.Group.Header.Columns[i + k].Width; + } + } + else { cellWidth = Report.Group.Header.Columns[i].Width; } + + if (Report.Group.Footer.ShowLine == true) g.DrawRectangle(new Pen(Color.Black, cell.BorderWidth), x, y, cellWidth, cellHeight); + SF = new StringFormat(); + SF.LineAlignment = cell.LineAlignment; + SF.Alignment = cell.Alignment; + SF.FormatFlags = cell.FormatFlags; + CurrentFont = this.Report.Font; + if (cell.Font != null) CurrentFont = cell.Font; + // g.DrawString(cell.Text, CurrentFont, Brushes.Black, new RectangleF(x, y, cellWidth, cellHeight),SF); + this.DrawString(g, CurrentFont, x, y, cellWidth, cellHeight, SF, cell.Text, cellWidth, row.Height); + } + x = x + Convert.ToSingle(Report.Group.Header.Columns[i].Width); + } + y = y + row.Height * row.RowSpan + Report.TableRowHeightReviseNumber; + x = dpix + Report.Group.LeftItem.Width; + } + + #region ұ + //ұ + if (Report.Group.RightItem.Rows.Count > 0) + { + x = dpix + Report.Group.LeftItem.Width + (Report.Group.Width - Report.Group.LeftItem.Width - Report.Group.RightItem.Width); + y = dpiy; + } + + foreach (TableRow row in Report.Group.RightItem.Rows) + { + int rowIndex = Report.Group.RightItem.Rows.IndexOf(row); + for (int i = 0; i < row.Cells.Count; i++) + { + TableCell cell = row.Cells[i]; + if (row.Cells[i].Visible == true) + { + float cellWidth = 0, cellHeight = 0; + if (cell.RowSpan > 1) + { + for (int k = 0; k < cell.RowSpan; k++) + { + cellHeight = cellHeight + Report.Group.RightItem.Rows[rowIndex + k].Height * Report.Group.RightItem.Rows[rowIndex + k].RowSpan + Report.TableRowHeightReviseNumber; + } + } + else { cellHeight = row.Height * row.RowSpan + Report.TableRowHeightReviseNumber; } + if (cell.ColumnSpan > 1) + { + for (int k = 0; k < cell.ColumnSpan; k++) + { + cellWidth = cellWidth + Report.Group.RightItem.Columns[i + k].Width; + } + } + else { cellWidth = Report.Group.RightItem.Columns[i].Width; } + + if (Report.Group.RightItem.ShowLine == true) g.DrawRectangle(new Pen(Color.Black, cell.BorderWidth), x, y, cellWidth, cellHeight); + SF = new StringFormat(); + SF.LineAlignment = cell.LineAlignment; + SF.Alignment = cell.Alignment; + SF.FormatFlags = cell.FormatFlags; + CurrentFont = this.Report.Font; + if (cell.Font != null) CurrentFont = cell.Font; + g.DrawString(cell.Text, CurrentFont, Brushes.Black, new RectangleF(x, y, cellWidth, cellHeight), SF); + } + x = x + Convert.ToSingle(Report.Group.RightItem.Columns[i].Width); + } + y = y + row.Height * row.RowSpan + Report.TableRowHeightReviseNumber; + x = dpix + Report.Group.LeftItem.Width + (Report.Group.Width - Report.Group.LeftItem.Width - Report.Group.RightItem.Width); + } + #endregion + + return y; + + } + private void DrawString(Graphics g, Font CurrentFont, float dpix, float dpiy, float width, float height, StringFormat sf, string value, float maxwidth, float RowHeight) + { + if (Regex.IsMatch(value, "||
", RegexOptions.IgnoreCase) == false) + { + g.DrawString(value, CurrentFont, Brushes.Black, new RectangleF(dpix, dpiy, width, height), sf); + } + else + { + float CurrentWidth = 0, x = dpix, y = dpiy + 0.5f; + value = Regex.Replace(value, "", "", RegexOptions.IgnoreCase); + value = Regex.Replace(value, "", "", RegexOptions.IgnoreCase); + value = Regex.Replace(value, "", "", RegexOptions.IgnoreCase); + value = Regex.Replace(value, "
", "", RegexOptions.IgnoreCase); + value = Regex.Replace(value, "
", "", RegexOptions.IgnoreCase); + string[] ss = value.Split(Convert.ToChar("")); + foreach (string s in ss) + { + if (s.Length == 0) continue; + string flag = s.Substring(0, 1); + switch (flag) + { + case "": + foreach (char c in s) + { + if (c.ToString() == "") continue; + Font f = new Font("", CurrentFont.Size * 0.5f, GraphicsUnit.Millimeter); + g.DrawString(c.ToString(), f, Brushes.Black, x, y); + float charWidth = this.MeasureString(c.ToString(), f).Width; + //float charWidth2 = this.MeasureString(c.ToString() + c.ToString(), CurrentFont).Width; + //charWidth = charWidth - (charWidth * 2 - charWidth2); + x = x + charWidth; + CurrentWidth = CurrentWidth + charWidth; + if (CurrentWidth >= maxwidth - charWidth) { CurrentWidth = 0; x = dpix; y = y + RowHeight; } + } + continue; + case "": + foreach (char c in s) + { + if (c.ToString() == "") continue; + Font f = new Font("", CurrentFont.Size * 0.5f, GraphicsUnit.Millimeter); + g.DrawString(c.ToString(), f, Brushes.Black, x, y + RowHeight * 0.5f); + float charWidth = this.MeasureString(c.ToString(), f).Width; + //float charWidth2 = this.MeasureString(c.ToString() + c.ToString(), CurrentFont).Width; + //charWidth = charWidth - (charWidth * 2 - charWidth2); + x = x + charWidth; + CurrentWidth = CurrentWidth + charWidth; + if (CurrentWidth >= maxwidth - charWidth) { CurrentWidth = 0; x = dpix; y = y + RowHeight; } + } + continue; + default: + float charHeight = this.MeasureString("Ը߶", CurrentFont).Height; + foreach (char c in s) + { + if (c.ToString() == "") + { + CurrentWidth = 0; + x = dpix; + y = y + charHeight; + continue; + } + g.DrawString(c.ToString(), CurrentFont, Brushes.Black, x, y); + float charWidth = this.MeasureString(c.ToString(), CurrentFont).Width; + float charWidth2 = this.MeasureString(c.ToString() + c.ToString(), CurrentFont).Width; + if (c.ToString().Trim() != "") charWidth = charWidth - (charWidth * 2 - charWidth2); + x = x + charWidth; + CurrentWidth = CurrentWidth + charWidth; + if (CurrentWidth >= maxwidth) { CurrentWidth = 0; x = dpix; y = y + charHeight; } + } + break; + } + } + } + } + + public void Print() + { + if (m_Document.PrinterSettings.IsValid == false) { MessageBox.Show("ӡûаװ,׼ôӡ"); return; } + m_Document.Print(); + + } + + + + + private void m_Document_EndPrint(object sender, PrintEventArgs e) + { + if (this.EndPrint != null) this.EndPrint(this, null); + } + + } + #endregion + #region ӡ_ҳӡ + public class PrintMuchReport + { + public List Report { get; set; } + public PrintDocument Document { get; set; } + public Kind Kind { get; set; } + public Int16 Copies { get; set; } + //ݴӡ + public bool Collate { get; set; } + int CurrentPageNumber = 0; //ǰҳ + int StopPageNumber = 0; //ҳ + public int GetPagerCount() + { + return StopPageNumber; + } + + + + public event EventHandler EndPrint; + + + + + public PrintMuchReport(List report) + { + Copies = 1; + Document = new PrintDocument(); + Document.DocumentName = report.Count.ToString(); + Document.PrintPage += new PrintPageEventHandler(pd_PrintPage); + Document.BeginPrint += new PrintEventHandler(m_Document_BeginPrint); + Document.QueryPageSettings += new QueryPageSettingsEventHandler(m_Document_QueryPageSettings); + Document.EndPrint += new PrintEventHandler(m_Document_EndPrint); + this.Report = report; + this.Kind = this.Report[0].PagerKind[0]; + this.StopPageNumber = report.Count; + //SetPageRecordNumber(Convert.ToInt32(value.Width), Convert.ToInt32(value.Height)); + } + + private void MathRowHeight(Table tb) + { + if (tb.Rows.Count == 0) return; + Font CurrentFont = this.Report[0].Font; + foreach (TableRow row in tb.Rows) + { + if (row.Height > MeasureString("Ը߶", CurrentFont).Height) continue; + int RowNumber = 1; + float WidthCount = 0; + foreach (TableColumn col in tb.Columns) + { + int index = tb.Columns.IndexOf(col); + if (row.Cells[index].Font != null) CurrentFont = row.Cells[index].Font; + string value1 = Regex.Replace(row.Cells[index].Text, "", "", RegexOptions.IgnoreCase); + value1 = Regex.Replace(value1, "", "", RegexOptions.IgnoreCase); + value1 = Regex.Replace(value1, "", "", RegexOptions.IgnoreCase); + value1 = Regex.Replace(value1, "", "", RegexOptions.IgnoreCase); + if (Regex.IsMatch(value1, "
", RegexOptions.IgnoreCase) == false) + { + WidthCount = MeasureString(value1, CurrentFont).Width; + int CurrentRowNumber = 1; + try + { + CurrentRowNumber = Convert.ToInt32(Math.Ceiling(WidthCount / (col.Width * row.Cells[index].ColumnSpan))); + } + catch { } + if (CurrentRowNumber == 0) CurrentRowNumber = 1; + if (CurrentRowNumber > RowNumber) RowNumber = CurrentRowNumber; + } + else + { + int MaxRowNumber = 0; + string[] ss = Regex.Split(value1, "
", RegexOptions.IgnoreCase); + foreach (string s in ss) + { + WidthCount = MeasureString(s, CurrentFont).Width; + int CurrentRowNumber = 1; + try + { + CurrentRowNumber = Convert.ToInt32(Math.Ceiling(WidthCount / col.Width * row.Cells[index].ColumnSpan)); + } + catch { } + if (CurrentRowNumber == 0) CurrentRowNumber = 1; + MaxRowNumber = MaxRowNumber + CurrentRowNumber; + } + if (MaxRowNumber > RowNumber) RowNumber = MaxRowNumber; + } + } + row.RowSpan = RowNumber; + row.Height = MeasureString("Ը߶", CurrentFont).Height; + } + } + private void MathRowHeight(PageRows Rows) + { + Font CurrentFont = this.Report[0].Font; + float WidthCount = 0; + foreach (PageRow row in Rows) + { + if (row.Font != null) CurrentFont = row.Font; + row.Height = 0; + float Height = Convert.ToSingle(MeasureString(row.Text, CurrentFont).Height); + float charHeight = Convert.ToSingle(MeasureString("Ը߶", CurrentFont).Height); + if (Height == 0) { row.Height = charHeight; continue; } + float cellWidth = Convert.ToSingle(this.Report[0].Width - Report[0].Left - Report[0].Right); + + string value1 = Regex.Replace(row.Text, "", "", RegexOptions.IgnoreCase); + value1 = Regex.Replace(value1, "", "", RegexOptions.IgnoreCase); + value1 = Regex.Replace(value1, "", "", RegexOptions.IgnoreCase); + value1 = Regex.Replace(value1, "", "", RegexOptions.IgnoreCase); + if (Regex.IsMatch(value1, "
", RegexOptions.IgnoreCase) == false) + { + WidthCount = MeasureString(value1, CurrentFont).Width; + int CurrentRowNumber = 1; + try + { + CurrentRowNumber = Convert.ToInt32(Math.Ceiling(WidthCount / cellWidth)); + } + catch { } + if (CurrentRowNumber == 0) CurrentRowNumber = 1; + row.Height = Height * CurrentRowNumber; + } + else + { + string[] ss = Regex.Split(value1, "
", RegexOptions.IgnoreCase); + foreach (string s in ss) + { + WidthCount = MeasureString(s, CurrentFont).Width; + int CurrentRowNumber = 1; + try + { + CurrentRowNumber = Convert.ToInt32(Math.Ceiling(WidthCount / cellWidth)); + } + catch { } + if (CurrentRowNumber == 0) CurrentRowNumber = 1; + row.Height = row.Height + Height * CurrentRowNumber; + } + } + } + } + + public SizeF MeasureString(string Text, Font font) + { + Bitmap bmp = new Bitmap(100, 100); + Graphics g = Graphics.FromImage(bmp); + g.PageUnit = font.Unit; + SizeF s = g.MeasureString(Text, font); + return s; + } + public SizeF MeasureString(string Text, Font font, GraphicsUnit unit) + { + Bitmap bmp = new Bitmap(100, 100); + Graphics g = Graphics.FromImage(bmp); + g.PageUnit = unit; + SizeF s = g.MeasureString(Text, font); + return s; + } + + + + private void m_Document_QueryPageSettings(object sender, QueryPageSettingsEventArgs e) + { + e.PageSettings.Margins = new Margins(0, 0, 0, 0); + //e.PageSettings.PrinterSettings.DefaultPageSettings.Margins = e.PageSettings.Margins; + e.PageSettings.PrinterSettings.Copies = this.Copies; + e.PageSettings.PrinterSettings.Collate = this.Collate; + if (this.Report[0].RotatePoint > 0) { e.PageSettings.Landscape = true; } + else { e.PageSettings.Landscape = this.Kind.Landscape; } + + //e.PageSettings.PrinterSettings.DefaultPageSettings.Landscape = e.PageSettings.Landscape; + + PaperSize CustomPaperSize = null; + PaperSize PaperSizeItem = null; + foreach (PaperSize item in e.PageSettings.PrinterSettings.PaperSizes) + { + if (item.PaperName == this.Kind.Name && item.Kind != PaperKind.Custom) + { + PaperSizeItem = item; + break; + } + if (item.Kind == PaperKind.Custom) CustomPaperSize = item; + } + if (PaperSizeItem != null) { e.PageSettings.PaperSize = PaperSizeItem; } + else + { + if (CustomPaperSize != null) + { + e.PageSettings.PaperSize = new PaperSize(CustomPaperSize.PaperName, System.Drawing.Printing.PrinterUnitConvert.Convert(this.Kind.Width * 10, PrinterUnit.TenthsOfAMillimeter, PrinterUnit.Display), System.Drawing.Printing.PrinterUnitConvert.Convert(this.Kind.Height * 10, PrinterUnit.TenthsOfAMillimeter, PrinterUnit.Display)); + e.PageSettings.PaperSize.RawKind = CustomPaperSize.RawKind; + } + } + //e.PageSettings.PrinterSettings.DefaultPageSettings.PaperSize = e.PageSettings.PaperSize; + if (Report[0].PageLayout == PageLayoutType.GridLayout) e.PageSettings.PrinterSettings.PrintRange = PrintRange.SomePages; + e.PageSettings.PrinterSettings.FromPage = this.CurrentPageNumber; + e.PageSettings.PrinterSettings.ToPage = this.StopPageNumber; + } + + private void m_Document_BeginPrint(object sender, PrintEventArgs e) + { + this.CurrentPageNumber = 0; + } + + private void pd_PrintPage(object sender, PrintPageEventArgs e) + { + Graphics g = e.Graphics; + //RectangleF picRect = new RectangleF(10, 10, e.MarginBounds.Height, e.MarginBounds.Width); + //float y=picRect.Y + picRect.Height / 2; + //float x = picRect.X + picRect.Width / 2; + //g.TranslateTransform(y / 2, y - picRect.Height / 2); + ////תĽǶ + //g.RotateTransform(90.0F); + MyReport report = this.Report[this.CurrentPageNumber]; + + if (report.RotatePoint > 0) + { + //תĽǶ + if (report.RotateX == 0) report.RotateX = e.MarginBounds.Width / 4; + g.TranslateTransform(report.RotateX, report.RotateY); + g.RotateTransform(report.RotatePoint); + } + + g.PageUnit = GraphicsUnit.Millimeter; + DrawStringObject(report,g); + DrawLines(report,g); + DrawRectangles(report,g); + DrawImages(report,g); + DrawHeader(report,g, report.Left, report.Top); + CurrentPageNumber++; + + if (CurrentPageNumber < this.StopPageNumber) + { + e.HasMorePages = true; + } + else + { + e.HasMorePages = false; + } + } + + void DrawStringObject(MyReport report, Graphics g) + { + foreach (StringObject item in report.PageStringObjects) + { + Font CurrentFont = report.Font; + if (item.Font != null) CurrentFont = item.Font; + if (item.TextAlign == "Left") + { + g.DrawString(item.Text, CurrentFont, Brushes.Black, item.Left, item.Top); + } + if (item.TextAlign == "Center") + { + if (item.Height == 0) item.Height = MeasureString(item.Text, CurrentFont, GraphicsUnit.Millimeter).Height; + StringFormat sf = new StringFormat(); + sf.Alignment = StringAlignment.Center; + sf.LineAlignment = StringAlignment.Center; + RectangleF rf = new RectangleF(item.Left, item.Top, item.Width, item.Height); + g.DrawString(item.Text, CurrentFont, Brushes.Black, rf, sf); + } + if (item.TextAlign == "Right") + { + StringFormat sf = new StringFormat(); + sf.Alignment = StringAlignment.Near; + sf.LineAlignment = StringAlignment.Center; + RectangleF rf = new RectangleF(item.Left, item.Top, item.Width, item.Height); + g.DrawString(item.Text, CurrentFont, Brushes.Black, rf, sf); + } + } + } + + void DrawLines(MyReport report, Graphics g) + { + g.PageUnit = GraphicsUnit.Point; + foreach (Line lin in report.PageLines) + { + g.DrawLine(new Pen(Brushes.Black, lin.BrushWidth), lin.Pt1, lin.Pt2); + } + g.PageUnit = GraphicsUnit.Millimeter; + } + void DrawImages(MyReport report, Graphics g) + { + //g.PageUnit = GraphicsUnit.Pixel; + foreach (ImageObject img in report.PageImageObjects) + { + if (img.IsZoom == false) { g.DrawImage(img.MemoryImage, img.Left, img.Top); } + else { g.DrawImage(img.MemoryImage, img.Left, img.Top, img.Width, img.Height); } + } + //g.PageUnit = GraphicsUnit.Millimeter; + } + void DrawRectangles(MyReport report, Graphics g) + { + g.PageUnit = GraphicsUnit.Point; + foreach (Rectangle gx in report.PageRectangles) + { + g.DrawRectangle(new Pen(Brushes.Black, gx.BrushWidth), gx.X, gx.Y, gx.Width, gx.Height); + } + g.PageUnit = GraphicsUnit.Millimeter; + } + float DrawHeader(MyReport report, Graphics g, float dpix, float dpiy) + { + float x = dpix; + float y = dpiy; + StringFormat SF = null; + Font CurrentFont = report.Font; + + foreach (PageRow row in report.Header.Rows) + { + if (row.Text == "") { y = y + row.Height; continue; } + CurrentFont = report.Font; + if (row.Font != null) CurrentFont = row.Font; + + SF = new StringFormat(); + SF.LineAlignment = row.LineAlignment; + SF.Alignment = row.Alignment; + SF.FormatFlags = row.FormatFlags; + if (this.Kind.Landscape == false) + { + // g.DrawString(row.Text, CurrentFont, Brushes.Black, new RectangleF(x, y, Convert.ToSingle(this.Kind.Width-Report.Left-Report.Right), Convert.ToSingle(RowHeight)), SF); + float cellWidth = Convert.ToSingle(this.Kind.Width - report.Left - report.Right); + float cellHeight = row.Height; + this.DrawString(g, CurrentFont, x, y, cellWidth, cellHeight, SF, row.Text, cellWidth, row.Height); + } + else + { + // g.DrawString(row.Text, CurrentFont, Brushes.Black, new RectangleF(x, y, Convert.ToSingle(this.Kind.Height-Report.Left-Report.Right), Convert.ToSingle(RowHeight)), SF); + float cellWidth = Convert.ToSingle(this.Kind.Height - report.Left - report.Right); + float cellHeight = row.Height; + this.DrawString(g, CurrentFont, x, y, cellWidth, cellHeight, SF, row.Text, cellWidth, row.Height); + } + y = y + row.Height; + } + + if (report.Header.TableItem.Rows.Count > 0) y = y + report.TableRowHeightReviseNumber; + foreach (TableRow row in report.Header.TableItem.Rows) + { + int rowIndex = report.Header.TableItem.Rows.IndexOf(row); + for (int i = 0; i < row.Cells.Count; i++) + { + TableCell cell = row.Cells[i]; + if (row.Cells[i].Visible == true) + { + float cellWidth = 0, cellHeight = 0; + if (cell.RowSpan > 1) + { + for (int k = 0; k < cell.RowSpan; k++) + { + cellHeight = cellHeight + report.Header.TableItem.Rows[rowIndex + k].Height * report.Header.TableItem.Rows[rowIndex + k].RowSpan + report.TableRowHeightReviseNumber; + } + } + else { cellHeight = row.Height * row.RowSpan + report.TableRowHeightReviseNumber; } + if (cell.ColumnSpan > 1) + { + for (int k = 0; k < cell.ColumnSpan; k++) + { + cellWidth = cellWidth + report.Header.TableItem.Columns[i + k].Width; + } + } + else { cellWidth = report.Header.TableItem.Columns[i].Width; } + + if (report.Header.TableItem.ShowLine == true) g.DrawRectangle(new Pen(Color.Black, cell.BorderWidth), x, y, cellWidth, cellHeight); + SF = new StringFormat(); + SF.LineAlignment = cell.LineAlignment; + SF.Alignment = cell.Alignment; + SF.FormatFlags = cell.FormatFlags; + CurrentFont = report.Font; + if (cell.Font != null) CurrentFont = cell.Font; + // g.DrawString(cell.Text, CurrentFont, Brushes.Black, new RectangleF(x, y, cellWidth, cellHeight), SF); + this.DrawString(g, CurrentFont, x, y, cellWidth, cellHeight, SF, cell.Text, cellWidth, row.Height); + } + x = x + Convert.ToSingle(report.Header.TableItem.Columns[i].Width); + } + y = y + row.Height * row.RowSpan + report.TableRowHeightReviseNumber; + x = dpix; + } + return y; + } + + private void DrawString(Graphics g, Font CurrentFont, float dpix, float dpiy, float width, float height, StringFormat sf, string value, float maxwidth, float RowHeight) + { + if (value==null) value=""; + if (Regex.IsMatch(value, "||
", RegexOptions.IgnoreCase) == false) + { + g.DrawString(value, CurrentFont, Brushes.Black, new RectangleF(dpix, dpiy, width, height), sf); + } + else + { + float CurrentWidth = 0, x = dpix, y = dpiy + 0.5f; + value = Regex.Replace(value, "", "", RegexOptions.IgnoreCase); + value = Regex.Replace(value, "", "", RegexOptions.IgnoreCase); + value = Regex.Replace(value, "", "", RegexOptions.IgnoreCase); + value = Regex.Replace(value, "
", "", RegexOptions.IgnoreCase); + value = Regex.Replace(value, "
", "", RegexOptions.IgnoreCase); + string[] ss = value.Split(Convert.ToChar("")); + foreach (string s in ss) + { + if (s.Length == 0) continue; + string flag = s.Substring(0, 1); + switch (flag) + { + case "": + foreach (char c in s) + { + if (c.ToString() == "") continue; + Font f = new Font("", CurrentFont.Size * 0.5f, GraphicsUnit.Millimeter); + g.DrawString(c.ToString(), f, Brushes.Black, x, y); + float charWidth = this.MeasureString(c.ToString(), f).Width; + //float charWidth2 = this.MeasureString(c.ToString() + c.ToString(), CurrentFont).Width; + //charWidth = charWidth - (charWidth * 2 - charWidth2); + x = x + charWidth; + CurrentWidth = CurrentWidth + charWidth; + if (CurrentWidth >= maxwidth - charWidth) { CurrentWidth = 0; x = dpix; y = y + RowHeight; } + } + continue; + case "": + foreach (char c in s) + { + if (c.ToString() == "") continue; + Font f = new Font("", CurrentFont.Size * 0.5f, GraphicsUnit.Millimeter); + g.DrawString(c.ToString(), f, Brushes.Black, x, y + RowHeight * 0.5f); + float charWidth = this.MeasureString(c.ToString(), f).Width; + //float charWidth2 = this.MeasureString(c.ToString() + c.ToString(), CurrentFont).Width; + //charWidth = charWidth - (charWidth * 2 - charWidth2); + x = x + charWidth; + CurrentWidth = CurrentWidth + charWidth; + if (CurrentWidth >= maxwidth - charWidth) { CurrentWidth = 0; x = dpix; y = y + RowHeight; } + } + continue; + default: + float charHeight = this.MeasureString("Ը߶", CurrentFont).Height; + foreach (char c in s) + { + if (c.ToString() == "") + { + CurrentWidth = 0; + x = dpix; + y = y + charHeight; + continue; + } + g.DrawString(c.ToString(), CurrentFont, Brushes.Black, x, y); + float charWidth = this.MeasureString(c.ToString(), CurrentFont).Width; + float charWidth2 = this.MeasureString(c.ToString() + c.ToString(), CurrentFont).Width; + if (c.ToString().Trim() != "") charWidth = charWidth - (charWidth * 2 - charWidth2); + x = x + charWidth; + CurrentWidth = CurrentWidth + charWidth; + if (CurrentWidth >= maxwidth) { CurrentWidth = 0; x = dpix; y = y + charHeight; } + } + break; + } + } + } + } + + public void Print() + { + if (Document.PrinterSettings.IsValid == false) { MessageBox.Show("ӡûаװ,׼ôӡ"); return; } + Document.Print(); + } + + private void m_Document_EndPrint(object sender, PrintEventArgs e) + { + if (this.EndPrint != null) this.EndPrint(this, null); + } + + } + #endregion + #region + [Serializable] + public class MyReport + { + public PageHeader Header; + public PageFooter Footer; + public PageGroup Group; + public Lines PageLines; + public ImageObjects PageImageObjects; + public StringObjects PageStringObjects; + public float Width; //ҳ(λ) + public float Height; //ҳ(λ) + public float Top = 0; + public float Left = 10F; + public float Right = 10F; + public float Bottom = 0; + public float RotatePoint = 0; //ת + public float RotateX = 0; //תXת + public float RotateY = 0; //תYת + public Rectangles PageRectangles; + /// + /// ÿҳҳ + /// + public int PageRecordNumber = 0; + /// + /// Ƿʾҳ + /// + public bool ShowPagerNumber = true; + /// + /// ֽ֧ + /// + public Kinds PagerKind = null; + /// + /// ǷԶÿҳ + /// + public bool AutoMathPageRecordNumber = false; + /// + /// иֵ(ϱ±ߵĿ϶) + /// + public float TableRowHeightReviseNumber = 1.4F; + private bool m_IsFillBlank = false; + /// + /// Ƿ + /// + public virtual bool IsFillBlank + { + get { return m_IsFillBlank; } + set + { + m_IsFillBlank = value; + + } + } + + private PageLayoutType m_PageLayout = PageLayoutType.GridLayout; + /// + /// ֻģʽ + /// + public virtual PageLayoutType PageLayout + { + get { return m_PageLayout; } + set + { + m_PageLayout = value; + } + } + private Font m_Font; + public Font Font + { + get + { + return this.m_Font; + } + set + { + m_Font = value; + this.Group.Font = value; + this.Header.TableItem.Font = value; + this.Footer.TableItem.Font = value; + this.Group.LeftItem.Font = value; + this.Group.RightItem.Font = value; + this.Group.DataItem.Font = value; + this.Group.Header.Font = value; + this.Group.Footer.Font = value; + } + } + + + public MyReport() + { + Header = new PageHeader(); + Footer = new PageFooter(); + Group = new PageGroup(); + PageLines = new Lines(); + PageRectangles = new Rectangles(); + PageImageObjects = new ImageObjects(); + PageStringObjects = new StringObjects(); + PagerKind = new Kinds(); + this.Font = new System.Drawing.Font("", 3, System.Drawing.FontStyle.Regular, GraphicsUnit.Millimeter); + } + public MyReport(Kind kind) + { + Header = new PageHeader(); + Footer = new PageFooter(); + Group = new PageGroup(); + PageLines = new Lines(); + PageRectangles = new Rectangles(); + PageImageObjects = new ImageObjects(); + PageStringObjects = new StringObjects(); + PagerKind = new Kinds(); + this.Font = new System.Drawing.Font("", 3, System.Drawing.FontStyle.Regular, GraphicsUnit.Millimeter); + if (kind.Landscape == false) + { + this.Height = kind.Height; + this.Width = kind.Width; + } + else + { + this.Height = kind.Width; + this.Width = kind.Height; + } + PagerKind.Add(kind); + this.Group.Width = this.Width - this.Left - this.Right; + } + public MyReport(string name, float width, float height, bool landscape) + { + Header = new PageHeader(); + Footer = new PageFooter(); + Group = new PageGroup(); + PageLines = new Lines(); + PageRectangles = new Rectangles(); + PageImageObjects = new ImageObjects(); + PageStringObjects = new StringObjects(); + PagerKind = new Kinds(); + this.Font = new System.Drawing.Font("", 3, System.Drawing.FontStyle.Regular, GraphicsUnit.Millimeter); + PagerKind.Add(new Kind(name, Convert.ToInt32(width), Convert.ToInt32(height), landscape)); + if (landscape == false) + { + this.Width = width; + this.Height = height; + } + else + { + this.Width = height; + this.Height = width; + } + this.Group.Width = this.Width - this.Left - this.Right; + } + public MyReport(float width, float height, bool landscape) + { + Header = new PageHeader(); + Footer = new PageFooter(); + Group = new PageGroup(); + PageLines = new Lines(); + PageRectangles = new Rectangles(); + PageImageObjects = new ImageObjects(); + PageStringObjects = new StringObjects(); + PagerKind = new Kinds(); + this.Font = new System.Drawing.Font("", 3, System.Drawing.FontStyle.Regular, GraphicsUnit.Millimeter); + PagerKind.Add(new Kind("ԶС", Convert.ToInt32(width), Convert.ToInt32(height), landscape)); + if (landscape == false) + { + this.Width = width; + this.Height = height; + } + else + { + this.Width = height; + this.Height = width; + } + this.Group.Width = this.Width - this.Left - this.Right; + } + public MyReport(float width, float height) + { + Header = new PageHeader(); + Footer = new PageFooter(); + Group = new PageGroup(); + PageLines = new Lines(); + PageRectangles = new Rectangles(); + PageImageObjects = new ImageObjects(); + PageStringObjects = new StringObjects(); + PagerKind = new Kinds(); + this.Font = new System.Drawing.Font("", 3, System.Drawing.FontStyle.Regular, GraphicsUnit.Millimeter); + if (width < height) + { + PagerKind.Add(new Kind("ԶС", Convert.ToInt32(width), Convert.ToInt32(height), false)); + } + else + { + PagerKind.Add(new Kind("ԶС", Convert.ToInt32(width), Convert.ToInt32(height), true)); + } + this.Width = width; + this.Height = height; + this.Group.Width = this.Width - this.Left - this.Right; + } + + + + #region ѶתDataSet + public DataSet ConvertDataSet() + { + DataSet ds = new DataSet(); + DataRow row = null; + // + DataTable ReportTable = new DataTable("MyReport"); + ReportTable.Columns.Add("PageRecordNumber", typeof(int)); //ҳ + ReportTable.Columns.Add("Width", typeof(float)); // + ReportTable.Columns.Add("Height", typeof(float)); //߶ + ReportTable.Columns.Add("ShowPagerNumber", typeof(bool)); //Ƿʾҳ + ReportTable.Columns.Add("AutoMathPageRecordNumber", typeof(bool)); //ǷԶÿҳ + ReportTable.Columns.Add("TableRowHeightReviseNumber", typeof(float)); //иֵ(ϱ±ߵĿ϶) + ReportTable.Columns.Add("HeaderHeight", typeof(float)); //ҳü߶ + ReportTable.Columns.Add("GroupWidth", typeof(float)); // + ReportTable.Columns.Add("GroupHeight", typeof(float)); //߶ + ReportTable.Columns.Add("FooterHeight", typeof(float)); //ҳβ߶ + ReportTable.Columns.Add("Top", typeof(float)); //ϱ߾ + ReportTable.Columns.Add("Left", typeof(float)); //߾ + ReportTable.Columns.Add("Right", typeof(float)); //ұ߾ + ReportTable.Columns.Add("Bottom", typeof(float)); //±߾ + ReportTable.Columns.Add("IsFillBlank", typeof(bool)); //Ƿӡ + ReportTable.Columns.Add("familyName", typeof(string)); // + ReportTable.Columns.Add("emSize", typeof(float)); //С + ReportTable.Columns.Add("FontStyle", typeof(int)); //ʽ + ReportTable.Columns.Add("GraphicsUnit", typeof(int)); //嵥λ + ReportTable.Columns.Add("PageLayout", typeof(int)); //ҳ沼 + ReportTable.Columns.Add("RotatePoint", typeof(float)); //ת + ReportTable.Columns.Add("RotateX", typeof(float)); //תXת + ReportTable.Columns.Add("RotateY", typeof(float)); //תYת + + + ds.Tables.Add(ReportTable); + + row = ds.Tables["MyReport"].NewRow(); + row["Width"] = this.Width; + row["Height"] = this.Height; + row["PageRecordNumber"] = this.PageRecordNumber; + row["ShowPagerNumber"] = this.ShowPagerNumber; + row["AutoMathPageRecordNumber"] = this.AutoMathPageRecordNumber; + row["TableRowHeightReviseNumber"] = this.TableRowHeightReviseNumber; + row["HeaderHeight"] = this.Header.Height; + row["GroupWidth"] = this.Group.Width; + row["GroupHeight"] = this.Group.Height; + row["FooterHeight"] = this.Footer.Height; + row["Top"] = this.Top; + row["Left"] = this.Left; + row["Right"] = this.Right; + row["Bottom"] = this.Bottom; + row["IsFillBlank"] = this.IsFillBlank; + row["familyName"] = this.Font.Name; + row["emSize"] = this.Font.Size; + row["FontStyle"] = (int)this.Font.Style; + row["GraphicsUnit"] = (int)this.Font.Unit; + row["PageLayout"] = this.PageLayout; + row["RotatePoint"] = this.RotatePoint; + row["RotateX"] = this.RotateX; + row["RotateY"] = this.RotateY; + + ds.Tables["MyReport"].Rows.Add(row); + + + DataTable KindTable = new DataTable("PagerKind"); + KindTable.Columns.Add("Name", typeof(string)); //ֽ + KindTable.Columns.Add("Height", typeof(int)); //߶ + KindTable.Columns.Add("Width", typeof(int)); // + KindTable.Columns.Add("KindType", typeof(int)); //ֽ + KindTable.Columns.Add("Landscape", typeof(bool)); // + ds.Tables.Add(KindTable); + foreach (Kind kd in this.PagerKind) + { + row = ds.Tables["PagerKind"].NewRow(); + row["Name"] = kd.Name; + row["Height"] = kd.Height; + row["Width"] = kd.Width; + row["KindType"] = kd.KindType; + row["Landscape"] = kd.Landscape; + ds.Tables["PagerKind"].Rows.Add(row); + } + + + //߶ + DataTable LinesTable = new DataTable("Lines"); + LinesTable.Columns.Add("BrushWidth", typeof(float)); + LinesTable.Columns.Add("x1", typeof(float)); + LinesTable.Columns.Add("y1", typeof(float)); + LinesTable.Columns.Add("x2", typeof(float)); + LinesTable.Columns.Add("y2", typeof(float)); + ds.Tables.Add(LinesTable); + + foreach (Line l in this.PageLines) + { + row = ds.Tables["Lines"].NewRow(); + row["BrushWidth"] = l.BrushWidth; + row["x1"] = l.Pt1.X; + row["y1"] = l.Pt1.Y; + row["x2"] = l.Pt2.X; + row["y2"] = l.Pt2.Y; + ds.Tables["Lines"].Rows.Add(row); + } + + //ͼƬ + DataTable ImageObjectsTable = new DataTable("ImageObjects"); + ImageObjectsTable.Columns.Add("IsZoom", typeof(bool)); + ImageObjectsTable.Columns.Add("Height", typeof(int)); + ImageObjectsTable.Columns.Add("Width", typeof(int)); + ImageObjectsTable.Columns.Add("Top", typeof(int)); + ImageObjectsTable.Columns.Add("Left", typeof(int)); + ImageObjectsTable.Columns.Add("MemoryByte", typeof(byte[])); + ds.Tables.Add(ImageObjectsTable); + + foreach (ImageObject img in this.PageImageObjects) + { + row = ds.Tables["ImageObjects"].NewRow(); + row["IsZoom"] = img.IsZoom; + row["Height"] = img.Height; + row["Width"] = img.Width; + row["Top"] = img.Top; + row["Left"] = img.Left; + row["MemoryByte"] = img.MemoryByte; + ds.Tables["ImageObjects"].Rows.Add(row); + } + + //ζ + DataTable RectanglesTable = new DataTable("Rectangles"); + RectanglesTable.Columns.Add("BrushWidth", typeof(float)); + RectanglesTable.Columns.Add("X", typeof(float)); + RectanglesTable.Columns.Add("Y", typeof(float)); + RectanglesTable.Columns.Add("Width", typeof(float)); + RectanglesTable.Columns.Add("Height", typeof(float)); + ds.Tables.Add(RectanglesTable); + + foreach (Rectangle l in this.PageRectangles) + { + row = ds.Tables["Rectangles"].NewRow(); + row["BrushWidth"] = l.BrushWidth; + row["X"] = l.X; + row["Y"] = l.Y; + row["Width"] = l.Width; + row["Height"] = l.Height; + ds.Tables["Rectangles"].Rows.Add(row); + } + + + DataTable PageRowsTable = new DataTable("PageRows"); + PageRowsTable.Columns.Add("ReportSign", typeof(int)); + PageRowsTable.Columns.Add("Alignment", typeof(int)); + PageRowsTable.Columns.Add("familyName", typeof(string)); + PageRowsTable.Columns.Add("emSize", typeof(float)); + PageRowsTable.Columns.Add("FontStyle", typeof(int)); + PageRowsTable.Columns.Add("GraphicsUnit", typeof(int)); + PageRowsTable.Columns.Add("FormatFlags", typeof(int)); + PageRowsTable.Columns.Add("Height", typeof(float)); + PageRowsTable.Columns.Add("LineAlignment", typeof(int)); + PageRowsTable.Columns.Add("Text", typeof(string)); + ds.Tables.Add(PageRowsTable); + + foreach (PageRow prow in this.Header.Rows) + { + row = ds.Tables["PageRows"].NewRow(); + row["ReportSign"] = 1; + row["Alignment"] = (int)prow.Alignment; + if (prow.Font != null) + { + row["familyName"] = prow.Font.Name; + row["emSize"] = prow.Font.Size; + row["FontStyle"] = (int)prow.Font.Style; + row["GraphicsUnit"] = (int)prow.Font.Unit; + } + row["FormatFlags"] = (int)prow.FormatFlags; + row["Height"] = prow.Height; + row["LineAlignment"] = (int)prow.LineAlignment; + row["Text"] = prow.Text; + ds.Tables["PageRows"].Rows.Add(row); + } + foreach (PageRow prow in this.Footer.Rows) + { + row = ds.Tables["PageRows"].NewRow(); + row["ReportSign"] = 2; + row["Alignment"] = (int)prow.Alignment; + if (prow.Font != null) + { + row["familyName"] = prow.Font.Name; + row["emSize"] = prow.Font.Size; + row["FontStyle"] = (int)prow.Font.Style; + row["GraphicsUnit"] = (int)prow.Font.Unit; + } + row["FormatFlags"] = (int)prow.FormatFlags; + row["Height"] = prow.Height; + row["LineAlignment"] = (int)prow.LineAlignment; + row["Text"] = prow.Text; + ds.Tables["PageRows"].Rows.Add(row); + } + + + // + DataTable tb = new DataTable("Table"); + tb.Columns.Add("TableID", typeof(int)); + tb.Columns.Add("Height", typeof(float)); + tb.Columns.Add("ShowLine", typeof(bool)); + tb.Columns.Add("Width", typeof(float)); + ds.Tables.Add(tb); + + //ж + DataTable ColumnsTable = new DataTable("TableColumns"); + ColumnsTable.Columns.Add("TableID", typeof(int)); + ColumnsTable.Columns.Add("MinWidth", typeof(float)); + ColumnsTable.Columns.Add("Width", typeof(float)); + ds.Tables.Add(ColumnsTable); + //ж + DataTable RowsTable = new DataTable("TableRows"); + RowsTable.Columns.Add("TableID", typeof(int)); + RowsTable.Columns.Add("RowID", typeof(int)).AutoIncrement = true; + RowsTable.Columns["RowID"].AutoIncrementSeed = 1; + RowsTable.Columns["RowID"].AutoIncrementStep = 1; + RowsTable.Columns.Add("Height", typeof(float)); + RowsTable.Columns.Add("RowSpan", typeof(int)); + ds.Tables.Add(RowsTable); + + //жеĵԪ + DataTable CellTable = new DataTable("TableCells"); + CellTable.Columns.Add("RowID", typeof(int)); + CellTable.Columns.Add("Alignment", typeof(int)); + CellTable.Columns.Add("BorderWidth", typeof(float)); + CellTable.Columns.Add("ColumnSpan", typeof(int)); + CellTable.Columns.Add("familyName", typeof(string)); + CellTable.Columns.Add("emSize", typeof(float)); + CellTable.Columns.Add("FontStyle", typeof(int)); + CellTable.Columns.Add("GraphicsUnit", typeof(int)); + CellTable.Columns.Add("FormatFlags", typeof(int)); + CellTable.Columns.Add("Height", typeof(float)); + CellTable.Columns.Add("LineAlignment", typeof(int)); + CellTable.Columns.Add("RowSpan", typeof(int)); + CellTable.Columns.Add("Text", typeof(string)); + CellTable.Columns.Add("Visible", typeof(bool)); + CellTable.Columns.Add("VisibleState", typeof(bool)); + CellTable.Columns.Add("Width", typeof(float)); + ds.Tables.Add(CellTable); + + FillTable(ds, 1, this.Header.TableItem); + FillTable(ds, 2, this.Group.Header); + FillTable(ds, 3, this.Group.DataItem); + FillTable(ds, 4, this.Group.Footer); + FillTable(ds, 5, this.Footer.TableItem); + FillTable(ds, 6, this.Group.LeftItem); + FillTable(ds, 7, this.Group.RightItem); + return ds; + } + + + private void FillTable(DataSet ds, int TableID, Table table) + { + DataRow row = null; + row = ds.Tables["Table"].NewRow(); + row["TableID"] = TableID; + row["Height"] = table.Height; + row["ShowLine"] = table.ShowLine; + row["Width"] = table.Width; + ds.Tables["Table"].Rows.Add(row); + foreach (TableColumn col in table.Columns) + { + row = ds.Tables["TableColumns"].NewRow(); + row["TableID"] = TableID; + row["MinWidth"] = col.MinWidth; + row["Width"] = col.Width; + ds.Tables["TableColumns"].Rows.Add(row); + } + foreach (TableRow trow in table.Rows) + { + row = ds.Tables["TableRows"].NewRow(); + row["TableID"] = TableID; + row["Height"] = trow.Height; + row["RowSpan"] = trow.RowSpan; + ds.Tables["TableRows"].Rows.Add(row); + int rowid = Convert.ToInt32(row["RowID"]); + foreach (TableCell cell in trow.Cells) + { + row = ds.Tables["TableCells"].NewRow(); + row["RowID"] = rowid; + row["Alignment"] = (int)cell.Alignment; + row["BorderWidth"] = cell.BorderWidth; + row["ColumnSpan"] = cell.ColumnSpan; + if (cell.Font != null) + { + row["familyName"] = cell.Font.Name; + row["emSize"] = cell.Font.Size; + row["FontStyle"] = (int)cell.Font.Style; + row["GraphicsUnit"] = (int)cell.Font.Unit; + } + row["FormatFlags"] = cell.FormatFlags; + row["Height"] = cell.Height; + row["LineAlignment"] = (int)cell.LineAlignment; + row["RowSpan"] = cell.RowSpan; + row["Text"] = cell.Text; + row["Visible"] = cell.Visible; + row["VisibleState"] = cell.VisibleState; + row["Width"] = cell.Width; + ds.Tables["TableCells"].Rows.Add(row); + } + } + } + #endregion + #region ˱ݵDataSetʼ + /// + /// ˱ݵDataSetʼ + /// + /// + public void InitReport(DataSet ds) + { + this.Height = Convert.ToSingle(ds.Tables["MyReport"].Rows[0]["Height"]); + this.Width = Convert.ToSingle(ds.Tables["MyReport"].Rows[0]["Width"]); + this.PageRecordNumber = Convert.ToInt32(ds.Tables["MyReport"].Rows[0]["PageRecordNumber"]); + this.ShowPagerNumber = Convert.ToBoolean(ds.Tables["MyReport"].Rows[0]["ShowPagerNumber"]); + this.AutoMathPageRecordNumber = Convert.ToBoolean(ds.Tables["MyReport"].Rows[0]["AutoMathPageRecordNumber"]); + this.TableRowHeightReviseNumber = Convert.ToSingle(ds.Tables["MyReport"].Rows[0]["TableRowHeightReviseNumber"]); + this.Header.Height = Convert.ToSingle(ds.Tables["MyReport"].Rows[0]["HeaderHeight"]); + this.Group.Height = Convert.ToSingle(ds.Tables["MyReport"].Rows[0]["GroupHeight"]); + this.Group.Width = Convert.ToSingle(ds.Tables["MyReport"].Rows[0]["GroupWidth"]); + this.Footer.Height = Convert.ToSingle(ds.Tables["MyReport"].Rows[0]["FooterHeight"]); + this.Left = Convert.ToSingle(ds.Tables["MyReport"].Rows[0]["Left"]); + this.Bottom = Convert.ToSingle(ds.Tables["MyReport"].Rows[0]["Bottom"]); + this.Top = Convert.ToSingle(ds.Tables["MyReport"].Rows[0]["Top"]); + this.Right = Convert.ToSingle(ds.Tables["MyReport"].Rows[0]["Right"]); + this.IsFillBlank = Convert.ToBoolean(ds.Tables["MyReport"].Rows[0]["IsFillBlank"]); + this.RotatePoint = Convert.ToSingle(ds.Tables["MyReport"].Rows[0]["RotatePoint"]); + this.RotateX = Convert.ToSingle(ds.Tables["MyReport"].Rows[0]["RotateX"]); + this.RotateY = Convert.ToSingle(ds.Tables["MyReport"].Rows[0]["RotateY"]); + + this.Font = new Font(ds.Tables["MyReport"].Rows[0]["familyName"].ToString(), Convert.ToSingle(ds.Tables["MyReport"].Rows[0]["emSize"]), (FontStyle)ds.Tables["MyReport"].Rows[0]["FontStyle"], (GraphicsUnit)ds.Tables["MyReport"].Rows[0]["GraphicsUnit"]); + this.PageLayout = (PageLayoutType)ds.Tables["MyReport"].Rows[0]["PageLayout"]; + Kind kd = null; + Line lin = null; // + Rectangle rect = null; // + ImageObject img = null; //ͼƬ + PageRow prow = null; // + TableColumn col; // + TableRow trow = null; // + TableCell cell = null; //ĵԪ + DataRow[] drow = null; + foreach (DataRow row in ds.Tables["PagerKind"].Rows) + { + kd = new Kind(); + kd.Height = Convert.ToInt32(row["Height"]); + kd.Width = Convert.ToInt32(row["Width"]); + kd.Name = Convert.ToString(row["Name"]); + kd.KindType = (KindType)row["KindType"]; + kd.Landscape = (bool)row["Landscape"]; + this.PagerKind.Add(kd); + } + foreach (DataRow row in ds.Tables["Lines"].Rows) + { + lin = new Line(); + lin.BrushWidth = Convert.ToSingle(row["BrushWidth"]); + lin.Pt1 = new PointF(Convert.ToSingle(row["x1"]), Convert.ToSingle(row["y1"])); + lin.Pt2 = new PointF(Convert.ToSingle(row["x2"]), Convert.ToSingle(row["y2"])); + this.PageLines.Add(lin); + } + foreach (DataRow row in ds.Tables["ImageObjects"].Rows) + { + img = new ImageObject(); + img.IsZoom = Convert.ToBoolean(row["IsZoom"]); + img.Height = Convert.ToInt32(row["Height"]); + img.Width = Convert.ToInt32(row["Width"]); + img.Left = Convert.ToInt32(row["Left"]); + img.Top = Convert.ToInt32(row["Top"]); + img.MemoryByte = (byte[])row["MemoryByte"]; + this.PageImageObjects.Add(img); + } + foreach (DataRow row in ds.Tables["Rectangles"].Rows) + { + rect = new Rectangle(); + rect.BrushWidth = Convert.ToSingle(row["BrushWidth"]); + rect.Height = Convert.ToSingle(row["Height"]); + rect.Width = Convert.ToSingle(row["Width"]); + rect.X = Convert.ToSingle(row["X"]); + rect.Y = Convert.ToSingle(row["Y"]); + this.PageRectangles.Add(rect); + } + foreach (DataRow row in ds.Tables["PageRows"].Rows) + { + prow = new PageRow(); + prow.Alignment = (StringAlignment)row["Alignment"]; + if (row.IsNull("familyName") == false) + { + prow.Font = new Font(row["familyName"].ToString(), Convert.ToSingle(row["emSize"]), (FontStyle)row["FontStyle"], (GraphicsUnit)row["GraphicsUnit"]); + } + prow.FormatFlags = (StringFormatFlags)row["FormatFlags"]; + prow.Height = Convert.ToSingle(row["Height"]); + prow.LineAlignment = (StringAlignment)row["LineAlignment"]; + prow.Text = row["Text"].ToString(); + if (row["ReportSign"].ToString() == "1") + { + this.Header.Rows.Add(prow); + } + else + { + this.Footer.Rows.Add(prow); + } + } + + foreach (DataRow row in ds.Tables["Table"].Rows) + { + int TableID = Convert.ToInt32(row["TableID"]); + switch (TableID) + { + case 1: + this.Header.TableItem.Height = Convert.ToSingle(row["Height"]); + this.Header.TableItem.ShowLine = Convert.ToBoolean(row["ShowLine"]); + this.Header.TableItem.Width = Convert.ToSingle(row["Width"]); + break; + case 2: + this.Group.Header.Height = Convert.ToSingle(row["Height"]); + this.Group.Header.ShowLine = Convert.ToBoolean(row["ShowLine"]); + this.Group.Header.Width = Convert.ToSingle(row["Width"]); + break; + case 3: + this.Group.DataItem.Height = Convert.ToSingle(row["Height"]); + this.Group.DataItem.ShowLine = Convert.ToBoolean(row["ShowLine"]); + this.Group.DataItem.Width = Convert.ToSingle(row["Width"]); + break; + case 4: + this.Group.Footer.Height = Convert.ToSingle(row["Height"]); + this.Group.Footer.ShowLine = Convert.ToBoolean(row["ShowLine"]); + this.Group.Footer.Width = Convert.ToSingle(row["Width"]); + break; + case 5: + this.Footer.TableItem.Height = Convert.ToSingle(row["Height"]); + this.Footer.TableItem.ShowLine = Convert.ToBoolean(row["ShowLine"]); + this.Footer.TableItem.Width = Convert.ToSingle(row["Width"]); + break; + case 6: + this.Group.LeftItem.Height = Convert.ToSingle(row["Height"]); + this.Group.LeftItem.ShowLine = Convert.ToBoolean(row["ShowLine"]); + this.Group.LeftItem.Width = Convert.ToSingle(row["Width"]); + break; + case 7: + this.Group.RightItem.Height = Convert.ToSingle(row["Height"]); + this.Group.RightItem.ShowLine = Convert.ToBoolean(row["ShowLine"]); + this.Group.RightItem.Width = Convert.ToSingle(row["Width"]); + break; + default: + break; + } + } + + foreach (DataRow row in ds.Tables["TableColumns"].Rows) + { + int TableID = Convert.ToInt32(row["TableID"]); + col = new TableColumn(); + col.MinWidth = Convert.ToSingle(row["MinWidth"]); + col.Width = Convert.ToSingle(row["Width"]); + switch (TableID) + { + case 1: + this.Header.TableItem.Columns.Add(col); + break; + case 2: + this.Group.Header.Columns.Add(col); + break; + case 3: + this.Group.DataItem.Columns.Add(col); + break; + case 4: + this.Group.Footer.Columns.Add(col); + break; + case 5: + this.Footer.TableItem.Columns.Add(col); + break; + case 6: + this.Group.LeftItem.Columns.Add(col); + break; + case 7: + this.Group.RightItem.Columns.Add(col); + break; + default: + break; + } + } + + foreach (DataRow row in ds.Tables["TableRows"].Rows) + { + int TableID = Convert.ToInt32(row["TableID"]); + string rowID = Convert.ToString(row["RowID"]); + trow = new TableRow(); + trow.Height = Convert.ToSingle(row["Height"]); + trow.RowSpan = Convert.ToInt32(row["RowSpan"]); + //䵥Ԫ + drow = ds.Tables["TableCells"].Select("RowID=" + rowID); + foreach (DataRow arow in drow) + { + cell = new TableCell(); + cell.Alignment = (StringAlignment)arow["Alignment"]; + cell.BorderWidth = Convert.ToSingle(arow["BorderWidth"]); + cell.ColumnSpan = Convert.ToInt32(arow["ColumnSpan"]); + if (arow.IsNull("familyName") == false) + { + cell.Font = new Font(arow["familyName"].ToString(), Convert.ToSingle(arow["emSize"]), (FontStyle)arow["FontStyle"], (GraphicsUnit)arow["GraphicsUnit"]); + } + cell.FormatFlags = (StringFormatFlags)arow["FormatFlags"]; + cell.Height = Convert.ToSingle(arow["Height"]); + cell.LineAlignment = (StringAlignment)arow["LineAlignment"]; + cell.RowSpan = Convert.ToInt32(arow["RowSpan"]); + cell.Text = Convert.ToString(arow["Text"]); + cell.Visible = Convert.ToBoolean(arow["Visible"]); + cell.VisibleState = Convert.ToBoolean(arow["VisibleState"]); + cell.Width = Convert.ToSingle(arow["Width"]); + trow.Cells.Add(cell); + } + switch (TableID) + { + case 1: + this.Header.TableItem.Rows.Add(trow); + break; + case 2: + this.Group.Header.Rows.Add(trow); + break; + case 3: + this.Group.DataItem.Rows.Add(trow); + break; + case 4: + this.Group.Footer.Rows.Add(trow); + break; + case 5: + this.Footer.TableItem.Rows.Add(trow); + break; + case 6: + this.Group.LeftItem.Rows.Add(trow); + break; + case 7: + this.Group.RightItem.Rows.Add(trow); + break; + default: + break; + } + } + + } + #endregion + + + + public SizeF MeasureString(string Text, Font font) + { + if (PagerKind.Count == 0) throw new Exception("ܴӡֽͶPagerKind"); + System.Drawing.Font ffont = font; + if (font == null) ffont = this.Font; + Bitmap bmp = new Bitmap(PagerKind[0].Width, PagerKind[0].Height); + Graphics g = Graphics.FromImage(bmp); + g.PageUnit = GraphicsUnit.Millimeter; + SizeF s = g.MeasureString(Text, ffont); + return s; + } + + public void InitReport() + { + //ʽ + if (this.Header.TableItem.Rows.Count > 0) FormatGroups(this.Header.TableItem); //ҳü + if (this.Footer.TableItem.Rows.Count > 0) FormatGroups(this.Footer.TableItem); //ҳü + if (this.Group.Header.Rows.Count > 0) FormatGroups(this.Group.Header); + if (this.Group.DataItem.Rows.Count > 0) FormatGroups(this.Group.DataItem); + if (this.Group.Footer.Rows.Count > 0) FormatGroups(this.Group.Footer); + if (this.Group.LeftItem.Rows.Count > 0) FormatGroups(this.Group.LeftItem); + if (this.Group.RightItem.Rows.Count > 0) FormatGroups(this.Group.RightItem); + } + + + void FormatGroups(Table table) + { + float tableWidth = 0; + Font CurrentFont = this.Font; + foreach (TableColumn col in table.Columns) + { + if (col.Width != 0) { tableWidth = tableWidth + col.Width; continue; } + int index = table.Columns.IndexOf(col); + float colWidth = 0; + for (int i = 0; i < table.Rows.Count; i++) + { + //п + TableCell cell = table.Rows[i].Cells[index]; + if (cell.Font != null) CurrentFont = cell.Font; + if (cell.FormatFlags == StringFormatFlags.DirectionVertical) { continue; } + string value1 = Regex.Replace(cell.Text, "", "", RegexOptions.IgnoreCase); + value1 = Regex.Replace(value1, "", "", RegexOptions.IgnoreCase); + value1 = Regex.Replace(value1, "", "", RegexOptions.IgnoreCase); + value1 = Regex.Replace(value1, "", "", RegexOptions.IgnoreCase); + if (Regex.IsMatch(value1, "
", RegexOptions.IgnoreCase) == false) + { + float colw = this.MeasureString(value1, CurrentFont).Width; + if (colw > colWidth) { colWidth = colw; } + } + else + { + string[] ss = Regex.Split(value1, "
", RegexOptions.IgnoreCase); + foreach (string s in ss) + { + float colw = this.MeasureString(s, CurrentFont).Width; + if (colw > colWidth) { colWidth = colw; } + } + } + + } + col.Width = colWidth; + colWidth = 0; + tableWidth = tableWidth + col.Width; + } + table.Width = tableWidth; + + + float tableHeight = 0; + foreach (TableRow row in table.Rows) + { + + for (int i = 0; i < table.Columns.Count; i++) + { + TableCell cell = row.Cells[i]; + if (cell.RowSpan > 1) + {//>1,ô,㱾Ԫ߶ + for (int ii = 1; ii < cell.RowSpan; ii++) + { + table.Rows[table.Rows.IndexOf(row) + ii].Cells[i].Visible = false; + table.Rows[table.Rows.IndexOf(row) + ii].Cells[i].VisibleState = false; + } + } + + if (cell.ColumnSpan > 1) + {//1ô㱾Ԫ + for (int ii = 1; ii < cell.ColumnSpan; ii++) + { + row.Cells[i + ii].Visible = false; + row.Cells[i + ii].VisibleState = true; + } + } + + //ǵһ,ϱߵĵԪΪ,ôصԪ + int rowIndex = table.Rows.IndexOf(row); + if (rowIndex != 0 && i > 0) + { + if (row.Cells[i - 1].Visible == false && row.Cells[i - 1].VisibleState == false && table.Rows[rowIndex - 1].Cells[i].Visible == false && table.Rows[rowIndex - 1].Cells[i].VisibleState == true) + { + cell.Visible = false; + } + } + + } + tableHeight = tableHeight + (row.Height + this.TableRowHeightReviseNumber) * row.RowSpan; + } + table.Height = tableHeight; + } + } + #endregion + #region ҳü + /// + /// ҳü + /// + [Serializable] + public class PageHeader + { + private float m_Height; + + public float Height + { + get { return m_Height; } + set { m_Height = value; } + } + + private PageRows m_Rows; + + public PageRows Rows + { + get { return m_Rows; } + set { m_Rows = value; } + } + private Table m_TableItem; + /// + /// + /// + public Table TableItem + { + get { return m_TableItem; } + set { m_TableItem = value; } + } + + public PageHeader() + { + m_Rows = new PageRows(); + m_TableItem = new Table(); + m_TableItem.ShowLine = false; + } + } + #endregion + #region ҳ + /// + /// ҳ + /// + [Serializable] + public class PageFooter + { + private float m_Height; + + public float Height + { + get { return m_Height; } + set { m_Height = value; } + } + + private PageRows m_Rows; + + public PageRows Rows + { + get { return m_Rows; } + set { m_Rows = value; } + } + private Table m_TableItem; + /// + /// + /// + public Table TableItem + { + get { return m_TableItem; } + set { m_TableItem = value; } + } + + public PageFooter() + { + m_Rows = new PageRows(); + m_TableItem = new Table(); + m_TableItem.ShowLine = false; + } + } + #endregion + #region + [Serializable] + public class PageGroup + { + + private float m_Height; + public float Height + { + get { return m_Height; } + set { m_Height = value; } + } + private Font m_Font; + public Font Font + { + get + { + return this.m_Font; + } + set + { + m_Font = value; + } + } + + public PageGroup() + { + this.Header = new Table(); + this.DataItem = new Table(); + this.Footer = new Table(); + this.LeftItem = new Table(); + this.RightItem = new Table(); + this.Font = new System.Drawing.Font("", 3, System.Drawing.FontStyle.Regular, GraphicsUnit.Millimeter); + } + + #region ʼ + /// + /// DataTableʼ) + /// + /// + public void InitGroup(DataTable tb) + { + Header.Rows.Clear(); + DataItem.Rows.Clear(); + TableRow row; + // int RowNumber = 1; //и߱ + // float WidthCount = 0; //еԪı + float colWidthCount = 0; + if (Header.Columns.Count == 0) + {//û + for (int i = 0; i < tb.Columns.Count; i++) + { + string value1 = tb.Columns[i].Caption.Replace("", ""); + value1 = value1.Replace("", ""); + value1 = value1.Replace("", ""); + value1 = value1.Replace("", ""); + tb.Columns[i].ExtendedProperties.Add("Width", this.MeasureString(value1, this.Font).Width + MeasureString("A", this.Font).Width); + } + foreach (DataColumn col in tb.Columns) + { + colWidthCount = colWidthCount + Convert.ToSingle(col.ExtendedProperties["Width"]); + } + float SurplusWidth = this.Width - this.LeftItem.Width - this.RightItem.Width - colWidthCount; + float addWidth = 0; + if (SurplusWidth > 0) addWidth = SurplusWidth / Convert.ToSingle(tb.Columns.Count); + foreach (DataColumn col in tb.Columns) + { + col.ExtendedProperties["Width"] = Convert.ToSingle(col.ExtendedProperties["Width"]) + addWidth; + } + + for (int i = 0; i < tb.Columns.Count; i++) + { + Header.Columns.Add(new TableColumn(Convert.ToSingle(tb.Columns[i].ExtendedProperties["Width"]))); + DataItem.Columns.Add(new TableColumn(Convert.ToSingle(tb.Columns[i].ExtendedProperties["Width"]))); + } + + + + + row = Header.NewRow(); + for (int i = 0; i < tb.Columns.Count; i++) + {//б + row.Cells[i].Text = tb.Columns[i].Caption; + row.Cells[i].Width = Header.Columns[i].Width; + Header.Columns[i].Name = tb.Columns[i].ColumnName; + } + // if (this.Header.Height == 0) row.Height = MeasureString("Ը߶", this.Font).Height; + // if (this.Header.Height != 0) row.Height = this.Header.Height / Convert.ToSingle(tb.Rows.Count + 1); + Header.Rows.Add(row); + } + else + { + foreach (TableColumn col in Header.Columns) + { + if (tb.Columns[col.Name].ExtendedProperties.Contains("Width") == false) tb.Columns[col.Name].ExtendedProperties.Add("Width", 0); + if (col.Width == 0) + { + string value1 = col.Caption.Replace("", ""); + value1 = value1.Replace("", ""); + value1 = value1.Replace("", ""); + value1 = value1.Replace("", ""); + tb.Columns[col.Name].ExtendedProperties["Width"] = this.MeasureString(value1, this.Font).Width + MeasureString("A", this.Font).Width; + } + else + { + tb.Columns[col.Name].ExtendedProperties["Width"] = col.Width; + } + this.DataItem.Columns.Add(col.Name, col.Caption, col.DataType, col.Format); + } + foreach (DataRow crow in tb.Rows) + { + foreach (TableColumn col in Header.Columns) + { + if (col.Width != 0) continue; + string value = crow[col.Name].ToString(); + if (col.Format != "") + { + if (col.DataType == DbType.DateTime) + { + value = DataConvert.Format(value, TypeCode.DateTime, col.Format); + } + else if (col.DataType == DbType.Decimal || col.DataType == DbType.Single || col.DataType == DbType.Double) + { + value = DataConvert.Format(value, TypeCode.Decimal, col.Format); + } + else + { + value = crow[col.Name].ToString(); + } + } + string value1 = value.Replace("", ""); + value1 = value1.Replace("", ""); + value1 = value1.Replace("", ""); + value1 = value1.Replace("", ""); + float width = this.MeasureString(value1, this.Font).Width + this.MeasureString("A", this.Font).Width; + float maxWidth = Convert.ToSingle(tb.Columns[col.Name].ExtendedProperties["Width"]); + if (width > maxWidth) tb.Columns[col.Name].ExtendedProperties["Width"] = width; + } + } + foreach (DataColumn col in tb.Columns) + { + if (col.ExtendedProperties.ContainsKey("Width") == false) continue; + colWidthCount = colWidthCount + Convert.ToSingle(col.ExtendedProperties["Width"]); + } + float SurplusWidth = this.Width - this.LeftItem.Width - this.RightItem.Width - colWidthCount; + float addWidth = 0; + if (SurplusWidth > 0) + {//ܿСݲôʣĿƽ,Сп(ݼʽ) + addWidth = SurplusWidth / Convert.ToSingle(Header.Columns.Count); + foreach (DataColumn col in tb.Columns) + { + if (col.ExtendedProperties.ContainsKey("Width") == false) continue; + col.ExtendedProperties["Width"] = Convert.ToSingle(col.ExtendedProperties["Width"]) + addWidth; + } + } + for (int i = 0; i < Header.Columns.Count; i++) + { + this.Header.Columns[i].Width = Convert.ToSingle(tb.Columns[Header.Columns[i].Name].ExtendedProperties["Width"]); + this.DataItem.Columns[i].Width = Convert.ToSingle(tb.Columns[Header.Columns[i].Name].ExtendedProperties["Width"]); + } + if (SurplusWidth < 0) + { + float ColWidthCount = 0; //Спܿ + foreach (TableColumn col in this.Header.Columns) + { + if (col.Width <= col.MinWidth) continue; + ColWidthCount = ColWidthCount + col.Width; + } + for (int i = 0; i < Header.Columns.Count; i++) + { + if (Header.Columns[i].Width <= Header.Columns[i].MinWidth) continue; + Header.Columns[i].Width = Header.Columns[i].Width + Header.Columns[i].Width / ColWidthCount * SurplusWidth; //пܿȡпðٷֱȣȱܿ + this.DataItem.Columns[i].Width = Header.Columns[i].Width; + + } + } + + + + row = Header.NewRow(); + for (int i = 0; i < Header.Columns.Count; i++) + { + row.Cells[i].Text = Header.Columns[i].Caption; + row.Cells[i].Width = Header.Columns[i].Width; + row.Cells[i].Alignment = Header.Columns[i].StringFormat.Alignment; + row.Cells[i].LineAlignment = Header.Columns[i].StringFormat.LineAlignment; + row.Cells[i].FormatFlags = Header.Columns[i].StringFormat.FormatFlags; + + // WidthCount = MeasureString(row.Cells[i].Text, this.Font).Width; + // int CurrentRowNumber = Convert.ToInt32(Math.Ceiling(WidthCount / (Header.Columns[i].Width))); + // if (CurrentRowNumber > RowNumber) RowNumber = CurrentRowNumber; + } + row.RowSpan = 1; + // row.Height = MeasureString("Ը߶", this.Font).Height; + Header.Rows.Add(row); + } + + foreach (DataRow row1 in tb.Rows) + { + + row = Header.NewRow(); + foreach (TableColumn col in Header.Columns) + { + int index = Header.Columns.IndexOf(col); + if (col.Format != "") + { + if (col.DataType == DbType.DateTime) + { + row.Cells[index].Text = DataConvert.Format(row1[col.Name], TypeCode.DateTime, col.Format); + } + else if (col.DataType == DbType.Decimal || col.DataType == DbType.Single || col.DataType == DbType.Double) + { + row.Cells[index].Text = DataConvert.Format(row1[col.Name], TypeCode.Decimal, col.Format); + } + else + { + row.Cells[index].Text = row1[col.Name].ToString(); + } + } + else + { + row.Cells[index].Text = row1[col.Name].ToString(); + } + row.Cells[index].Width = col.Width; + row.Cells[index].Alignment = col.StringFormat.Alignment; + row.Cells[index].LineAlignment = col.StringFormat.LineAlignment; + row.Cells[index].FormatFlags = col.StringFormat.FormatFlags; + + // WidthCount = MeasureString(row.Cells[index].Text, this.Font).Width; + //int CurrentRowNumber = Convert.ToInt32(Math.Ceiling(WidthCount / (col.Width - MeasureString("A", this.Font).Width))); + // int CurrentRowNumber = Convert.ToInt32(Math.Ceiling(WidthCount / (col.Width))); + // if (CurrentRowNumber > RowNumber) RowNumber = CurrentRowNumber; + } + row.RowSpan = 1; + // row.Height = MeasureString("Ը߶", this.Font).Height; + DataItem.Rows.Add(row); + } + + } + #endregion + + + + + public SizeF MeasureString(string Text, Font font) + { + System.Drawing.Font ffont = font; + if (font == null) ffont = this.Font; + Bitmap bmp = new Bitmap(100, 100); + Graphics g = Graphics.FromImage(bmp); + g.PageUnit = font.Unit; + SizeF s = g.MeasureString(Text, ffont); + return s; + } + + + private float m_Width; + + public float Width + { + get { return m_Width; } + set { m_Width = value; } + } + + private Table m_Header; + + /// + /// бͷ + /// + public Table Header + { + get { return m_Header; } + set { m_Header = value; } + } + private Table m_Footer; + + /// + /// бβ + /// + public Table Footer + { + get { return m_Footer; } + set { m_Footer = value; } + } + private Table m_DataItem; + + /// + /// + /// + public Table DataItem + { + get { return m_DataItem; } + set { m_DataItem = value; } + } + private Table m_LeftItem; + /// + /// ݱ + /// + public Table LeftItem + { + get { return m_LeftItem; } + set { m_LeftItem = value; } + } + private Table m_RightItem; + /// + /// ݱ + /// + public Table RightItem + { + get { return m_RightItem; } + set { m_RightItem = value; } + } + } + #endregion + #region ʾĵеһ + /// + /// ʾĵеһ + /// + [Serializable] + public class PageRow + { + /// + /// Ҫʾַ + /// + private string m_Text; + + public string Text + { + get { return m_Text; } + set { m_Text = value; } + } + + private float m_Height = 0; + + public float Height + { + get { return m_Height; } + set { m_Height = value; } + } + private System.Drawing.Font m_Font; + + public System.Drawing.Font Font + { + get { return m_Font; } + set { m_Font = value; } + } + private StringFormatFlags m_FormatFlags; + /// + /// ıʾʽ + /// + public StringFormatFlags FormatFlags + { + get { return m_FormatFlags; } + set { m_FormatFlags = value; } + } + + private StringAlignment m_LineAlignment; + /// + /// ж뷽ʽ + /// + public StringAlignment LineAlignment + { + get { return m_LineAlignment; } + set { m_LineAlignment = value; } + } + + private StringAlignment m_Alignment; + /// + /// ı뷽ʽ + /// + public StringAlignment Alignment + { + get { return m_Alignment; } + set { m_Alignment = value; } + } + + public PageRow() + { + this.LineAlignment = StringAlignment.Near; + this.Alignment = StringAlignment.Near; + this.FormatFlags = StringFormatFlags.DisplayFormatControl; + //this.Font = new System.Drawing.Font("", 3, System.Drawing.FontStyle.Regular,GraphicsUnit.Millimeter); + } + + public PageRow(string Text) + { + this.LineAlignment = StringAlignment.Near; + this.Alignment = StringAlignment.Near; + this.FormatFlags = StringFormatFlags.DisplayFormatControl; + //this.Font = new System.Drawing.Font("", 3, System.Drawing.FontStyle.Regular,GraphicsUnit.Millimeter); + this.Text = Text; + } + + public PageRow(string Text, float Height) + { + this.LineAlignment = StringAlignment.Near; + this.Alignment = StringAlignment.Near; + this.FormatFlags = StringFormatFlags.DisplayFormatControl; + //this.Font = new System.Drawing.Font("", 3, System.Drawing.FontStyle.Regular,GraphicsUnit.Millimeter); + this.Text = Text; + this.Height = Height; + } + + + } + #endregion + #region еļ + [Serializable] + public class PageRows + { + + private ArrayList Controls; + + + public int Count + { + get + { + return this.Controls.Count; + } + set { int a = value; } + } + + public PageRows() + { + Controls = new ArrayList(); + } + + public int IndexOf(PageRow item) + { + return Controls.IndexOf(item); + } + + public void Insert(int index, PageRow item) + { + Controls.Insert(index, item); + } + + public void RemoveAt(int index) + { + Controls.RemoveAt(index); + } + + public PageRow this[int index] + { + get + { + return (PageRow)Controls[index]; + } + set + { + Controls[index] = value; + } + } + + public PageRow GetRow(int index) + { + return (PageRow)Controls[index]; + } + + #region ICollection Ա + + public void Add(PageRow item) + { + Controls.Add(item); + } + public void Add(string Text, StringAlignment Alignment, Font font) + { + PageRow row = new PageRow(Text); + row.Height = MeasureString("Ը߶", font).Height; + row.Alignment = Alignment; + row.Font = font; + Controls.Add(row); + } + public void Add(string Text, Font font) + { + PageRow row = new PageRow(Text); + row.Height = MeasureString("Ը߶", font).Height; + row.Font = font; + Controls.Add(row); + } + public bool Contains(PageRow item) + { + return Controls.Contains(item); + } + + public void CopyTo(PageRow[] array, int arrayIndex) + { + Controls.CopyTo(array, arrayIndex); + } + + public void Clear() + { + Controls.Clear(); + } + + public bool IsReadOnly + { + get { return false; } + } + + public void Remove(PageRow item) + { + Controls.Remove(item); + } + + #endregion + + #region IEnumerable Ա + + public System.Collections.IEnumerator GetEnumerator() + { + return Controls.GetEnumerator(); + } + + #endregion + + private SizeF MeasureString(string Text, Font font) + { + Bitmap bmp = new Bitmap(100, 100); + Graphics g = Graphics.FromImage(bmp); + g.PageUnit = font.Unit; + SizeF s = g.MeasureString(Text, font); + return s; + } + } + #endregion + #region + /// + /// + /// + [Serializable] + public class TableColumn + { + private float m_Width = 0; + + public float Width + { + get + { + return m_Width; + } + set + { + this.m_Width = value; + } + } + + private float m_MinWidth = 0; + + /// + /// С + /// + public float MinWidth + { + get + { + return m_MinWidth; + } + set + { + + this.m_MinWidth = value; + } + } + + private string m_Caption; + /// + /// б + /// + public string Caption + { + get { return m_Caption; } + set { m_Caption = value; } + } + + private string m_Name; + /// + /// + /// + public string Name + { + get + { + return m_Name; + } + set + { + this.m_Name = value; + } + } + + private string m_Format; + /// + /// ʽ + /// + public string Format + { + get + { + return m_Format; + } + set + { + this.m_Format = value; + } + } + + private DbType m_DataType = DbType.String; + /// + /// + /// + public DbType DataType + { + get + { + return m_DataType; + } + set + { + this.m_DataType = value; + } + } + + private string m_Percent; + /// + /// пռðٷֱ + /// + public string Percent + { + get + { + return m_Percent; + } + set + { + this.m_Percent = value; + } + } + + private StringFormat m_StringFormat; + /// + /// ʽ + /// + public StringFormat StringFormat + { + get + { + return m_StringFormat; + } + set + { + this.m_StringFormat = value; + } + } + public Dictionary KeyValueFormat { get; set; } + public Func CellFormatter { get; set; } + public TableColumn() + { + StringFormat = new StringFormat(); + StringFormat.Alignment = StringAlignment.Center; + StringFormat.LineAlignment = StringAlignment.Center; + StringFormat.FormatFlags = StringFormatFlags.DisplayFormatControl; + KeyValueFormat = new Dictionary(); + } + public TableColumn(float Width) + { + m_Width = Width; + StringFormat = new StringFormat(); + StringFormat.Alignment = StringAlignment.Center; + StringFormat.LineAlignment = StringAlignment.Center; + StringFormat.FormatFlags = StringFormatFlags.DisplayFormatControl; + KeyValueFormat = new Dictionary(); + } + + public TableColumn(float Width, StringAlignment Alignment) + { + m_Width = Width; + StringFormat = new StringFormat(); + StringFormat.Alignment = Alignment; + StringFormat.LineAlignment = StringAlignment.Center; + StringFormat.FormatFlags = StringFormatFlags.DisplayFormatControl; + KeyValueFormat = new Dictionary(); + } + public TableColumn(float Width, StringAlignment Alignment, StringAlignment LineAlignment) + { + m_Width = Width; + StringFormat = new StringFormat(); + StringFormat.Alignment = Alignment; + StringFormat.LineAlignment = LineAlignment; + StringFormat.FormatFlags = StringFormatFlags.DisplayFormatControl; + KeyValueFormat = new Dictionary(); + } + + } + #endregion + #region е + /// + /// е + /// + [Serializable] + public class TableRow + { + private TableCellCollection TableCells; + private float m_Height = 0; + + public float Height + { + get { return m_Height; } + set { m_Height = value; } + } + + private int m_RowSpan = 1; + /// + /// ȡñпԽ + /// + public int RowSpan + { + get + { + return this.m_RowSpan; + } + set + { + m_RowSpan = value; + } + } + + + public TableRow() + { + TableCells = new TableCellCollection(); + } + public TableRow(float height) + { + TableCells = new TableCellCollection(); + this.Height = height; + } + + public void AddCell(string Text,int ColumnSpan,int RowSpan) + { + TableCell cell = new TableCell(); + cell.Text = Text; + cell.ColumnSpan = ColumnSpan; + cell.RowSpan = RowSpan; + this.Cells.Add(cell); + } + + + public TableCellCollection Cells + { + get + { + return TableCells; + } + } + } + #endregion + #region еĵԪ + /// + /// еĵԪ + /// + [Serializable] + public class TableCell + { + private float m_Width; + private float m_Height; + private Single m_BorderWidth; + private int m_ColumnSpan; + private Font m_Font; + private int m_RowSpan; + private string m_Text; + private StringFormatFlags m_FormatFlags; + /// + /// ıʾʽ + /// + public StringFormatFlags FormatFlags + { + get { return m_FormatFlags; } + set { m_FormatFlags = value; } + } + + private StringAlignment m_LineAlignment; + /// + /// ж뷽ʽ + /// + public StringAlignment LineAlignment + { + get { return m_LineAlignment; } + set { m_LineAlignment = value; } + } + + private StringAlignment m_Alignment; + /// + /// ı뷽ʽ + /// + public StringAlignment Alignment + { + get { return m_Alignment; } + set { m_Alignment = value; } + } + + + + public TableCell() + { + this.LineAlignment = StringAlignment.Center; + this.Alignment = StringAlignment.Center; + this.FormatFlags = StringFormatFlags.DisplayFormatControl; + //this.Font = new System.Drawing.Font("", 3, System.Drawing.FontStyle.Regular,GraphicsUnit.Millimeter); + Width = 30; + BorderWidth = Convert.ToSingle(0.1); + ColumnSpan = 1; + RowSpan = 1; + Text = " "; + } + public TableCell(string Text) + { + this.LineAlignment = StringAlignment.Center; + this.Alignment = StringAlignment.Center; + this.FormatFlags = StringFormatFlags.DisplayFormatControl; + //this.Font = new System.Drawing.Font("", 3, System.Drawing.FontStyle.Regular,GraphicsUnit.Millimeter); + Width = 30; + BorderWidth = Convert.ToSingle(0.1); + ColumnSpan = 1; + RowSpan = 1; + this.Text = Text; + } + + + + /// + /// + /// + public float Width + { + get + { + return this.m_Width; + } + set + { + m_Width = value; + } + } + + /// + /// ߶ + /// + public float Height + { + get + { + return this.m_Height; + } + set + { + m_Height = value; + } + } + + /// + /// ߿ + /// + public float BorderWidth + { + get + { + return this.m_BorderWidth; + } + set + { + m_BorderWidth = value; + } + } + + /// + /// ȡõԪԽ + /// + public int ColumnSpan + { + get + { + return this.m_ColumnSpan; + } + set + { + m_ColumnSpan = value; + } + } + + /// + /// Ԫݵ + /// + public Font Font + { + get + { + return this.m_Font; + } + set + { + m_Font = value; + } + } + + /// + /// ȡ еԪԽ + /// + public int RowSpan + { + get + { + return this.m_RowSpan; + } + set + { + m_RowSpan = value; + } + } + + /// + /// Ҫʾı + /// + public string Text + { + get + { + return this.m_Text; + } + set + { + m_Text = value; + } + } + + private bool m_Visible = true; + public bool Visible + { + get + { + return this.m_Visible; + } + set + { + m_Visible = value; + } + } + + private bool m_VisibleState = true; + /// + /// trueΪ,falseΪ + /// + public bool VisibleState + { + get + { + return this.m_VisibleState; + } + set + { + m_VisibleState = value; + } + } + + + + + } + #endregion + #region еĵԪ񼯺 + /// + /// Ԫ񼯺 + /// + [Serializable] + public sealed class TableCellCollection + { + private ArrayList Controls; + + + public TableCellCollection() + { + Controls = new ArrayList(); + } + + + #region IList Ա + + public int IndexOf(TableCell item) + { + return Controls.IndexOf(item); + } + + public void Insert(int index, TableCell item) + { + Controls.Insert(index, item); + } + + public TableCell this[int index] + { + get + { + return (TableCell)this.Controls[index]; + } + set + { + this.Controls[index] = value; + } + } + + #endregion + + #region ICollection Ա + public bool Contains(TableCell item) + { + return Controls.Contains(item); + } + + public void CopyTo(TableCell[] array, int arrayIndex) + { + Controls.CopyTo(array, arrayIndex); + } + + public int Count + { + get { return Controls.Count; } + set { int a = value; } + } + + public bool IsReadOnly + { + get { return false; } + } + + public void Remove(TableCell item) + { + Controls.Remove(item); + } + + #endregion + + + + #region IEnumerable Ա + + public System.Collections.IEnumerator GetEnumerator() + { + return Controls.GetEnumerator(); + } + + #endregion + + #region IList Ա + + + public void RemoveAt(int index) + { + Controls.RemoveAt(index); ; + } + + #endregion + + #region ICollection Ա + + + public void Clear() + { + Controls.Clear(); + } + + #endregion + + public void Add(TableCell cell) + { + Controls.Add(cell); + } + public void Add(object item) + { + Controls.Add(item); + } + + } + #endregion + #region м + /// + /// м + /// + [Serializable] + public class TableRowCollection + { + private ArrayList Controls; + + + public TableRowCollection() + { + Controls = new ArrayList(); + } + + + #region IList Ա + + public int IndexOf(TableRow item) + { + return Controls.IndexOf(item); + } + + public void Insert(int index, TableRow item) + { + Controls.Insert(index, item); + } + + public void RemoveAt(int index) + { + Controls.RemoveAt(index); + } + + public TableRow this[int index] + { + get + { + return (TableRow)Controls[index]; + } + set + { + Controls[index] = value; + } + } + + #endregion + + #region ICollection Ա + + public void Add(TableRow item) + { + Controls.Add(item); + } + public void Add(TableRow item, Font font) + { + item.Height = MeasureString("Ը߶", font).Height; + Controls.Add(item); + } + + public bool Contains(TableRow item) + { + return Controls.Contains(item); + } + + public void CopyTo(TableRow[] array, int arrayIndex) + { + Controls.CopyTo(array, arrayIndex); + } + + public int Count + { + get { return Controls.Count; } + set { int a = value; } + } + + + public bool IsReadOnly + { + get { return false; } + } + + public void Remove(TableRow item) + { + Controls.Remove(item); + } + + #endregion + + #region IEnumerable Ա + + public System.Collections.IEnumerator GetEnumerator() + { + return Controls.GetEnumerator(); + } + + #endregion + + #region ICollection Ա + + + public void Clear() + { + Controls.Clear(); + } + #endregion + + private SizeF MeasureString(string Text, Font font) + { + Bitmap bmp = new Bitmap(100, 100); + Graphics g = Graphics.FromImage(bmp); + g.PageUnit = font.Unit; + SizeF s = g.MeasureString(Text, font); + return s; + } + + } + #endregion + #region м + /// + /// м + /// + [Serializable] + public class TableColumnCollection + { + private ArrayList Controls; + + public TableColumnCollection() + { + Controls = new ArrayList(); + } + + #region IList Ա + + public int IndexOf(TableColumn item) + { + return Controls.IndexOf(item); + } + + public void Insert(int index, TableColumn item) + { + Controls.Insert(index, item); + } + + public void RemoveAt(int index) + { + Controls.RemoveAt(index); + } + + public TableColumn this[int index] + { + get + { + return (TableColumn)Controls[index]; + } + set + { + Controls[index] = value; + } + } + + #endregion + + #region ICollection Ա + + public bool Contains(TableColumn item) + { + return Controls.Contains(item); + } + public bool Contains(string Name) + { + foreach (TableColumn col in this.Controls) + { + if (col.Name == Name) return true; + } + return false; + } + public void CopyTo(TableColumn[] array, int arrayIndex) + { + Controls.CopyTo(array, arrayIndex); + } + + public int Count + { + get { return Controls.Count; } + set { int a = value; } + } + + public bool IsReadOnly + { + get { return false; } + } + + public void Remove(TableColumn item) + { + Controls.Remove(item); + } + + public TableColumn GetTableColumn(string Name) + { + TableColumn col = null; + foreach (TableColumn item in Controls) + { + if (item.Name == Name) { col = item;break; } + } + return col; + } + + #endregion + + public System.Collections.IEnumerator GetEnumerator() + { + return Controls.GetEnumerator(); + } + + public void Clear() + { + Controls.Clear(); + } + public void Add(TableColumn item) + { + Controls.Add(item); + } + public void Add(string Name, string Caption, float MinWidth) + { + TableColumn col = new TableColumn(); + col.MinWidth = MinWidth; + col.Caption = Caption; + col.Name = Name; + col.DataType = DbType.String; + col.Format = ""; + Controls.Add(col); + } + public void Add(string Name, string Caption, float MinWidth, StringFormat sf) + { + TableColumn col = new TableColumn(); + col.MinWidth = MinWidth; + col.Caption = Caption; + col.Name = Name; + col.DataType = DbType.String; + col.Format = ""; + col.StringFormat = sf; + Controls.Add(col); + } + + public void Add(string Name, string Caption, DbType DataType, string Format, StringFormat sf) + { + TableColumn col = new TableColumn(); + col.MinWidth = float.MaxValue; + col.Caption = Caption; + col.Name = Name; + col.DataType = DataType; + col.Format = Format; + col.StringFormat = sf; + Controls.Add(col); + } + public void Add(string Name, string Caption, DbType DataType, string Format) + { + TableColumn col = new TableColumn(); + col.MinWidth = float.MaxValue; + col.Caption = Caption; + col.Name = Name; + col.DataType = DataType; + col.Format = Format; + Controls.Add(col); + } + public void Add(string Name, string Caption, DbType DataType, string Format, float Width, StringFormat sf) + { + TableColumn col = new TableColumn(); + col.MinWidth = float.MaxValue; + col.Caption = Caption; + col.Name = Name; + col.DataType = DataType; + col.Format = Format; + col.Width = Width; + col.StringFormat = sf; + Controls.Add(col); + } + public void Add(string Name, string Caption, DbType DataType, string Format, float Width) + { + TableColumn col = new TableColumn(); + col.MinWidth = float.MaxValue; + col.Caption = Caption; + col.Name = Name; + col.DataType = DataType; + col.Format = Format; + col.Width = Width; + Controls.Add(col); + } + + public void Add(string Name, string Caption, DbType DataType, Dictionary Format) + { + TableColumn col = new TableColumn(); + col.MinWidth = float.MaxValue; + col.Caption = Caption; + col.Name = Name; + col.DataType = DataType; + col.Format = ""; + col.KeyValueFormat = Format; + Controls.Add(col); + } + + public void Add(string Name, string Caption, DbType DataType, Func Format) + { + TableColumn col = new TableColumn(); + col.MinWidth = float.MaxValue; + col.Caption = Caption; + col.Name = Name; + col.DataType = DataType; + col.CellFormatter = Format; + Controls.Add(col); + } + + + } + #endregion + #region + /// + /// + /// + [Serializable] + public class Table + { + private TableRowCollection TableRows; + private TableColumnCollection TableColumns; + private float m_Width; + public float Width + { + get { return m_Width; } + set { m_Width = value; } + } + private float m_Height; + public float Height + { + get { return m_Height; } + set { m_Height = value; } + } + private bool m_ShowLine = true; + /// + /// Ƿʾ + /// + public bool ShowLine + { + get { return m_ShowLine; } + set { m_ShowLine = value; } + } + private Font m_Font; + public Font Font + { + get + { + return this.m_Font; + } + set + { + m_Font = value; + } + } + + public Table() + { + TableRows = new TableRowCollection(); + TableColumns = new TableColumnCollection(); + } + + public TableRowCollection Rows + { + get + { + return this.TableRows; + } + } + + + public TableColumnCollection Columns + { + get + { + return this.TableColumns; + } + } + + public TableRow NewRow() + { + TableRow row = new TableRow(); + TableCell cell = null; + for (int i = 0; i < this.Columns.Count; i++) + { + cell = new TableCell(); + cell.Width = this.Columns[i].Width; + cell.Alignment = this.Columns[i].StringFormat.Alignment; + cell.FormatFlags = this.Columns[i].StringFormat.FormatFlags; + cell.LineAlignment = this.Columns[i].StringFormat.LineAlignment; + row.Cells.Add(cell); + } + row.Height = this.MeasureString("Կ:", this.Font).Height; + return row; + } + public TableRow NewRow(StringAlignment TextAlignment) + { + TableRow row = new TableRow(); + TableCell cell = null; + for (int i = 0; i < this.Columns.Count; i++) + { + cell = new TableCell(); + cell.Width = this.Columns[i].Width; + cell.Alignment = TextAlignment; + row.Cells.Add(cell); + } + row.Height = this.MeasureString("Կ:", this.Font).Height; + return row; + } + public TableRow NewRow(string[] list) + { + TableRow row = new TableRow(); + TableCell cell = null; + for (int i = 0; i < this.Columns.Count; i++) + { + cell = new TableCell(); + cell.Width = this.Columns[i].Width; + cell.Alignment = this.Columns[i].StringFormat.Alignment; + cell.FormatFlags = this.Columns[i].StringFormat.FormatFlags; + cell.LineAlignment = this.Columns[i].StringFormat.LineAlignment; + if (i < list.Length) cell.Text = list[i]; + row.Cells.Add(cell); + } + row.Height = this.MeasureString("Կ:", this.Font).Height; + return row; + } + public TableRow NewRow(string[] list, StringAlignment TextAlignment) + { + TableRow row = new TableRow(); + TableCell cell = null; + for (int i = 0; i < this.Columns.Count; i++) + { + cell = new TableCell(); + cell.Width = this.Columns[i].Width; + if (i < list.Length) cell.Text = list[i]; + cell.Alignment = TextAlignment; + row.Cells.Add(cell); + } + row.Height = this.MeasureString("Կ:", this.Font).Height; + return row; + } + + private SizeF MeasureString(string Text, Font font) + { + Bitmap bmp = new Bitmap(100, 100); + Graphics g = Graphics.FromImage(bmp); + g.PageUnit = GraphicsUnit.Millimeter; + SizeF s = g.MeasureString(Text, font); + return s; + } + + + public void SetFont(Font font) + { + foreach (TableRow row in this.Rows) + { + foreach (TableCell cell in row.Cells) + { + cell.Font = font; + } + } + } + + } + #endregion + #region ߶ + /// + /// ߶ + /// + [Serializable] + public class Line + { + private float m_BrushWidth = 0.1F; + /// + /// ϸ + /// + public float BrushWidth + { + get { return m_BrushWidth; } + set { m_BrushWidth = value; } + } + private PointF m_Pt1; + + public PointF Pt1 + { + get { return m_Pt1; } + set { m_Pt1 = value; } + } + private PointF m_Pt2; + + public PointF Pt2 + { + get { return m_Pt2; } + set { m_Pt2 = value; } + } + + public Line() { } + public Line(PointF pt1, PointF pt2) + { + this.m_Pt1 = pt1; + this.m_Pt2 = pt2; + } + } + #endregion + #region ߵļ + [Serializable] + public class Lines + { + + private ArrayList Controls; + + public int Count + { + get + { + return this.Controls.Count; + } + set { int a = value; } + } + + public Lines() + { + Controls = new ArrayList(); + } + + #region IList Ա + + public int IndexOf(Line item) + { + return Controls.IndexOf(item); + } + + public void Insert(int index, Line item) + { + Controls.Insert(index, item); + } + + public void RemoveAt(int index) + { + Controls.RemoveAt(index); + } + + public Line this[int index] + { + get + { + return (Line)Controls[index]; + } + set + { + Controls[index] = value; + } + } + + #endregion + + #region ICollection Ա + + public void Add(Line item) + { + Controls.Add(item); + } + + public bool Contains(Line item) + { + return Controls.Contains(item); + } + + public void CopyTo(Line[] array, int arrayIndex) + { + Controls.CopyTo(array, arrayIndex); + } + + public void Clear() + { + Controls.Clear(); + } + + public bool IsReadOnly + { + get { return false; } + } + + public void Remove(Line item) + { + Controls.Remove(item); + } + + #endregion + + #region IEnumerable Ա + public System.Collections.IEnumerator GetEnumerator() + { + return Controls.GetEnumerator(); + } + #endregion + } + #endregion + #region ζ + /// + /// ζ + /// + [Serializable] + public class Rectangle + { + private float m_BrushWidth = 0.1F; + /// + /// ϸ + /// + public float BrushWidth + { + get { return m_BrushWidth; } + set { m_BrushWidth = value; } + } + private float m_x; + public float X + { + get { return m_x; } + set { m_x = value; } + } + private float m_y; + public float Y + { + get { return m_y; } + set { m_y = value; } + } + private float m_Width; + public float Width + { + get { return m_Width; } + set { m_Width = value; } + } + private float m_Height; + public float Height + { + get { return m_Height; } + set { m_Height = value; } + } + + public Rectangle() + { + + } + + public Rectangle(float x, float y, float width, float height) + { + this.m_x = x; + this.m_y = y; + this.Width = width; + this.Height = height; + } + } + #endregion + #region εļ + [Serializable] + public class Rectangles + { + + private ArrayList Controls; + + public int Count + { + get + { + return this.Controls.Count; + } + set { int a = value; } + } + + public Rectangles() + { + Controls = new ArrayList(); + } + + #region IList Ա + + public int IndexOf(Rectangle item) + { + return Controls.IndexOf(item); + } + + public void Insert(int index, Rectangle item) + { + Controls.Insert(index, item); + } + + public void RemoveAt(int index) + { + Controls.RemoveAt(index); + } + + public Rectangle this[int index] + { + get + { + return (Rectangle)Controls[index]; + } + set + { + Controls[index] = value; + } + } + + #endregion + + #region ICollection Ա + + public void Add(Rectangle item) + { + Controls.Add(item); + } + + public bool Contains(Rectangle item) + { + return Controls.Contains(item); + } + + public void CopyTo(Rectangle[] array, int arrayIndex) + { + Controls.CopyTo(array, arrayIndex); + } + + public void Clear() + { + Controls.Clear(); + } + + public bool IsReadOnly + { + get { return false; } + } + + public void Remove(Rectangle item) + { + Controls.Remove(item); + } + + #endregion + + #region IEnumerable Ա + public System.Collections.IEnumerator GetEnumerator() + { + return Controls.GetEnumerator(); + } + #endregion + } + #endregion + #region ֽ + /// + /// ֽ + /// + public class Kind + { + private string m_Name; + /// + /// ֽ + /// + public string Name + { + get { return m_Name; } + set { m_Name = value; } + } + + private int m_Width; + /// + /// + /// + public int Width + { + get { return m_Width; } + set { m_Width = value; } + } + + private int m_Height; + /// + /// ߶ + /// + public int Height + { + get + { + return this.m_Height; + } + set + { + m_Height = value; + } + } + private KindType m_KindType; + /// + /// ֽ + /// + public KindType KindType + { + get + { + return this.m_KindType; + } + set + { + m_KindType = value; + } + } + private bool m_Landscape; + /// + /// Ǻ,Ĭfalsetrue + /// + public bool Landscape + { + get { return this.m_Landscape; } + set { m_Landscape = value; } + } + + public Kind() + { + + } + + public Kind(KindType kind, bool landscape) + { + this.Landscape = landscape; + KindType = kind; + switch (kind) + { + case KindType.A3: + this.Name = "A3"; + this.Width = 297; + this.Height = 420; + break; + case KindType.A4: + this.Name = "A4"; + this.Width = 210; + this.Height = 297; + break; + case KindType.A5: + this.Name = "A5"; + this.Width = 148; + this.Height = 210; + break; + case KindType.B4: + this.Name = "B4"; + this.Width = 250; + this.Height = 353; + break; + case KindType.B5: + this.Name = "B5"; + this.Width = 176; + this.Height = 250; + break; + case KindType.Cascade2: + this.Name = "1/2"; + this.Width = 210; + this.Height = 139; + break; + case KindType.Cascade3: + this.Name = "1/3"; + this.Width = 210; + this.Height = 93; + break; + case KindType.Cascade4: + this.Name = "1/4"; + this.Width = 210; + this.Height = 69; + break; + default: + this.Width = 0; + this.Height = 0; + break; + } + + } + public Kind(string Name, int width, int height, bool landscape) + { + this.Name = Name; + this.Width = width; + this.Height = height; + this.KindType = KindType.Custom; + this.Landscape = landscape; + } + public Kind(int width, int height, bool landscape) + { + this.Name = "ԶС"; + this.Width = width; + this.Height = height; + this.KindType = KindType.Custom; + this.Landscape = landscape; + } + + + } + #endregion + #region ӡֽ֧ + /// + /// ӡֽ֧ + /// + public class Kinds + { + private ArrayList Controls; + + public int Count + { + get + { + return this.Controls.Count; + } + } + + public Kinds() + { + Controls = new ArrayList(); + } + + #region IList Ա + + public int IndexOf(Kind item) + { + return Controls.IndexOf(item); + } + + public void Insert(int index, Kind item) + { + Controls.Insert(index, item); + } + + public void RemoveAt(int index) + { + Controls.RemoveAt(index); + } + + public Kind this[int index] + { + get + { + return (Kind)Controls[index]; + } + set + { + Controls[index] = value; + } + } + + #endregion + + #region ICollection Ա + + public void Add(Kind item) + { + Controls.Add(item); + } + + public bool Contains(Kind item) + { + return Controls.Contains(item); + } + + public void CopyTo(Kind[] array, int arrayIndex) + { + Controls.CopyTo(array, arrayIndex); + } + + public void Clear() + { + Controls.Clear(); + } + + public bool IsReadOnly + { + get { return false; } + } + + public void Remove(Kind item) + { + Controls.Remove(item); + } + + #endregion + + #region IEnumerable Ա + public System.Collections.IEnumerator GetEnumerator() + { + return Controls.GetEnumerator(); + } + #endregion + + + } + #endregion + #region ֽ + public enum KindType + { + /// + /// 297*420 + /// + A3 = 0, + /// + /// 210*297 + /// + A4 = 1, + /// + /// 148*210 + /// + A5 = 2, + /// + /// 250*353 + /// + B4 = 3, + /// + /// 176*250 + /// + B5 = 4, + /// + /// 1/2(139*210) + /// + Cascade2 = 5, + /// + /// 1/3(93*210) + /// + Cascade3 = 6, + /// + /// 1/4(69*210) + /// + Cascade4 = 7, + /// + /// Զ + /// + Custom = 8 + } + #endregion + #region ҳƷʽ + public enum PageLayoutType + { + /// + /// Ĭ + /// + GridLayout = 0, + /// + /// ģʽ(϶) + /// + FlowLayout = 1, + } + #endregion + #region ͼƬ + public class ImageObject + { + private int m_Height; + /// + /// ߶(ԺΪλ) + /// + public int Height + { + get { return m_Height; } + set { m_Height = value; } + } + private int m_Width; + /// + /// (ԺΪλ) + /// + public int Width + { + get { return m_Width; } + set { m_Width = value; } + } + private int m_Top; + /// + /// (ԺΪλ) + /// + public int Top + { + get { return m_Top; } + set { m_Top = value; } + } + private int m_Left; + /// + /// (ԺΪλ) + /// + public int Left + { + get { return m_Left; } + set { m_Left = value; } + } + + + private byte[] m_MemoryByte; + /// + /// ͼƬ + /// + public byte[] MemoryByte + { + get { return m_MemoryByte; } + set { m_MemoryByte = value; } + } + + + private bool m_IsZoom; + /// + /// Ƿ + /// + public bool IsZoom + { + get { return m_IsZoom; } + set { m_IsZoom = value; } + } + + /// + /// ͼƬ + /// + public Image MemoryImage + { + get + { + if (MemoryByte == null) return null; + MemoryStream ms = new MemoryStream(); + ms.Write(MemoryByte, 0, MemoryByte.Length); + Image img = Image.FromStream(ms); + ms.Close(); + return img; + } + } + public ImageObject(string imagePath, int left, int top) + { + if (File.Exists(imagePath) == false) throw new Exception("ļ"); + this.MemoryByte = GetPhoto(imagePath); + this.Left = left; + this.Top = top; + this.Width = 0; + this.Height = 0; + this.IsZoom = false; + } + public ImageObject(string imagePath, int left, int top, int width, int height) + { + if (File.Exists(imagePath) == false) throw new Exception("ļ"); + this.MemoryByte = GetPhoto(imagePath); + this.Left = left; + this.Top = top; + this.Width = width; + this.Height = height; + this.IsZoom = true; + } + public ImageObject() + { + + } + private byte[] GetPhoto(string filePath) + { + Bitmap bmp = new Bitmap(filePath); + MemoryStream ms = new MemoryStream(); + bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); + bmp.Dispose(); + byte[] photo = new byte[ms.Length - 1]; + ms.Position = 0; + ms.Read(photo, 0, photo.Length - 1); + ms.Close(); + return photo; + } + + public void Zoom() + { + //Image.GetThumbnailImageAbort myCallback = new Image.GetThumbnailImageAbort(ThumbnailCallback); + //Image myThumbnail = MemoryImage.GetThumbnailImage(Width, Height, myCallback, IntPtr.Zero); + //MemoryByte = GetPhoto(myThumbnail); + //myThumbnail.Dispose(); + //MemoryImage.Dispose(); + + System.Drawing.Image initImage = CustomIO.GetPhoto(MemoryByte); + //ͼ + System.Drawing.Image resultImage = new System.Drawing.Bitmap(Width, Height); + System.Drawing.Graphics resultG = System.Drawing.Graphics.FromImage(resultImage); + // + resultG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; + resultG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; + //ָɫջ + resultG.Clear(Color.White); + //ͼ + resultG.DrawImage(initImage, new System.Drawing.Rectangle(0, 0, Width, Height), new System.Drawing.Rectangle(0, 0, initImage.Width, initImage.Height), System.Drawing.GraphicsUnit.Pixel); + MemoryByte = GetPhoto(resultImage); + //ͷͼԴ + resultG.Dispose(); + resultImage.Dispose(); + + //ͷԭʼͼƬԴ + initImage.Dispose(); + } + + bool ThumbnailCallback() + { + return false; + } + + #region ͼƬתbate,MemoryStreamʾ + public byte[] GetPhoto(System.Drawing.Image img) + { + Bitmap bmp = new Bitmap(img); + MemoryStream ms = new MemoryStream(); + bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); + bmp.Dispose(); + byte[] photo = new byte[ms.Length - 1]; + ms.Position = 0; + ms.Read(photo, 0, photo.Length - 1); + ms.Close(); + return photo; + } + #endregion + + } + #endregion + #region ͼƬļ + [Serializable] + public class ImageObjects + { + + private ArrayList Controls; + + public int Count + { + get + { + return this.Controls.Count; + } + set { int a = value; } + } + + public ImageObjects() + { + Controls = new ArrayList(); + } + + #region IList Ա + + public int IndexOf(ImageObject item) + { + return Controls.IndexOf(item); + } + + public void Insert(int index, ImageObject item) + { + Controls.Insert(index, item); + } + + public void RemoveAt(int index) + { + Controls.RemoveAt(index); + } + + public ImageObject this[int index] + { + get + { + return (ImageObject)Controls[index]; + } + set + { + Controls[index] = value; + } + } + + #endregion + + #region ICollection Ա + + public void Add(ImageObject item) + { + Controls.Add(item); + } + + public bool Contains(ImageObject item) + { + return Controls.Contains(item); + } + + public void CopyTo(ImageObject[] array, int arrayIndex) + { + Controls.CopyTo(array, arrayIndex); + } + + public void Clear() + { + Controls.Clear(); + } + + public bool IsReadOnly + { + get { return false; } + } + + public void Remove(ImageObject item) + { + Controls.Remove(item); + } + + #endregion + + #region IEnumerable Ա + public System.Collections.IEnumerator GetEnumerator() + { + return Controls.GetEnumerator(); + } + #endregion + } + #endregion + #region ĵ + public class ReportDocument + { + private int m_ID; + /// + /// ID + /// + public virtual int ID + { + get { return m_ID; } + set { m_ID = value; } + } + private string m_Name = "Ĭĵ"; + /// + /// ĵ + /// + public virtual string Name + { + get { return m_Name; } + set { m_Name = value; } + } + private string m_FileName; + /// + /// ļ+· + /// + public virtual string FileName + { + get { return m_FileName; } + set { m_FileName = value; } + } + private int m_State; + /// + /// ӡ״̬(1δӡ2ڴӡ3Ѵӡ) + /// + public virtual int State + { + get { return m_State; } + set { m_State = value; } + } + private string m_GuID; + /// + /// Ψһ + /// + public virtual string GuID + { + get { return m_GuID; } + set { m_GuID = value; } + } + private int m_Copies = 1; + /// + /// ӡ + /// + public int Copies + { + get { return m_Copies; } + set { m_Copies = value; } + } + private int m_CopiesCount = 1; + /// + /// ӡ + /// + public int CopiesCount + { + get { return m_CopiesCount; } + set { m_CopiesCount = value; } + } + private int m_CurrentCopies; + /// + /// ǰӡ + /// + public int CurrentCopies + { + get { return m_CurrentCopies; } + set { m_CurrentCopies = value; } + } + private PrintReport m_PrReport; + /// + /// ӡ + /// + public PrintReport PrReport + { + get { return m_PrReport; } + set { m_PrReport = value; } + } + + private string m_Url; + /// + /// webSericeַ + /// + public virtual string Url + { + get { return m_Url; } + set { m_Url = value; } + } + + public ReportDocument() + { } + + public ReportDocument(int id, string Name, string FileName, int Copies) + { + this.ID = id; + this.Name = Name; + this.FileName = FileName; + this.Copies = Copies; + this.GuID = Guid.NewGuid().ToString(); + } + } + #endregion + #region ĵļ + [Serializable] + public class ReportDocuments + { + + private ArrayList Controls; + + public int Count + { + get { return this.Controls.Count; } + set { int a = value; } + } + + public ReportDocuments() + { + Controls = new ArrayList(); + } + + #region ύӡĵ + public void RetuenReportDocuments(DataSet ds) + { + ReportDocument doc = null; + foreach (DataRow row in ds.Tables[0].Rows) + { + doc = new ReportDocument(); + doc.Copies = Convert.ToInt16(row["Copies"]); + doc.CopiesCount = Convert.ToInt16(row["Copies"]); + doc.CurrentCopies = 0; + doc.GuID = Convert.ToString(row["GuID"]); + doc.ID = Convert.ToInt32(row["ID"]); + doc.Name = Convert.ToString(row["Name"]); + doc.State = Convert.ToInt32(row["State"]); + doc.FileName = Convert.ToString(row["FileName"]); + doc.Url = Convert.ToString(row["Url"]); + this.Add(doc); + } + } + #endregion + #region ȡӡ״̬ + /// + /// شӡ״̬ + /// + /// + /// + public static ReportDocument GetPrintState(int id) + { + string filePath = System.AppDomain.CurrentDomain.BaseDirectory + "ReportFile/PrintState.xml"; + if (System.IO.File.Exists(filePath) == false) return null; + DataSet ds = new DataSet(); + ds.ReadXml(filePath, XmlReadMode.ReadSchema); + DataRow[] drow = ds.Tables[0].Select("id=" + id.ToString()); + if (drow.Length == 0) return null; + ReportDocument doc = new ReportDocument(); + doc.Copies = Convert.ToInt16(drow[0]["Copies"]); + doc.CopiesCount = Convert.ToInt16(drow[0]["CopiesCount"]); + doc.CurrentCopies = Convert.ToInt16(drow[0]["CurrentCopies"]); + doc.GuID = Convert.ToString(drow[0]["GuID"]); + doc.ID = Convert.ToInt32(drow[0]["ID"]); + doc.Name = Convert.ToString(drow[0]["Name"]); + doc.State = Convert.ToInt32(drow[0]["State"]); + return doc; + } + #endregion + + #region IList Ա + + public int IndexOf(ReportDocument item) + { + return Controls.IndexOf(item); + } + + public void Insert(int index, ReportDocument item) + { + Controls.Insert(index, item); + } + + public void RemoveAt(int index) + { + Controls.RemoveAt(index); + } + + public ReportDocument this[int index] + { + get + { + return (ReportDocument)Controls[index]; + } + set + { + Controls[index] = value; + } + } + + #endregion + + #region ICollection Ա + + public void Add(ReportDocument item) + { + Controls.Add(item); + } + + public bool Contains(ReportDocument item) + { + return Controls.Contains(item); + } + + public void CopyTo(ReportDocument[] array, int arrayIndex) + { + Controls.CopyTo(array, arrayIndex); + } + + public void Clear() + { + Controls.Clear(); + } + + public bool IsReadOnly + { + get { return false; } + } + + public void Remove(ReportDocument item) + { + Controls.Remove(item); + } + + #endregion + + #region IEnumerable Ա + public System.Collections.IEnumerator GetEnumerator() + { + return Controls.GetEnumerator(); + } + #endregion + } + #endregion + #region 껭ַ + public class StringObject + { + public string Name { get; set; } + public int Top { get; set; } + public int Left { get; set; } + public string Text { get; set; } + public Font Font { get; set; } + public bool Visible { get; set; } + public string FormatText { get; set; } + public string TextAlign { get; set; } + public float Width { get; set; } + public float Height { get; set; } + } + #endregion + #region 껭ַ + public class StringObjects : List + { + public StringObject this[string Name] + { + get + { + StringObject model = null; + foreach (var item in this) + { + if (item.Name == Name) model=item; + } + return model; + } + } + } + #endregion + +} \ No newline at end of file diff --git a/基础类库/HuizhongLibrary/Database.cs b/基础类库/HuizhongLibrary/Database.cs new file mode 100644 index 0000000..e76f264 --- /dev/null +++ b/基础类库/HuizhongLibrary/Database.cs @@ -0,0 +1,1885 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Data.OleDb; +using System.Data.SqlClient; +using System.Diagnostics; +using System.IO; +using System.Reflection; +using System.Text; +using HuizhongLibrary.Common.Configuration; +using HuizhongLibrary.Log; +//using Oracle.DataAccess.Client; +using Oracle.ManagedDataAccess.Client; +using MySql.Data.MySqlClient; + +namespace HuizhongLibrary.Data +{ + public class Database + { + public bool IsCheckKeyword = true; //检测SQL关键字 + + public string Namespace { get; set; } + private string m_ConnectionString; + + public string ConnectionString + { + get { return m_ConnectionString; } + set { m_ConnectionString = value; } + } + private DbProviderFactory m_Factory; + + public DbProviderFactory Factory + { + get { return m_Factory; } + set { m_Factory = value; } + } + private string m_DataBaseName = ""; + + private bool m_IsLastingConnect = false; + /// + /// 是否保持连接 + /// + public bool IsLastingConnect + { + get { return m_IsLastingConnect; } + set { m_IsLastingConnect = value; } + } + + private DbConnection cn = null; + + public string DataBaseName + { + get { return m_DataBaseName; } + set { m_DataBaseName = value; } + } + + public Database(string Namespace, string ConnectionString, DbProviderFactory factory) + { + this.Namespace = Namespace; + this.Factory = factory; + this.ConnectionString = ConnectionString; + } + + public Database(string ConnectionString) + { + this.Namespace = "System.Data.SqlClient"; + this.Factory = DbProviderFactories.GetFactory(this.Namespace); + this.ConnectionString = ConnectionString; + } + + public Database(string Namespace, string ConnectionString) + { + this.Namespace = Namespace; + if (string.IsNullOrEmpty(this.Namespace)) this.Namespace = "System.Data.SqlClient"; + if (this.Namespace == "Oracle.DataAccess.Client") + { + + } + else if (this.Namespace == "MySql.Data.MySqlClient") + { + + } + else + { + this.Factory = DbProviderFactories.GetFactory(this.Namespace); + } + this.ConnectionString = ConnectionString; + } + + #region 读取数据库设置 + public Dictionary GetConnectionInfo() + { + string[] sss = ConnectionString.Split(';'); + var ListModel = new Dictionary(); + foreach (string item in sss) + { + string[] ss = item.Split('='); + if (ss.Length < 2) continue; + if (ss[0] == "server") ListModel.Add("server", ss[1]); + if (ss[0] == "database") ListModel.Add("database", ss[1]); + if (ss[0] == "Integrated Security") + { + ListModel.Add("Integrated Security", "win"); + } + if (ss[0] == "uid") + { + ListModel.Add("Integrated Security", "sql"); + } + if (ss[0] == "pwd") ListModel.Add("PassWord", ss[1]); + } + return ListModel; + } + #endregion + + #region 释放内存 + public void Dispose(DbCommand command) + { + command.Parameters.Clear(); + command.Dispose(); + command = null; + Factory = null; + cn = null; + } + #endregion + + #region 返回条件参数化连接语句 + public string GetWhere(RefParameterCollection Param, CommandType CommandType) + { + string tsql = ""; + if (Param != null && Param.Count != 0) + { + if (CommandType == CommandType.Text) + { + foreach (RefParameter pam in Param) + { + if (pam.Direction != ParameterDirection.Input) continue; + if (pam.IsDeclare == false) continue; //不生成条件 + if (tsql.IndexOf("where") == -1) + { + switch (pam.Condition) + { + case "in": + tsql = tsql + " where " + pam.Name + " " + pam.Condition + " (@" + pam.Caption + "0"; + string[] chars1 = pam.Value.ToString().Split(new char[] { ',' }); + for (int i = 1; i < chars1.Length; i++) + { + tsql = tsql + " ,@" + pam.Caption + i.ToString(); + } + tsql = tsql + ")" + pam.EndString; + break; + case "not in": + tsql = tsql + " where " + pam.Name + " " + pam.Condition + " (@" + pam.Caption + "0"; + string[] chars2 = pam.Value.ToString().Split(new char[] { ',' }); + for (int i = 1; i < chars2.Length; i++) + { + tsql = tsql + " ,@" + pam.Caption + i.ToString(); + } + tsql = tsql + ")" + pam.EndString; + break; + case "like": + tsql = tsql + " where " + pam.Name + " like '%'+" + "@" + pam.Caption + "+'%'" + pam.EndString; + break; + case "like left": + tsql = tsql + " where " + pam.Name + " like '%'+" + "@" + pam.Caption + pam.EndString; + break; + case "like right": + tsql = tsql + " where " + pam.Name + " like " + "@" + pam.Caption + "+'%'" + pam.EndString; + break; + case "is": + tsql = tsql + " where " + pam.Name + " is null" + pam.EndString; + break; + case "is not": + tsql = tsql + " where " + pam.Name + " is not null" + pam.EndString; + break; + default: + if (pam.Type == DbType.String && Convert.ToString(pam.Value) == "") + { + tsql = tsql + " where " + pam.Name + pam.Condition + "''" + pam.EndString; + } + else if (pam.Value == null || pam.Value == DBNull.Value) + { + tsql = tsql + " where " + pam.Name + " is null" + pam.EndString; + } + else + { + tsql = tsql + " where " + pam.Name + pam.Condition + "@" + pam.Caption + pam.EndString; + } + break; + } + + } + else + { + switch (pam.Condition) + { + case "in": + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " " + pam.Condition + " (@" + pam.Caption + "0"; + string[] chars3 = pam.Value.ToString().Split(new char[] { ',' }); + for (int i = 1; i < chars3.Length; i++) + { + tsql = tsql + " ,@" + pam.Caption + i.ToString(); + } + tsql = tsql + ")" + pam.EndString; + break; + case "not in": + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " " + pam.Condition + " (@" + pam.Caption + "0"; + string[] chars4 = pam.Value.ToString().Split(new char[] { ',' }); + for (int i = 1; i < chars4.Length; i++) + { + tsql = tsql + " ,@" + pam.Caption + i.ToString(); + } + tsql = tsql + ")" + pam.EndString; + break; + case "like": + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " like '%'+" + "@" + pam.Caption + "+'%'" + pam.EndString; + break; + case "like left": + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " like '%'+" + "@" + pam.Caption + pam.EndString; + break; + case "like right": + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " like " + "@" + pam.Caption + "+'%'" + pam.EndString; + break; + case "is": + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " is null" + pam.EndString; + break; + case "is not": + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " is not null" + pam.EndString; + break; + default: + if (pam.Type == DbType.String && Convert.ToString(pam.Value) == "") + { + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + pam.Condition + "''" + pam.EndString; + } + else if (pam.Value == null || pam.Value == DBNull.Value) + { + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " is null" + pam.EndString; + } + else + { + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + pam.Condition + "@" + pam.Caption + pam.EndString; + } + break; + } + } + } + } + else + { + + foreach (RefParameter pam in Param) + { + if (pam.Direction != ParameterDirection.Input) continue; + if (pam.IsDeclare == false) continue; //不生成条件 + if (tsql.IndexOf("where") == -1) + { + switch (pam.Condition) + { + case "in": + if (pam.Type != DbType.String) + { + tsql = tsql + " where " + pam.Name + " in (" + pam.Value.ToString() + ")" + pam.EndString; + } + else + { + string[] chars1 = pam.Value.ToString().Split(new char[] { ',' }); + string ss = ""; + foreach (string s in chars1) + { + if (ss == "") { ss = "'" + s + "'"; } + else { ss = ss + ",'" + s + "'"; } + } + + tsql = tsql + " where " + pam.Name + " in (" + ss + ")" + pam.EndString; + } + break; + case "not in": + if (pam.Type != DbType.String) + { + tsql = tsql + " where " + pam.Name + " not in (" + pam.Value.ToString() + ")" + pam.EndString; + } + else + { + string[] chars2 = pam.Value.ToString().Split(new char[] { ',' }); + string ss = ""; + foreach (string s in chars2) + { + if (ss == "") { ss = "'" + s + "'"; } + else { ss = ss + ",'" + s + "'"; } + } + + tsql = tsql + " where " + pam.Name + " not in (" + ss + ")" + pam.EndString; + } + break; + case "like": + tsql = tsql + " where " + pam.Name + " like '%" + pam.Value.ToString() + "%'" + pam.EndString; + break; + case "like left": + tsql = tsql + " where " + pam.Name + " like '%" + pam.Value.ToString() + "'" + pam.EndString; + break; + case "like right": + tsql = tsql + " where " + pam.Name + " like '" + pam.Value.ToString() + "%'" + pam.EndString; + break; + case "is": + tsql = tsql + " where " + pam.Name + " is null" + pam.EndString; + break; + case "is not": + tsql = tsql + " where " + pam.Name + " is not null" + pam.EndString; + break; + default: + + if (pam.Type == DbType.String && Convert.ToString(pam.Value) == "") + { + tsql = " where " + pam.Name + pam.Condition + "''" + pam.EndString; + } + else if (pam.Value == null || pam.Value == DBNull.Value) + { + tsql = " where " + pam.Name + " is null" + pam.EndString; + } + else if (pam.Type == DbType.String || pam.Type == DbType.DateTime) + { + tsql = " where " + pam.Name + pam.Condition + "'" + pam.Value.ToString() + "'" + pam.EndString; + } + else + { + tsql = " where " + pam.Name + pam.Condition + pam.Value.ToString() + pam.EndString; + } + break; + } + + } + else + { + switch (pam.Condition) + { + case "in": + if (pam.Type != DbType.String) + { + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " in (" + pam.Value.ToString() + ")" + pam.EndString; + } + else + { + string[] chars3 = pam.Value.ToString().Split(new char[] { ',' }); + string ss = ""; + foreach (string s in chars3) + { + if (ss == "") { ss = "'" + s + "'"; } + else { ss = ss + ",'" + s + "'"; } + } + + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " in (" + ss + ")" + pam.EndString; + } + break; + case "not in": + if (pam.Type != DbType.String) + { + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " not in (" + pam.Value.ToString() + ")" + pam.EndString; + } + else + { + string[] chars4 = pam.Value.ToString().Split(new char[] { ',' }); + string ss = ""; + foreach (string s in chars4) + { + if (ss == "") { ss = "'" + s + "'"; } + else { ss = ss + ",'" + s + "'"; } + } + + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " not in (" + ss + ")" + pam.EndString; + } + break; + case "like": + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " like '%" + pam.Value.ToString() + "%'" + pam.EndString; + break; + case "like left": + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " like '%" + pam.Value.ToString() + "'" + pam.EndString; + break; + case "like right": + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " like '" + pam.Value.ToString() + "%'" + pam.EndString; + break; + case "is": + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " is null" + pam.EndString; + break; + case "is not": + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " is not null" + pam.EndString; + break; + default: + if (pam.Type == DbType.String && Convert.ToString(pam.Value) == "") + { + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + pam.Condition + "''" + pam.EndString; + } + else if (pam.Value == null || pam.Value == DBNull.Value) + { + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " is null" + pam.EndString; + } + else if (pam.Type == DbType.String || pam.Type == DbType.DateTime) + { + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + pam.Condition + "'" + pam.Value.ToString() + "'" + pam.EndString; + } + else + { + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + pam.Condition + pam.Value.ToString() + pam.EndString; + } + + break; + } + } + } + } + } + return tsql; + } + #endregion + + #region 创建Connection对象 + public DbConnection CreateConnection() + { + if (cn != null) return cn; + if (this.Namespace == "Oracle.DataAccess.Client") + { + cn = new OracleConnection(); + } + else if (this.Namespace == "MySql.Data.MySqlClient") + { + cn = new MySqlConnection(); + } + else + { + cn = Factory.CreateConnection(); + } + cn.ConnectionString = this.ConnectionString; + if (this.DataBaseName != "") System.Text.RegularExpressions.Regex.Replace(cn.ConnectionString, @"", DataBaseName); + return cn; + } + #endregion + #region 创建DbDataAdapter + public DbDataAdapter CreateDbDataAdapter() + { + DbDataAdapter da = null; + if (this.Namespace == "Oracle.DataAccess.Client") + { + da = new OracleDataAdapter(); + } + else if (this.Namespace == "MySql.Data.MySqlClient") + { + da = new MySqlDataAdapter(); + } + else + { + da = Factory.CreateDataAdapter(); + } + return da; + } + #endregion + #region 读取数据库名称 + public string GetDataBaseName() + { + if (cn != null) return cn.Database; + cn = CreateConnection(); + return cn.Database; + } + #endregion + + #region 测试连接 + public bool TestConnection() + { + if (cn == null) cn = CreateConnection(); + try + { + cn.Open(); + } + catch + { + return false; + } + cn.Close(); + return true; + } + #endregion + + #region 返回向DataTable查询条件 + public static string GetDataTableWhere(RefParameterCollection Param) + { + string tsql = ""; + if (Param != null && Param.Count != 0) + { + foreach (RefParameter pam in Param) + { + if (Param.IndexOf(pam) == 0) + { + switch (pam.Condition) + { + case "in": + if (pam.Type != DbType.String) + { + tsql = pam.Name + " in (" + pam.Value.ToString() + ")"; + } + else + { + string[] chars1 = pam.Value.ToString().Split(new char[] { ',' }); + string ss = ""; + foreach (string s in chars1) + { + if (ss == "") { ss = "'" + s + "'"; } + else { ss = ss + ",'" + s + "'"; } + } + tsql = pam.Name + " in (" + ss + ")"; + } + break; + case "not in": + if (pam.Type != DbType.String) + { + tsql = pam.Name + " not in (" + pam.Value.ToString() + ")"; + } + else + { + string[] chars2 = pam.Value.ToString().Split(new char[] { ',' }); + string ss = ""; + foreach (string s in chars2) + { + if (ss == "") { ss = "'" + s + "'"; } + else { ss = ss + ",'" + s + "'"; } + } + + tsql = pam.Name + " not in (" + ss + ")"; + } + break; + case "like": + tsql = pam.Name + " like '%" + pam.Value.ToString() + "%'"; + break; + case "like left": + tsql = pam.Name + " like '%" + pam.Value.ToString() + "'"; + break; + case "like right": + tsql = pam.Name + " like '" + pam.Value.ToString() + "%'"; + break; + case "is": + tsql = pam.Name + " is null"; + break; + case "is not": + tsql = pam.Name + " is not null"; + break; + default: + + if (pam.Type == DbType.String || pam.Type == DbType.DateTime) + { + tsql = pam.Name + pam.Condition + "'" + pam.Value.ToString() + "'"; + } + else + { + tsql = pam.Name + pam.Condition + pam.Value.ToString(); + } + break; + } + + } + else + { + switch (pam.Condition) + { + case "in": + if (pam.Type != DbType.String) + { + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " in (" + pam.Value.ToString() + ")"; + } + else + { + string[] chars3 = pam.Value.ToString().Split(new char[] { ',' }); + string ss = ""; + foreach (string s in chars3) + { + if (ss == "") { ss = "'" + s + "'"; } + else { ss = ss + ",'" + s + "'"; } + } + + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " in (" + ss + ")"; + } + break; + case "not in": + if (pam.Type != DbType.String) + { + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " not in (" + pam.Value.ToString() + ")"; + } + else + { + string[] chars4 = pam.Value.ToString().Split(new char[] { ',' }); + string ss = ""; + foreach (string s in chars4) + { + if (ss == "") { ss = "'" + s + "'"; } + else { ss = ss + ",'" + s + "'"; } + } + + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " not in (" + ss + ")"; + } + break; + case "like": + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " like '%" + pam.Value.ToString() + "%'"; + break; + case "like left": + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " like '%" + pam.Value.ToString() + "'"; + break; + case "like right": + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " like '" + pam.Value.ToString() + "%'"; + break; + case "is": + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " is null"; + break; + case "is not": + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " is not null"; + break; + default: + if (pam.Type == DbType.String || pam.Type == DbType.DateTime) + { + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + pam.Condition + "'" + pam.Value.ToString() + "'"; + } + else + { + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + pam.Condition + pam.Value.ToString(); + } + + break; + } + } + } + } + return tsql; + } + #endregion + + #region Command对象 + /// + /// 执行Sql语句的Command + /// + public DbCommand GetSqlStringCommand(string query) + { + return CreateCommandByCommandType(CommandType.Text, query); + } + + public virtual DbCommand GetStoredProcCommand(string storedProcedureName) + { + + return CreateCommandByCommandType(CommandType.StoredProcedure, storedProcedureName); + } + + private DbCommand CreateCommandByCommandType(CommandType commandType, string commandText) + { + DbCommand command = null; + if (this.Namespace == "Oracle.DataAccess.Client") + { + command = new OracleCommand(); + } + else if (this.Namespace == "MySql.Data.MySqlClient") + { + command = new MySqlCommand(); + } + else + { + if (Factory == null) + { + ErrorFollow.TraceWrite("连接方式错误", "", commandText); + return null; + } + command = Factory.CreateCommand(); + } + command.CommandType = commandType; + command.CommandText = commandText; + command.CommandTimeout = 300; + return command; + } + #endregion + + #region 参数 + public void AddInParameter(DbCommand cmd, RefParameterCollection Param) + { + if (Param != null && Param.Count != 0) + { + int i = 0; + foreach (RefParameter pam in Param) + { + if (pam.Direction == ParameterDirection.Input) + { + if (pam.IsDeclare == true) + { + if (pam.Condition == "in" || pam.Condition == "not in") + { + string[] chars = pam.Value.ToString().Split(new char[] { ',' }); + i = 0; + foreach (string s in chars) + { + this.AddInParameter(cmd, "@" + pam.Caption + i.ToString(), pam.Type, s); + i++; + } + } + else + { + if (pam.Value != null) + { + this.AddInParameter(cmd, "@" + pam.Caption, pam.Type, pam.Value); + } + } + } + else + { + + this.AddInParameter(cmd, "@" + pam.Name, pam.Type, pam.Value); + } + } + else + { + this.AddOutParameter(cmd, "@" + pam.Name, pam.Type, 50); + } + } + } + } + + + + + public void AddInParameter(DbCommand command, string name, DbType dbType, string sourceColumn, bool nullable, DataRowVersion version) + { + DbParameter parameter = CreateParameter(name, dbType, nullable, sourceColumn, version); + command.Parameters.Add(parameter); ; + } + + public void AddInParameter(DbCommand command, string name, DbType dbType, object value) + { + AddParameter(command, name, dbType, ParameterDirection.Input, true, value, null); + } + + public void AddOutParameter(DbCommand command, string name, DbType dbType, int Size) + { + AddParameter(command, name, dbType, ParameterDirection.Output, true, DBNull.Value, Size); + } + + public virtual void AddParameter(DbCommand command, string name, DbType dbType, ParameterDirection direction, bool nullable, object value, int? Size) + { + DbParameter parameter = CreateParameter(name, dbType, direction, nullable, value, Size); + command.Parameters.Add(parameter); + } + + + protected virtual DbParameter CreateParameter(string name, DbType dbType, ParameterDirection direction, bool nullable, object value, int? Size) + { + DbParameter param = Factory.CreateParameter(); + param.ParameterName = name; + param.DbType = dbType; + param.IsNullable = nullable; + param.Value = (value == null) ? DBNull.Value : value; + param.Direction = direction; + if (Size != null) param.Size = Size.Value; + return param; + } + + protected virtual DbParameter CreateParameter(string name, DbType dbType, bool nullable, string sourceColumn, DataRowVersion version) + { + DbParameter param = Factory.CreateParameter(); + param.ParameterName = name; + param.Value = DBNull.Value; + param.IsNullable = nullable; + param.DbType = dbType; + param.Direction = ParameterDirection.Input; + param.SourceColumnNullMapping = nullable; + param.SourceColumn = sourceColumn; + param.SourceVersion = version; + return param; + } + #endregion + + #region 打开连接 + private void ConnectOpen(DbConnection cn) + { + if (this.IsLastingConnect == false || cn.State == ConnectionState.Closed) cn.Open(); + } + #endregion + + #region 关闭连接 + private void ConnectClose(DbConnection cn) + { + if (this.IsLastingConnect == false || cn.State == ConnectionState.Open) cn.Close(); + } + public void CloseConnect() + { + cn.Close(); + cn.Dispose(); + } + #endregion + + #region 杀死锁进程 + public bool KillProcess() + { + //bConnection cn = CreateConnection(); + // try + // { + // DbCommand command = this.GetStoredProcCommand("p_lockinfo"); + // AddInParameter(command, "@kill_lock_spid", DbType.Boolean, true); //自动杀掉死锁进程 + // AddInParameter(command, "@show_spid_if_nolock", DbType.Int32, false); //不显示进程信息 + // command.Connection = cn; + // ConnectOpen(cn); + // cn.ChangeDatabase("master"); + // int a = command.ExecuteNonQuery(); + // ConnectClose(cn); + // HuizhongLibrary.Follow.ErrorFollow.TraceWrite("杀进程死锁成功:", "", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); + // } + // catch (Exception ex) + // { + + // HuizhongLibrary.Follow.ErrorFollow.TraceWrite("杀进程死锁出错:", "", ex.Message); + // return false; + // } + HuizhongLibrary.Log.ErrorFollow.TraceWrite("进程死锁:", "", ""); + return true; + } + #endregion + + #region 执行Command + public virtual DataTable ExecuteDataTable(DbCommand command) + { + bool bk=CheckSQL(command.CommandText); + if (bk == false) + { + ErrorFollow.TraceWrite("疑似SQL注入攻击,不允许执行", "", command.CommandText); + throw new Exception("疑似SQL注入攻击,不允许执行"); + } + DataTable tb = new DataTable(); + try + { + DbConnection cn = CreateConnection(); + command.Connection = cn; + DbDataAdapter adapter = CreateDbDataAdapter(); + adapter.SelectCommand = command; + ConnectOpen(cn); + if (this.DataBaseName != "") cn.ChangeDatabase(DataBaseName); + adapter.Fill(tb); + ConnectClose(cn); + //Dispose(command); + adapter.Dispose(); + adapter = null; + //using (DbDataAdapter adapter = Factory.CreateDataAdapter()) + //{ + // adapter.SelectCommand = command; + // ConnectOpen(cn); + // if (this.DataBaseName != "") cn.ChangeDatabase(DataBaseName); + // adapter.Fill(tb); + // ConnectClose(cn); + //} + } + catch (Exception ex) + { + ConnectClose(cn); + SqlConnection.ClearAllPools(); + if (ex.Message.Contains("进程已被死锁") == true) KillProcess(); + throw new Exception(ex.Message); + } + return tb; + } + + public virtual DataTable ExecuteDataTable(DbCommand command, int StartRowIndex, int RowCount,out int RowNum) + { + bool bk = CheckSQL(command.CommandText); + if (bk == false) + { + ErrorFollow.TraceWrite("疑似SQL注入攻击,不允许执行", "", command.CommandText); + throw new Exception("疑似SQL注入攻击,不允许执行"); + } + DataSet ds = new DataSet(); + try + { + DbConnection cn = CreateConnection(); + command.Connection = cn; + DbDataAdapter adapter = CreateDbDataAdapter(); + adapter.SelectCommand = command; + ConnectOpen(cn); + if (this.DataBaseName != "") cn.ChangeDatabase(DataBaseName); + RowNum=adapter.Fill(ds, StartRowIndex, RowCount, "Table1"); + ConnectClose(cn); + //Dispose(command); + adapter.Dispose(); + adapter = null; + } + catch (Exception ex) + { + ConnectClose(cn); + SqlConnection.ClearAllPools(); + if (ex.Message.Contains("进程已被死锁") == true) KillProcess(); + throw new Exception(ex.Message); + } + return ds.Tables[0]; + } + + + public virtual DataSet ExecuteDataSet(DbCommand command) + { + bool bk = CheckSQL(command.CommandText); + if (bk == false) + { + ErrorFollow.TraceWrite("疑似SQL注入攻击,不允许执行", "", command.CommandText); + throw new Exception("疑似SQL注入攻击,不允许执行"); + } + DataSet ds = new DataSet(); + try + { + DbConnection cn = CreateConnection(); + command.Connection = cn; + DbDataAdapter adapter = CreateDbDataAdapter(); + adapter.SelectCommand = command; + ConnectOpen(cn); + if (this.DataBaseName != "") cn.ChangeDatabase(DataBaseName); + adapter.Fill(ds); + ConnectClose(cn); + //Dispose(command); + adapter.Dispose(); + adapter = null; + } + catch (Exception ex) + { + ConnectClose(cn); + SqlConnection.ClearAllPools(); + if (ex.Message.Contains("进程已被死锁") == true) KillProcess(); + throw new Exception(ex.Message); + } + return ds; + } + + public virtual DataSet ExecuteDataSet(DbCommand command, int StartRowIndex, int RowCount) + { + bool bk = CheckSQL(command.CommandText); + if (bk == false) + { + ErrorFollow.TraceWrite("疑似SQL注入攻击,不允许执行", "", command.CommandText); + throw new Exception("疑似SQL注入攻击,不允许执行"); + } + DataSet ds = new DataSet(); + try + { + DbConnection cn = CreateConnection(); + command.Connection = cn; + DbDataAdapter adapter = CreateDbDataAdapter(); + adapter.SelectCommand = command; + ConnectOpen(cn); + if (this.DataBaseName != "") cn.ChangeDatabase(DataBaseName); + adapter.Fill(ds, StartRowIndex, RowCount, "Table1"); + ConnectClose(cn); + //Dispose(command); + adapter.Dispose(); + adapter = null; + } + catch (Exception ex) + { + ConnectClose(cn); + SqlConnection.ClearAllPools(); + if (ex.Message.Contains("进程已被死锁") == true) KillProcess(); + throw new Exception(ex.Message); + } + return ds; + } + + public virtual DataTable ExecuteDataTable(DbCommand command, DbConnection cn, DbTransaction trans) + { + bool bk = CheckSQL(command.CommandText); + if (bk == false) + { + ErrorFollow.TraceWrite("疑似SQL注入攻击,不允许执行", "", command.CommandText); + throw new Exception("疑似SQL注入攻击,不允许执行"); + } + DataTable tb = new DataTable(); + try + { + command.Connection = cn; + command.Transaction = trans; + DbDataAdapter adapter = CreateDbDataAdapter(); + adapter.SelectCommand = command; + adapter.Fill(tb); + //Dispose(command); + adapter.Dispose(); + adapter = null; + } + catch (Exception ex) + { + ConnectClose(cn); + SqlConnection.ClearAllPools(); + if (ex.Message.Contains("进程已被死锁") == true) KillProcess(); + throw new Exception(ex.Message); + } + return tb; + } + + public virtual int ExecuteNonQuery(DbCommand command) + { + bool bk = CheckSQL(command.CommandText); + if (bk == false) + { + ErrorFollow.TraceWrite("疑似SQL注入攻击,不允许执行", "", command.CommandText); + throw new Exception("疑似SQL注入攻击,不允许执行"); + } + DbConnection cn = CreateConnection(); + int a = 0; + try + { + command.Connection = cn; + ConnectOpen(cn); + if (this.DataBaseName != "") cn.ChangeDatabase(DataBaseName); + a = command.ExecuteNonQuery(); + ConnectClose(cn); + //Dispose(command); + } + catch (Exception ex) + { + ConnectClose(cn); + SqlConnection.ClearAllPools(); + if (ex.Message.Contains("进程已被死锁") == true) KillProcess(); + throw new Exception(ex.Message); + } + return a; + } + + public virtual void ExecuteNonQuery(List ListCommand) + { + foreach (var command in ListCommand) + { + bool bk = CheckSQL(command.CommandText); + if (bk == false) + { + ErrorFollow.TraceWrite("疑似SQL注入攻击,不允许执行", "", command.CommandText); + throw new Exception("疑似SQL注入攻击,不允许执行"); + } + } + + DbConnection cn = CreateConnection(); + ConnectOpen(cn); + if (this.DataBaseName != "") cn.ChangeDatabase(DataBaseName); + DbTransaction trans = cn.BeginTransaction(); + foreach (DbCommand cmd in ListCommand) + { + cmd.Connection = cn; + cmd.Transaction = trans; + cmd.ExecuteNonQuery(); + } + try + { + trans.Commit(); + ConnectClose(cn); + } + catch (Exception ex) + { + trans.Rollback(); + ConnectClose(cn); + SqlConnection.ClearAllPools(); + if (ex.Message.Contains("进程已被死锁") == true) KillProcess(); + throw new Exception(ex.Message); + } + } + + public virtual int ExecuteNonQuery(DbCommand command, DbConnection cn, DbTransaction trans) + { + bool bk = CheckSQL(command.CommandText); + if (bk == false) + { + ErrorFollow.TraceWrite("疑似SQL注入攻击,不允许执行", "", command.CommandText); + throw new Exception("疑似SQL注入攻击,不允许执行"); + } + int a = 0; + try + { + command.Connection = cn; + command.Transaction = trans; + a = command.ExecuteNonQuery(); + } + catch (Exception ex) + { + ConnectClose(cn); + SqlConnection.ClearAllPools(); + if (ex.Message.Contains("进程已被死锁") == true) KillProcess(); + throw new Exception(ex.Message); + } + + return a; + } + + public virtual object ExecuteScalar(DbCommand command) + { + bool bk = CheckSQL(command.CommandText); + if (bk == false) + { + ErrorFollow.TraceWrite("疑似SQL注入攻击,不允许执行", "", command.CommandText); + throw new Exception("疑似SQL注入攻击,不允许执行"); + } + DbConnection cn = CreateConnection(); + object a = null; + try + { + command.Connection = cn; + ConnectOpen(cn); + if (this.DataBaseName != "") cn.ChangeDatabase(DataBaseName); + a = command.ExecuteScalar(); + ConnectClose(cn); + //Dispose(command); + } + catch (Exception ex) + { + ConnectClose(cn); + SqlConnection.ClearAllPools(); + if (ex.Message.Contains("进程已被死锁") == true) KillProcess(); + throw new Exception(ex.Message); + } + return a; + } + + public virtual object ExecuteScalar(DbCommand command, DbConnection cn, DbTransaction trans) + { + bool bk = CheckSQL(command.CommandText); + if (bk == false) + { + ErrorFollow.TraceWrite("疑似SQL注入攻击,不允许执行", "", command.CommandText); + throw new Exception("疑似SQL注入攻击,不允许执行"); + } + object a = null; + try + { + command.Connection = cn; + command.Transaction = trans; + a = command.ExecuteScalar(); + } + catch (Exception ex) + { + ConnectClose(cn); + SqlConnection.ClearAllPools(); + if (ex.Message.Contains("进程已被死锁") == true) KillProcess(); + throw new Exception(ex.Message); + } + return a; + } + + public virtual IDataReader ExecuteReader(DbCommand command) + { + bool bk = CheckSQL(command.CommandText); + if (bk == false) + { + ErrorFollow.TraceWrite("疑似SQL注入攻击,不允许执行", "", command.CommandText); + throw new Exception("疑似SQL注入攻击,不允许执行"); + } + DbConnection cn = CreateConnection(); + IDataReader a = null; + try + { + command.Connection = cn; + ConnectOpen(cn); + if (this.DataBaseName != "") cn.ChangeDatabase(DataBaseName); + a = command.ExecuteReader(CommandBehavior.CloseConnection); + //ConnectClose(cn); + } + catch (Exception ex) + { + ConnectClose(cn); + SqlConnection.ClearAllPools(); + if (ex.Message.Contains("进程已被死锁") == true) KillProcess(); + throw new Exception(ex.Message); + } + return a; + } + + public virtual IDataReader ExecuteReader(DbCommand command, DbConnection cn, DbTransaction trans) + { + bool bk = CheckSQL(command.CommandText); + if (bk == false) + { + ErrorFollow.TraceWrite("疑似SQL注入攻击,不允许执行", "", command.CommandText); + throw new Exception("疑似SQL注入攻击,不允许执行"); + } + IDataReader a = null; + try + { + command.Connection = cn; + command.Transaction = trans; + } + catch (Exception ex) + { + ConnectClose(cn); + SqlConnection.ClearAllPools(); + if (ex.Message.Contains("进程已被死锁") == true) KillProcess(); + throw new Exception(ex.Message); + } + return a; + } + + //public void UpdateDataTable(DataTable tb, DbCommand insertCommand, DbCommand updateCommand, DbCommand deleteCommand) + //{ + // DbConnection cn = CreateConnection(); + // try + // { + // ConnectOpen(cn); + // if (this.DataBaseName != "") cn.ChangeDatabase(DataBaseName); + // //DbTransaction tran = cn.BeginTransaction(); + // DbDataAdapter da = Factory.CreateDataAdapter(); + // if (insertCommand != null) + // { + // //insertCommand.Transaction=tran; + // insertCommand.Connection = cn; + // da.InsertCommand = insertCommand; + // //da.InsertCommand.UpdatedRowSource = UpdateRowSource.None; + // } + // if (updateCommand != null) + // { + // //updateCommand.Transaction = tran; + // updateCommand.Connection = cn; + // da.UpdateCommand = updateCommand; + // //da.UpdateCommand.UpdatedRowSource = UpdateRowSource.None; + // } + // if (deleteCommand != null) + // { + // //deleteCommand.Transaction = tran; + // deleteCommand.Connection = cn; + // da.DeleteCommand = deleteCommand; + // //da.DeleteCommand.UpdatedRowSource = UpdateRowSource.None; + // } + // da.Update(tb); + // //tran.Commit(); + // ConnectClose(cn); + // } + // catch (Exception ex) + // { + // ConnectClose(cn); + // if (ex.Message.Contains("进程已被死锁") == true) KillProcess(); + // throw new Exception(ex.Message); + // } + + + //} + + public void UpdateDataTable(DataTable tb, DbCommand insertCommand, DbCommand updateCommand, DbCommand deleteCommand, int UpdateBatchSize) + { + bool bk = CheckSQL(insertCommand.CommandText); + if (bk == false) + { + ErrorFollow.TraceWrite("疑似SQL注入攻击,不允许执行", "", insertCommand.CommandText); + throw new Exception("疑似SQL注入攻击,不允许执行"); + } + bk = CheckSQL(updateCommand.CommandText); + if (bk == false) + { + ErrorFollow.TraceWrite("疑似SQL注入攻击,不允许执行", "", updateCommand.CommandText); + throw new Exception("疑似SQL注入攻击,不允许执行"); + } + bk = CheckSQL(deleteCommand.CommandText); + if (bk == false) + { + ErrorFollow.TraceWrite("疑似SQL注入攻击,不允许执行", "", deleteCommand.CommandText); + throw new Exception("疑似SQL注入攻击,不允许执行"); + } + DbConnection cn = CreateConnection(); + try + { + ConnectOpen(cn); + if (this.DataBaseName != "") cn.ChangeDatabase(DataBaseName); + //DbTransaction tran = cn.BeginTransaction(); + DbDataAdapter da = CreateDbDataAdapter(); + if (UpdateBatchSize != 1) da.UpdateBatchSize = UpdateBatchSize; + if (insertCommand != null) + { + //insertCommand.Transaction=tran; + insertCommand.Connection = cn; + da.InsertCommand = insertCommand; + if (UpdateBatchSize != 1) da.InsertCommand.UpdatedRowSource = UpdateRowSource.None; + } + if (updateCommand != null) + { + //updateCommand.Transaction = tran; + updateCommand.Connection = cn; + da.UpdateCommand = updateCommand; + if (UpdateBatchSize != 1) da.UpdateCommand.UpdatedRowSource = UpdateRowSource.None; + } + if (deleteCommand != null) + { + //deleteCommand.Transaction = tran; + deleteCommand.Connection = cn; + da.DeleteCommand = deleteCommand; + if (UpdateBatchSize != 1) da.DeleteCommand.UpdatedRowSource = UpdateRowSource.None; + } + da.Update(tb); + + //tran.Commit(); + ConnectClose(cn); + } + catch (Exception ex) + { + ConnectClose(cn); + SqlConnection.ClearAllPools(); + if (ex.Message.Contains("进程已被死锁") == true) KillProcess(); + throw new Exception(ex.Message); + } + } + + public void UpdateDataSet(DataSet ds, string TableName, DbCommand insertCommand, DbCommand updateCommand, DbCommand deleteCommand) + { + bool bk = CheckSQL(insertCommand.CommandText); + if (bk == false) + { + ErrorFollow.TraceWrite("疑似SQL注入攻击,不允许执行", "", insertCommand.CommandText); + throw new Exception("疑似SQL注入攻击,不允许执行"); + } + bk = CheckSQL(updateCommand.CommandText); + if (bk == false) + { + ErrorFollow.TraceWrite("疑似SQL注入攻击,不允许执行", "", updateCommand.CommandText); + throw new Exception("疑似SQL注入攻击,不允许执行"); + } + bk = CheckSQL(deleteCommand.CommandText); + if (bk == false) + { + ErrorFollow.TraceWrite("疑似SQL注入攻击,不允许执行", "", deleteCommand.CommandText); + throw new Exception("疑似SQL注入攻击,不允许执行"); + } + DbConnection cn = CreateConnection(); + try + { + ConnectOpen(cn); + if (this.DataBaseName != "") cn.ChangeDatabase(DataBaseName); + //DbTransaction tran = cn.BeginTransaction(); + DbDataAdapter da = CreateDbDataAdapter(); + if (insertCommand != null) + { + //insertCommand.Transaction = tran; + insertCommand.Connection = cn; + da.InsertCommand = insertCommand; + //da.InsertCommand.UpdatedRowSource = UpdateRowSource.None; + } + if (updateCommand != null) + { + //updateCommand.Transaction = tran; + updateCommand.Connection = cn; + da.UpdateCommand = updateCommand; + //da.UpdateCommand.UpdatedRowSource = UpdateRowSource.None; + } + if (deleteCommand != null) + { + //deleteCommand.Transaction = tran; + deleteCommand.Connection = cn; + da.DeleteCommand = deleteCommand; + //da.DeleteCommand.UpdatedRowSource = UpdateRowSource.None; + } + da.Update(ds, TableName); + + //tran.Commit(); + ConnectClose(cn); + } + catch (Exception ex) + { + ConnectClose(cn); + SqlConnection.ClearAllPools(); + if (ex.Message.Contains("进程已被死锁") == true) KillProcess(); + throw new Exception(ex.Message); + } + } + + public void UpdateDataSet(DataSet ds, string TableName, DbCommand insertCommand, DbCommand updateCommand, DbCommand deleteCommand, int UpdateBatchSize) + { + bool bk = CheckSQL(insertCommand.CommandText); + if (bk == false) + { + ErrorFollow.TraceWrite("疑似SQL注入攻击,不允许执行", "", insertCommand.CommandText); + throw new Exception("疑似SQL注入攻击,不允许执行"); + } + bk = CheckSQL(updateCommand.CommandText); + if (bk == false) + { + ErrorFollow.TraceWrite("疑似SQL注入攻击,不允许执行", "", updateCommand.CommandText); + throw new Exception("疑似SQL注入攻击,不允许执行"); + } + bk = CheckSQL(deleteCommand.CommandText); + if (bk == false) + { + ErrorFollow.TraceWrite("疑似SQL注入攻击,不允许执行", "", deleteCommand.CommandText); + throw new Exception("疑似SQL注入攻击,不允许执行"); + } + DbConnection cn = CreateConnection(); + try + { + ConnectOpen(cn); + if (this.DataBaseName != "") cn.ChangeDatabase(DataBaseName); + //DbTransaction tran = cn.BeginTransaction(); + DbDataAdapter da = CreateDbDataAdapter(); + if (UpdateBatchSize != 1) da.UpdateBatchSize = UpdateBatchSize; + if (insertCommand != null) + { + //insertCommand.Transaction = tran; + insertCommand.Connection = cn; + da.InsertCommand = insertCommand; + if (UpdateBatchSize != 1) da.InsertCommand.UpdatedRowSource = UpdateRowSource.None; + } + if (updateCommand != null) + { + //updateCommand.Transaction = tran; + updateCommand.Connection = cn; + da.UpdateCommand = updateCommand; + if (UpdateBatchSize != 1) da.UpdateCommand.UpdatedRowSource = UpdateRowSource.None; + } + if (deleteCommand != null) + { + //deleteCommand.Transaction = tran; + deleteCommand.Connection = cn; + da.DeleteCommand = deleteCommand; + if (UpdateBatchSize != 1) da.DeleteCommand.UpdatedRowSource = UpdateRowSource.None; + } + da.Update(ds, TableName); + ConnectClose(cn); + } + catch (Exception ex) + { + ConnectClose(cn); + SqlConnection.ClearAllPools(); + if (ex.Message.Contains("进程已被死锁") == true) KillProcess(); + throw new Exception(ex.Message); + } + } + + public void UpdateBatchDataRow(DataRow[] drow, DbCommand insertCommand, DbCommand updateCommand, DbCommand deleteCommand) + { + bool bk = CheckSQL(insertCommand.CommandText); + if (bk == false) + { + ErrorFollow.TraceWrite("疑似SQL注入攻击,不允许执行", "", insertCommand.CommandText); + throw new Exception("疑似SQL注入攻击,不允许执行"); + } + bk = CheckSQL(updateCommand.CommandText); + if (bk == false) + { + ErrorFollow.TraceWrite("疑似SQL注入攻击,不允许执行", "", updateCommand.CommandText); + throw new Exception("疑似SQL注入攻击,不允许执行"); + } + bk = CheckSQL(deleteCommand.CommandText); + if (bk == false) + { + ErrorFollow.TraceWrite("疑似SQL注入攻击,不允许执行", "", deleteCommand.CommandText); + throw new Exception("疑似SQL注入攻击,不允许执行"); + } + DbConnection cn = CreateConnection(); + try + { + ConnectOpen(cn); + DbDataAdapter da = CreateDbDataAdapter(); + da.UpdateBatchSize = 0; + if (insertCommand != null) + { + //insertCommand.Transaction = transaction; + insertCommand.Connection = cn; + da.InsertCommand = insertCommand; + da.InsertCommand.UpdatedRowSource = UpdateRowSource.None; + } + if (updateCommand != null) + { + //updateCommand.Transaction = transaction; + updateCommand.Connection = cn; + da.UpdateCommand = updateCommand; + da.UpdateCommand.UpdatedRowSource = UpdateRowSource.None; + } + if (deleteCommand != null) + { + //deleteCommand.Transaction = transaction; + deleteCommand.Connection = cn; + da.DeleteCommand = deleteCommand; + da.DeleteCommand.UpdatedRowSource = UpdateRowSource.None; + } + da.Update(drow); + ConnectClose(cn); + } + catch (Exception ex) + { + ConnectClose(cn); + SqlConnection.ClearAllPools(); + if (ex.Message.Contains("进程已被死锁") == true) KillProcess(); + throw new Exception(ex.Message); + } + } + + public void UpdateTranDataTable(DataTable tb, DbCommand insertCommand, DbCommand updateCommand, DbCommand deleteCommand) + { + bool bk = CheckSQL(insertCommand.CommandText); + if (bk == false) + { + ErrorFollow.TraceWrite("疑似SQL注入攻击,不允许执行", "", insertCommand.CommandText); + throw new Exception("疑似SQL注入攻击,不允许执行"); + } + bk = CheckSQL(updateCommand.CommandText); + if (bk == false) + { + ErrorFollow.TraceWrite("疑似SQL注入攻击,不允许执行", "", updateCommand.CommandText); + throw new Exception("疑似SQL注入攻击,不允许执行"); + } + bk = CheckSQL(deleteCommand.CommandText); + if (bk == false) + { + ErrorFollow.TraceWrite("疑似SQL注入攻击,不允许执行", "", deleteCommand.CommandText); + throw new Exception("疑似SQL注入攻击,不允许执行"); + } + DataTable table1 = tb.GetChanges(DataRowState.Deleted); + if (table1 != null) table1.RejectChanges(); + DataTable table2 = tb.GetChanges(DataRowState.Added); + DataTable table3 = tb.GetChanges(DataRowState.Modified); + int len = 0; + if (table1 != null) len += table1.Rows.Count; + if (table2 != null) len += table2.Rows.Count; + if (table3 != null) len += table3.Rows.Count; + if (len == 0) return; + DbConnection cn = CreateConnection(); + ConnectOpen(cn); + DbTransaction trans = cn.BeginTransaction(); + try + { + DbCommand[] ListCommand = new DbCommand[len]; + int index = 0; + if (deleteCommand != null && table1 != null) + { + foreach (DataRow row in table1.Rows) + { + ListCommand[index] = this.GetSqlStringCommand(deleteCommand.CommandText); + ListCommand[index].CommandType = deleteCommand.CommandType; + ListCommand[index].CommandTimeout = 300; + foreach (DbParameter pam in deleteCommand.Parameters) + { + object value = pam.Value; + if (value == DBNull.Value) value = row[pam.SourceColumn]; + this.AddInParameter(ListCommand[index], pam.ParameterName, pam.DbType, value); + } + ListCommand[index].Connection = cn; + ListCommand[index].Transaction = trans; + ListCommand[index].ExecuteNonQuery(); + index++; + } + } + if (insertCommand != null && table2 != null) + { + foreach (DataRow row in table2.Rows) + { + ListCommand[index] = this.GetSqlStringCommand(insertCommand.CommandText); + ListCommand[index].CommandType = insertCommand.CommandType; + ListCommand[index].CommandTimeout = 300; + foreach (DbParameter pam in insertCommand.Parameters) + { + object value = pam.Value; + if (value == DBNull.Value) value = row[pam.SourceColumn]; + this.AddInParameter(ListCommand[index], pam.ParameterName, pam.DbType, value); + } + ListCommand[index].Connection = cn; + ListCommand[index].Transaction = trans; + ListCommand[index].ExecuteNonQuery(); + index++; + } + } + if (updateCommand != null && table3 != null) + { + foreach (DataRow row in table3.Rows) + { + ListCommand[index] = this.GetSqlStringCommand(updateCommand.CommandText); + ListCommand[index].CommandType = updateCommand.CommandType; + ListCommand[index].CommandTimeout = 300; + foreach (DbParameter pam in updateCommand.Parameters) + { + object value = pam.Value; + if (value == DBNull.Value) value = row[pam.SourceColumn]; + this.AddInParameter(ListCommand[index], pam.ParameterName, pam.DbType, value); + } + ListCommand[index].Connection = cn; + ListCommand[index].Transaction = trans; + ListCommand[index].ExecuteNonQuery(); + index++; + } + } + trans.Commit(); + } + catch (Exception ex) + { + trans.Rollback(); + if (ex.Message.Contains("进程已被死锁") == true) + { + ConnectClose(cn); + KillProcess(); + } + throw new Exception(ex.Message); + } + finally + { + ConnectClose(cn); + } + } + + public void UpdateDataTable(DataTable tb, DbCommand insertCommand, DbCommand updateCommand, DbCommand deleteCommand) + { + bool bk = CheckSQL(insertCommand.CommandText); + if (bk == false) + { + ErrorFollow.TraceWrite("疑似SQL注入攻击,不允许执行", "", insertCommand.CommandText); + throw new Exception("疑似SQL注入攻击,不允许执行"); + } + bk = CheckSQL(updateCommand.CommandText); + if (bk == false) + { + ErrorFollow.TraceWrite("疑似SQL注入攻击,不允许执行", "", updateCommand.CommandText); + throw new Exception("疑似SQL注入攻击,不允许执行"); + } + bk = CheckSQL(deleteCommand.CommandText); + if (bk == false) + { + ErrorFollow.TraceWrite("疑似SQL注入攻击,不允许执行", "", deleteCommand.CommandText); + throw new Exception("疑似SQL注入攻击,不允许执行"); + } + DataTable table1 = tb.GetChanges(DataRowState.Deleted); + if (table1 != null) table1.RejectChanges(); + DataTable table2 = tb.GetChanges(DataRowState.Added); + DataTable table3 = tb.GetChanges(DataRowState.Modified); + int len = 0; + if (table1 != null) len += table1.Rows.Count; + if (table2 != null) len += table2.Rows.Count; + if (table3 != null) len += table3.Rows.Count; + if (len == 0) return; + DbConnection cn = CreateConnection(); + ConnectOpen(cn); + //DbTransaction trans = cn.BeginTransaction(); + try + { + DbCommand[] ListCommand = new DbCommand[len]; + int index = 0; + if (deleteCommand != null && table1 != null) + { + foreach (DataRow row in table1.Rows) + { + ListCommand[index] = this.GetSqlStringCommand(deleteCommand.CommandText); + ListCommand[index].CommandType = deleteCommand.CommandType; + ListCommand[index].CommandTimeout = 300; + foreach (DbParameter pam in deleteCommand.Parameters) + { + object value = pam.Value; + if (value == DBNull.Value) value = row[pam.SourceColumn]; + this.AddInParameter(ListCommand[index], pam.ParameterName, pam.DbType, value); + } + ListCommand[index].Connection = cn; + //ListCommand[index].Transaction = trans; + ListCommand[index].ExecuteNonQuery(); + index++; + } + } + if (insertCommand != null && table2 != null) + { + foreach (DataRow row in table2.Rows) + { + ListCommand[index] = this.GetSqlStringCommand(insertCommand.CommandText); + ListCommand[index].CommandType = insertCommand.CommandType; + ListCommand[index].CommandTimeout = 300; + foreach (DbParameter pam in insertCommand.Parameters) + { + object value = pam.Value; + if (value == DBNull.Value) value = row[pam.SourceColumn]; + this.AddInParameter(ListCommand[index], pam.ParameterName, pam.DbType, value); + } + ListCommand[index].Connection = cn; + //ListCommand[index].Transaction = trans; + ListCommand[index].ExecuteNonQuery(); + index++; + } + } + if (updateCommand != null && table3 != null) + { + foreach (DataRow row in table3.Rows) + { + ListCommand[index] = this.GetSqlStringCommand(updateCommand.CommandText); + ListCommand[index].CommandType = updateCommand.CommandType; + ListCommand[index].CommandTimeout = 300; + foreach (DbParameter pam in updateCommand.Parameters) + { + object value = pam.Value; + if (value == DBNull.Value) value = row[pam.SourceColumn]; + this.AddInParameter(ListCommand[index], pam.ParameterName, pam.DbType, value); + } + ListCommand[index].Connection = cn; + //ListCommand[index].Transaction = trans; + ListCommand[index].ExecuteNonQuery(); + index++; + } + } + //trans.Commit(); + } + catch (Exception ex) + { + //trans.Rollback(); + if (ex.Message.Contains("进程已被死锁") == true) + { + ConnectClose(cn); + KillProcess(); + } + throw new Exception(ex.Message); + } + finally + { + ConnectClose(cn); + } + } + #endregion + + #region 参数格式化 + protected virtual void DeriveParameters(DbCommand discoveryCommand) + { + if (this.m_Factory == null) + { + throw new ArgumentNullException("DbProviderFactory"); + } + MethodInfo method = this.m_Factory.CreateCommandBuilder().GetType().GetMethod("DeriveParameters"); + if (method == null) + { + throw new ArgumentException("没有可以读取的参数,存储过程错误"); + } + method.Invoke(null, new object[] { discoveryCommand }); + } + + public void DiscoverParameters(DbCommand command) + { + DbConnection cn = CreateConnection(); + ConnectOpen(cn); + DbCommand discoveryCommand = this.CreateCommandByCommandType(command.CommandType, command.CommandText); + discoveryCommand.Connection = cn; + this.DeriveParameters(discoveryCommand); + foreach (IDataParameter parameter in discoveryCommand.Parameters) + { + IDataParameter cloneParameter = (IDataParameter)((ICloneable)parameter).Clone(); + command.Parameters.Add(cloneParameter); + } + ConnectClose(cn); + } + #endregion + + #region 创建有自动增加ID列(列名RowIndex)的DataSet + /// + /// 创建有自动增加ID列(列名RowIndex)的DataSet + /// + /// 要初始化的DataTable表数据 + /// 返回DataSet + public DataSet CreateDataSet(int TableCount) + { + DataSet ds = new DataSet(); + DataTable tb = null; + for (int i = 0; i < TableCount; i++) + { + string TableName = "Table"; + if (i > 0) TableName += i.ToString(); + tb = new DataTable(TableName); + tb.Columns.Add("RowIndex", typeof(int)); + tb.Columns[0].AutoIncrement = true; + tb.Columns[0].AutoIncrementSeed = 1; + ds.Tables.Add(tb); + } + return ds; + } + #endregion + + #region 创建有自动增加ID列(列名RowIndex)的DataTable + /// + /// 创建有自动增加ID列(列名RowIndex)的DataSet + /// + /// 返回DataTable + public DataTable CreateDataTable() + { + DataTable tb = null; + tb = new DataTable("Table"); + tb.Columns.Add("RowIndex", typeof(int)); + tb.Columns[0].AutoIncrement = true; + tb.Columns[0].AutoIncrementSeed = 1; + return tb; + } + #endregion + + #region SQL关键字检测 + public bool CheckSQL(string str) + { + if (IsCheckKeyword == false) return true; + var str2 = str.ToLower(); + if (str2.Contains("xp_cmdshell")) return false; + if (str2.Contains("exec master")) return false; + if (str2.Contains("netlocalgroup")) return false; + if (str2.Contains("administrators")) return false; + if (str2.Contains("net user")) return false; + if (str2.Contains("use master")) return false; + if (str2.Contains("sysobjects")) return false; + if (str2.Contains("syscolumns")) return false; + if (str2.Contains("sysusers")) return false; + if (str2.Contains("sysdatabases")) return false; + return true; + } + #endregion + + + public virtual void BatchExecuteNonQuery(List ListCommand) + { + DbConnection cn = CreateConnection(); + ConnectOpen(cn); + if (this.DataBaseName != "") cn.ChangeDatabase(DataBaseName); + + foreach (DbCommand cmd in ListCommand) + { + cmd.Connection = cn; + + cmd.ExecuteNonQuery(); + } + try + { + + ConnectClose(cn); + } + catch (Exception ex) + { + + ConnectClose(cn); + SqlConnection.ClearAllPools(); + if (ex.Message.Contains("进程已被死锁") == true) KillProcess(); + throw new Exception(ex.Message); + } + } + + + public void LoadDataSet(DbCommand command, DataSet ds, string TableName) + { + try + { + DbConnection cn = CreateConnection(); + command.Connection = cn; + DbDataAdapter adapter = CreateDbDataAdapter(); + adapter.SelectCommand = command; + ConnectOpen(cn); + if (this.DataBaseName != "") cn.ChangeDatabase(DataBaseName); + adapter.Fill(ds, TableName); + ConnectClose(cn); + adapter = null; + } + catch (Exception ex) + { + ConnectClose(cn); + if (ex.Message.Contains("进程已被死锁") == true) KillProcess(); + throw new Exception(ex.Message); + } + } + + public void LoadDataSet(DbCommand command, DataSet ds) + { + try + { + DbConnection cn = CreateConnection(); + command.Connection = cn; + DbDataAdapter adapter = CreateDbDataAdapter(); + adapter.SelectCommand = command; + ConnectOpen(cn); + if (this.DataBaseName != "") cn.ChangeDatabase(DataBaseName); + adapter.Fill(ds); + ConnectClose(cn); + adapter = null; + } + catch (Exception ex) + { + ConnectClose(cn); + SqlConnection.ClearAllPools(); + if (ex.Message.Contains("进程已被死锁") == true) KillProcess(); + throw new Exception(ex.Message); + } + } + + public void LoadDataSet(DbCommand command, DataSet ds, string TableName, int StartRowIndex, int RowCount) + { + try + { + DbConnection cn = CreateConnection(); + command.Connection = cn; + DbDataAdapter adapter = CreateDbDataAdapter(); + adapter.SelectCommand = command; + ConnectOpen(cn); + if (this.DataBaseName != "") cn.ChangeDatabase(DataBaseName); + adapter.Fill(ds, StartRowIndex, RowCount, TableName); + ConnectClose(cn); + adapter = null; + } + catch (Exception ex) + { + ConnectClose(cn); + SqlConnection.ClearAllPools(); + if (ex.Message.Contains("进程已被死锁") == true) KillProcess(); + throw new Exception(ex.Message); + } + } + } +} diff --git a/基础类库/HuizhongLibrary/DatabaseConnect.cs b/基础类库/HuizhongLibrary/DatabaseConnect.cs new file mode 100644 index 0000000..802cfe4 --- /dev/null +++ b/基础类库/HuizhongLibrary/DatabaseConnect.cs @@ -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 + + + } +} diff --git a/基础类库/HuizhongLibrary/DatabaseFactory.cs b/基础类库/HuizhongLibrary/DatabaseFactory.cs new file mode 100644 index 0000000..d5f96ad --- /dev/null +++ b/基础类库/HuizhongLibrary/DatabaseFactory.cs @@ -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; + } + } +} \ No newline at end of file diff --git a/基础类库/HuizhongLibrary/DateUtils.cs b/基础类库/HuizhongLibrary/DateUtils.cs new file mode 100644 index 0000000..5c89214 --- /dev/null +++ b/基础类库/HuizhongLibrary/DateUtils.cs @@ -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); + } + + /// + /// 获取北京时间 + /// + /// + public static DateTime GetBJNow() + { + return DateTime.Now.ToUniversalTime().AddHours(8); + } + } +} diff --git a/基础类库/HuizhongLibrary/Dingtalk/DingtalkModel.cs b/基础类库/HuizhongLibrary/Dingtalk/DingtalkModel.cs new file mode 100644 index 0000000..2801128 --- /dev/null +++ b/基础类库/HuizhongLibrary/Dingtalk/DingtalkModel.cs @@ -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 department { get; set; } + public List 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 department { get; set; } + public string mobile { get; set; } + + public DingUser() + { + department = new List(); + } + } + 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 userIdList { get; set; } + public List userIds { get; set; } + public int offset { get; set; } + public int limit { get; set; } + + public DingWorkRequest() + { + limit = 50; + userIdList = new List(); + userIds = new List(); + } + } + #endregion + #region 考勤结果 + public class DingWorkResult + { + public int errcode { get; set; } + public string errmsg { get; set; } + public bool hasMore { get; set; } + public List recordresult { get; set; } + } + public class DingWorkResult2 + { + public long id { get; set; } + /// + /// 考勤组ID + /// + public long groupId { get; set; } + /// + /// 排班ID + /// + public long planId { get; set; } + /// + /// 打卡记录ID + /// + public long recordId { get; set; } + /// + /// 考勤日期 + /// + public long workDate { get; set; } + public string userId { get; set; } + public string userAddress { get; set; } + /// + /// 打卡时间 + /// + public Int64 userCheckTime { get; set; } + /// + /// OnDuty=上班,OffDuty=下班 + /// + public string checkType { get; set; } + /// + /// Normal=范围内,Outside=范围外,NotSigned=未打卡 + /// + public string locationResult { get; set; } + /// + /// Normal=正常,Early=早退,Late=迟到,SeriousLate=严重迟到,Absenteeism=旷工迟到,NotSigned=未打卡 + /// + 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 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 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 cc_userids { get; set; } + public List form_component_values { get; set; } + public string result { get; set; } + public string business_id { get; set; } + public List operation_records { get; set; } + public List tasks { get; set; } + public string originator_dept_name { get; set; } + public string biz_action { get; set; } + public List 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 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; } + /// + /// 是否还有下一页 + /// + public bool has_more { get; set; } + /// + /// 下次查询起始页 + /// + public long next_cursor { get; set; } + public List data_list { get; set; } + } + public class DingLogResult3 + { + /// + /// 日志唯一id + /// + public string report_id { get; set; } + /// + /// 日志创建时间 + /// + public long create_time { get; set; } + /// + /// 日志创建人userid + /// + public string creator_id { get; set; } + /// + /// 日志创建人 + /// + public string creator_name { get; set; } + /// + /// 部门 + /// + public string dept_name { get; set; } + public string template_name { get; set; } + public string remark { get; set; } + public List 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 +} diff --git a/基础类库/HuizhongLibrary/Dingtalk/DingtalkService.cs b/基础类库/HuizhongLibrary/Dingtalk/DingtalkService.cs new file mode 100644 index 0000000..5d9701e --- /dev/null +++ b/基础类库/HuizhongLibrary/Dingtalk/DingtalkService.cs @@ -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(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(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(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; + } + } + + + + /// + ///获取AccessToken + /// + /// + /// + 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; + } + } + + + ///   +        /// 将c# DateTime时间格式转换为Unix时间戳格式   +        ///   +        /// 时间   +        /// long   +        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; + } + + /// + /// 获取签名 + /// + /// 将bytesToSign作为消息 + /// 将SecretKey作为秘钥 + /// + 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(HttpMethod method, string canonicalURI, Dictionary 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(); +// 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(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(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(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(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(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(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(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(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(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(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(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(XmlContent); + if (model2.errcode == 0) return; + ErrorMessage = model2.errmsg; + } + #endregion + #region 获取部门列表 + public static List 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(XmlContent); + if (model2.errcode == 0) return model2.department; + ErrorMessage = model2.errmsg; + return null; + } + #endregion + + #region 获取部门列表 + public static List 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(XmlContent); + if (model2.errcode == 0) return model2.department; + ErrorMessage = model2.errmsg; + return null; + } + #endregion + + + #region 获取部门id列表 + public static List 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(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(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(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(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(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(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(XmlContent); + if (model2.errcode == 0) return model2.userid; + ErrorMessage = model2.errmsg; + return ""; + } + #endregion + #region 获取员工列表 + public static List 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(XmlContent); + if (model2.errcode == 0) return model2.userlist; + ErrorMessage = model2.errmsg; + return null; + } + #endregion + #region 获取考勤结果 + public static List GetWork(string AccessToken, DingWorkRequest model, out string ErrorMessage) + { + var ListModel = new List(); + GetWorkDetail(AccessToken, model, ListModel, out ErrorMessage); + return ListModel; + } + public static void GetWorkDetail(string AccessToken, DingWorkRequest model, List 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(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 GetWordRecord(string AccessToken, DingWorkRequest model, out string ErrorMessage) + { + var ListModel = new List(); + GetWorkDetailRecord(AccessToken, model, ListModel, out ErrorMessage); + return ListModel; + } + public static void GetWorkDetailRecord(string AccessToken, DingWorkRequest model, List 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(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(XmlContent); + if (model2.errcode == 0)return model2.result.duration_in_minutes; + ErrorMessage = model2.errmsg; + return -1; + } + #endregion + #region 获取审批 + public static List 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(); + 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 GetExamIds(string AccessToken, string code, ExamIdRequest model,out string ErrorMessage) + { + var ListModel = new List(); + GetExamIdsDetail(AccessToken, code, model, ListModel, out ErrorMessage); + return ListModel; + } + public static void GetExamIdsDetail(string AccessToken, string code, ExamIdRequest model, List 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(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(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(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 GetLog(string AccessToken, DingLogRequest model, out string ErrorMessage) + { + var ListModel = new List(); + GetLogDetail(AccessToken, model, ListModel, out ErrorMessage); + return ListModel; + } + public static void GetLogDetail(string AccessToken, DingLogRequest model, List 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(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 + } +} diff --git a/基础类库/HuizhongLibrary/DllInvoke.cs b/基础类库/HuizhongLibrary/DllInvoke.cs new file mode 100644 index 0000000..acec78f --- /dev/null +++ b/基础类库/HuizhongLibrary/DllInvoke.cs @@ -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函数 + } + } +} diff --git a/基础类库/HuizhongLibrary/EcanConvertToCh.cs b/基础类库/HuizhongLibrary/EcanConvertToCh.cs new file mode 100644 index 0000000..82e79ca --- /dev/null +++ b/基础类库/HuizhongLibrary/EcanConvertToCh.cs @@ -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方法用于将汉字转换成全拼的拼音,其中,参数代表汉字字符串,此方法的返回值是转换后的拼音字符串 + + /// + /// 汉字转换成全拼的拼音 + /// + /// 汉字字符串 + /// 转换后的拼音字符串 + + 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;//返回获取到的汉字拼音 + } + } +} diff --git a/基础类库/HuizhongLibrary/ErrorFollow.cs b/基础类库/HuizhongLibrary/ErrorFollow.cs new file mode 100644 index 0000000..e3af78f --- /dev/null +++ b/基础类库/HuizhongLibrary/ErrorFollow.cs @@ -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 Ϣ + /// + /// Ϣ + /// + 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 Ϣ + /// + /// Ϣ + /// + 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 Ϣ_ұ浽ݿ + /// + /// Ϣ_ұ浽ݿ + /// + 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ҺշϢ + /// + /// Ϣ + /// + 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 Ϣ + /// + /// Ϣ + /// + 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 act = new Action(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 files = new List(); + 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 ӿϢ + /// + /// ӿϢ + /// + 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 + + + } +} diff --git a/基础类库/HuizhongLibrary/Extension/DataTableExtension.cs b/基础类库/HuizhongLibrary/Extension/DataTableExtension.cs new file mode 100644 index 0000000..44ab775 --- /dev/null +++ b/基础类库/HuizhongLibrary/Extension/DataTableExtension.cs @@ -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 +{ + /// + /// DataTable扩展 + /// + public static class DataTableExtension + { + #region DataTable转List + /// + /// DataTable转List + /// + /// 扩展对象 + public static List ToList(this DataTable tb) + { + if (tb == null || tb.Rows.Count == 0) return null; + //获取对象所有属性 + Type t = typeof(T); + List ListModel = new List(); + + 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(); + 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(); + 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(this DataRow row) + { + //获取对象所有属性 + DataTable tb = row.Table; + Type t = typeof(T); + T model = Activator.CreateInstance(); + 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 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)) + { + info.SetValue(model, Convert.ToByte(val), null); + } + else if (info.PropertyType == typeof(Int16) || info.PropertyType == typeof(Nullable)) + { + info.SetValue(model, Convert.ToInt16(val), null); + } + else if (info.PropertyType == typeof(int) || info.PropertyType == typeof(Nullable)) + { + info.SetValue(model, Convert.ToInt32(val), null); + } + else if (info.PropertyType == typeof(Int64) || info.PropertyType == typeof(Nullable)) + { + info.SetValue(model, Convert.ToInt64(val), null); + } + else if (info.PropertyType == typeof(bool) || info.PropertyType == typeof(Nullable)) + { + 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)) + { + info.SetValue(model, Convert.ToDecimal(val), null); + } + else if (info.PropertyType == typeof(Double) || info.PropertyType == typeof(Nullable)) + { + info.SetValue(model, Convert.ToDouble(val), null); + } + else if (info.PropertyType == typeof(Single) || info.PropertyType == typeof(Nullable)) + { + info.SetValue(model, Convert.ToSingle(val), null); + } + else if (info.PropertyType == typeof(DateTime) || info.PropertyType == typeof(Nullable)) + { + 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 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)) + { + info.SetValue(model, Convert.ToByte(val)); + } + else if (info.FieldType == typeof(Int16) || info.FieldType == typeof(Nullable)) + { + info.SetValue(model, Convert.ToInt16(val)); + } + else if (info.FieldType == typeof(int) || info.FieldType == typeof(Nullable)) + { + info.SetValue(model, Convert.ToInt32(val)); + } + else if (info.FieldType == typeof(Int64) || info.FieldType == typeof(Nullable)) + { + info.SetValue(model, Convert.ToInt64(val)); + } + else if (info.FieldType == typeof(bool) || info.FieldType == typeof(Nullable)) + { + 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)) + { + info.SetValue(model, Convert.ToDecimal(val)); + } + else if (info.FieldType == typeof(Double) || info.FieldType == typeof(Nullable)) + { + info.SetValue(model, Convert.ToDouble(val)); + } + else if (info.FieldType == typeof(Single) || info.FieldType == typeof(Nullable)) + { + info.SetValue(model, Convert.ToSingle(val)); + } + else if (info.FieldType == typeof(DateTime) || info.FieldType == typeof(Nullable)) + { + 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(); + tb2.Rows.Add(row); + } + return tb2; + } + #endregion + + } + + +} diff --git a/基础类库/HuizhongLibrary/Extension/ListExtension.cs b/基础类库/HuizhongLibrary/Extension/ListExtension.cs new file mode 100644 index 0000000..325c9c2 --- /dev/null +++ b/基础类库/HuizhongLibrary/Extension/ListExtension.cs @@ -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(this Object obj) + { + var ss = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(obj)); + return ss; + } + #endregion + + + #region 转JSON文件 + /// + /// 转JSON文件 + /// + /// 扩展对象 + /// 文件路径 + 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字符串 + /// + /// 转JSON字符串 + /// + /// 扩展对象 + 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字符串 + /// + /// 转JSON字符串 + /// + /// 扩展对象 + 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 + /// + /// List转DataTable + /// + /// 对象 + /// 扩展对象 + /// + public static DataTable ToDataTable(this IEnumerable ListModel) where TResult : class + { + //创建属性的集合 + List pList = new List(); + //获得反射的入口 + Type type = typeof(TResult); + DataTable dt = new DataTable(); + //把所有的public属性加入到集合 并添加DataTable的列 + Array.ForEach(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(this IEnumerable list, List ListSerializePropertieName) where TResult : class + { + //创建属性的集合 + List pList = new List(); + //获得反射的入口 + Type type = typeof(TResult); + DataTable dt = new DataTable(); + //把所有的public属性加入到集合 并添加DataTable的列 + Array.ForEach(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 ListModel = new List(); + 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 + + } +} + + diff --git a/基础类库/HuizhongLibrary/HTMLPage1.html b/基础类库/HuizhongLibrary/HTMLPage1.html new file mode 100644 index 0000000..206ad6f --- /dev/null +++ b/基础类库/HuizhongLibrary/HTMLPage1.html @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + diff --git a/基础类库/HuizhongLibrary/HtmlCapture.cs b/基础类库/HuizhongLibrary/HtmlCapture.cs new file mode 100644 index 0000000..f4fdb4b --- /dev/null +++ b/基础类库/HuizhongLibrary/HtmlCapture.cs @@ -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 +} diff --git a/基础类库/HuizhongLibrary/HttpFormData.cs b/基础类库/HuizhongLibrary/HttpFormData.cs new file mode 100644 index 0000000..7accc1d --- /dev/null +++ b/基础类库/HuizhongLibrary/HttpFormData.cs @@ -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 +{ + + + /// + /// 表单数据项 + /// + public class FormItemModel + { + /// + /// 表单键,request["key"] + /// + public string Key { set; get; } + /// + /// 表单值,上传文件时忽略,request["key"].value + /// + public string Value { set; get; } + /// + /// 是否是文件 + /// + 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; + } + } + /// + /// 上传的文件名 + /// + public string FileName { set; get; } + /// + /// 上传的文件内容 + /// + 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; //总是接受 + } + + /// + /// 使用Post方法获取字符串结果 + /// + /// + /// Post表单内容 + /// + /// 默认20秒 + /// 响应内容的编码类型(默认utf-8) + /// + public static string PostForm(string url, string Head, List 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; + } + } + } + + /// + /// 使用Post方法获取字符串结果 + /// + /// + /// Post表单内容 + /// + /// 默认20秒 + /// 响应内容的编码类型(默认utf-8) + /// + public static string PostForm(string url,List Head, List 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; + } + } + } + } +} + diff --git a/基础类库/HuizhongLibrary/HuizhongLibrary.csproj b/基础类库/HuizhongLibrary/HuizhongLibrary.csproj new file mode 100644 index 0000000..0fd713e --- /dev/null +++ b/基础类库/HuizhongLibrary/HuizhongLibrary.csproj @@ -0,0 +1,317 @@ + + + + + Debug + AnyCPU + {DB915A85-C567-4084-A3F2-A47E4A3291B7} + Library + Properties + HuizhongLibrary + HuizhongLibrary + v4.0 + 512 + SAK + SAK + SAK + SAK + + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + bin\Debug\HuizhongLibrary.XML + x86 + + + MinimumRecommendedRules.ruleset + true + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + False + UsingDll\Aspose.Words.dll + + + UsingDll\BarcodeLib.dll + + + False + bin\Debug\bouncycastle.crypto.dll + + + False + .\DirectShowLib-2005.dll + + + False + UsingDll\LitJson.dll + + + False + bin\Debug\MySql.Data.dll + + + + False + UsingDll\NPOI.dll + + + UsingDll\NPOI.OOXML.dll + + + UsingDll\NPOI.OpenXml4Net.dll + + + UsingDll\O2S.Components.PDFRender4NET.dll + + + False + UsingDll\Oracle.ManagedDataAccess.dll + + + + + + + + + + + + + + + + + + + UsingDll\ThoughtWorks.QRCode.dll + + + UsingDll\websocket-sharp.dll + + + + UsingDll\zxing.ce2.0.dll + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + UserControl + + + AlphaLabel.cs + + + + + UserControl + + + MyPanel.cs + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Form + + + PrintSetup.cs + + + + True + True + Settings.settings + + + + + + + + + + + + + + + True + True + Reference.map + + + + + + + + + + AlphaLabel.cs + + + MyPanel.cs + + + PrintSetup.cs + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + Reference.map + + + MSDiscoCodeGenerator + Reference.cs + + + + + + + + + + + + Dynamic + Web References\US\ + http://47.114.82.162:7000/UpdateService.asmx + + + + + Settings + HuizhongLibrary_US_UpdateService + + + + + + + + + + + \ No newline at end of file diff --git a/基础类库/HuizhongLibrary/HuizhongLibrary.sln b/基础类库/HuizhongLibrary/HuizhongLibrary.sln new file mode 100644 index 0000000..4dfc77a --- /dev/null +++ b/基础类库/HuizhongLibrary/HuizhongLibrary.sln @@ -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 diff --git a/基础类库/HuizhongLibrary/JavaScriptConstant.cs b/基础类库/HuizhongLibrary/JavaScriptConstant.cs new file mode 100644 index 0000000..0cb9f0f --- /dev/null +++ b/基础类库/HuizhongLibrary/JavaScriptConstant.cs @@ -0,0 +1,814 @@ +using System; + +namespace HuizhongLibrary.Control +{ + /// + /// JavaScriptConstant ժҪ˵ + /// + public class JavaScriptConstant + { + #region ѡȫѡĽű + public static string jsCheckAll = @""; + + #endregion + #region ƶű + public static string divMove=@""; + #endregion + #region سƶű + public static string EnterMoveFocus= @""; + #endregion + #region ڿؼű + public static string DateMonth = @""; + #endregion + #region ӡű + public static string DoPrint = @""; + #endregion + #region ֻ븡Ľű + /* +ascii˵ +8˸ +46delete +37-40 +48-57С +96-105 +110190СС +189109Сĸ +13س +9 Tab ǸѽƵһıĶ + */ + public static string KeyDown_float = @""; + #endregion + #region ֻĽű + /* +ascii˵ +8˸ +46delete +37-40 +48-57С +96-105 +110190СС +189109Сĸ +13س +9 Tab ǸѽƵһıĶ + */ + public static string KeyDown_int = @""; + #endregion + #region ͻ˻شű + public static string doPostBack = @""; + #endregion + #region ֤ڵĽű + public static string CheckDateTime= @""; + #endregion + #region ֵ֤С + public static string CheckSize = @""; + #endregion + #region ʽֵ + public static string FormatNumber = @""; + #endregion + #region Ȩ + public static string PopedomSetting = @""; + #endregion + + + } +} diff --git a/基础类库/HuizhongLibrary/LedLibrary.cs b/基础类库/HuizhongLibrary/LedLibrary.cs new file mode 100644 index 0000000..c2859ce --- /dev/null +++ b/基础类库/HuizhongLibrary/LedLibrary.cs @@ -0,0 +1,1101 @@ +using System; +using System.Runtime.InteropServices; +using HuizhongLibrary.Log; + +namespace HuizhongLibrary +{ + public class LedLibrary + { + //定义回调 + public delegate void CallBack(string szMessagge, int nProgress); + //声明回调 + private CallBack callBack; + + [DllImport("BX_IV.dll")] + public static extern int Initialize(); //初始化动态库 + + [DllImport("BX_IV.dll")] + public static extern int Uninitialize(); //释放动态库 + + /*------------------------------------------------------------------------------- + 过程名: AddScreen + 向动态库中添加显示屏信息;该函数不与显示屏通讯,只用于动态库中的指定显示屏参数信息配置。 + 参数: + nControlType :显示屏的控制器型号;详见宏定义“控制器型号定义” + Controller_BX_5AT = 0x0051; + Controller_BX_5A0 = 0x0151; + Controller_BX_5A1 = 0x0251; + Controller_BX_5A2 = 0x0351; + Controller_BX_5A3 = 0x0451; + Controller_BX_5A4 = 0x0551; + Controller_BX_5A1_WIFI = 0x0651; + Controller_BX_5A2_WIFI = 0x0751; + Controller_BX_5A4_WIFI = 0x0851; + Controller_BX_5A = 0x0951; + Controller_BX_5A2_RF = 0x1351; + Controller_BX_5A4_RF = 0x1551; + Controller_BX_5AT_WIFI = 0x1651; + Controller_BX_5AL = 0x1851; + + Controller_AX_AT = 0x2051; + Controller_AX_A0 = 0x2151; + + Controller_BX_5MT = 0x0552; + Controller_BX_5M1 = 0x0052; + Controller_BX_5M1X = 0x0152; + Controller_BX_5M2 = 0x0252; + Controller_BX_5M3 = 0x0352; + Controller_BX_5M4 = 0x0452; + + Controller_BX_5E1 = 0x0154; + Controller_BX_5E2 = 0x0254; + Controller_BX_5E3 = 0x0354; + + Controller_BX_5UT = 0x0055; + Controller_BX_5U0 = 0x0155; + Controller_BX_5U1 = 0x0255; + Controller_BX_5U2 = 0x0355; + Controller_BX_5U3 = 0x0455; + Controller_BX_5U4 = 0x0555; + Controller_BX_5U5 = 0x0655; + Controller_BX_5U = 0x0755; + Controller_BX_5UL = 0x0855; + + Controller_AX_UL = 0x2055; + Controller_AX_UT = 0x2155; + Controller_AX_U0 = 0x2255; + Controller_AX_U1 = 0x2355; + Controller_AX_U2 = 0x2455; + + Controller_BX_5Q0 = 0x0056; + Controller_BX_5Q1 = 0x0156; + Controller_BX_5Q2 = 0x0256; + Controller_BX_5Q0P = 0x1056; + Controller_BX_5Q1P = 0x1156; + Controller_BX_5Q2P = 0x1256; + Controller_BX_5QL = 0x1356; + + Controller_BX_5QS1 = 0x0157; + Controller_BX_5QS2 = 0x0257; + Controller_BX_5QS = 0x0357; + Controller_BX_5QS1P = 0x1157; + Controller_BX_5QS2P = 0x1257; + Controller_BX_5QSP = 0x1357; + nScreenNo :显示屏屏号;该参数与LedshowTW 2013软件中"设置屏参"模块的"屏号"参数一致。 + nSendMode :与显示屏的通讯模式; + 0:串口模式、BX-5A2&RF、BX-5A4&RF等控制器为RF串口无线模式; + 1:GPRS模式 + 2:网络模式 + 4:WiFi模式 + 5:ONBON服务器-GPRS + 6:ONBON服务器-3G + nWidth :显示屏宽度 16的整数倍;最小64;BX-5E系列最小为80 + nHeight :显示屏高度 16的整数倍;最小16; + nScreenType :显示屏类型;1:单基色;2:双基色; + 3:双基色;注意:该显示屏类型只有BX-4MC支持;同时该型号控制器不支持其它显示屏类型。 + 4:全彩色;注意:该显示屏类型只有BX-5Q系列支持;同时该型号控制器不支持其它显示屏类型。 + 5:双基色灰度;注意:该显示屏类型只有BX-5QS支持;同时该型号控制器不支持其它显示屏类型。 + nPixelMode :点阵类型;1:R+G;2:G+R;该参数只对双基色屏有效 ;默认为2; + nDataDA :数据极性;,0x00:数据低有效,0x01:数据高有效;默认为0; + nDataOE :OE极性; 0x00:OE 低有效;0x01:OE 高有效;默认为0; + nRowOrder :行序模式;0:正常;1:加1行;2:减1行;默认为0; + nFreqPar :扫描点频;0~6;默认为0; + pCom :串口名称;串口通讯模式时有效;例:COM1 + nBaud :串口波特率:目前支持9600、57600;默认为57600; + pSocketIP :控制卡IP地址,网络通讯模式时有效;例:192.168.0.199; + 本动态库网络通讯模式时只支持固定IP模式,单机直连和网络服务器模式不支持。 + nSocketPort :控制卡网络端口;网络通讯模式时有效;例:5005 + nServerMode :0:服务器模式未启动;1:服务器模式启动。 + pBarcode :设备条形码 + pNetworkID :服务器模式时的网络ID编号 + pServerIP :中转服务器IP地址 + nServerPort :中转服务器网络端口 + pServerAccessUser:中转服务器访问用户名 + pServerAccessPassword:中转服务器访问密码 + pWiFiIP :控制器WiFi模式的IP地址信息;WiFi通讯模式时有效;例:192.168.100.1 + nWiFiPort :控制卡WiFi端口;WiFi通讯模式时有效;例:5005 + pGprsIP :GPRS服务器IP地址 + nGprsPort :GPRS服务器端口 + pGprsID :GPRS编号 + pScreenStatusFile:用于保存查询到的显示屏状态参数保存的INI文件名; + 只有执行查询显示屏状态GetScreenStatus时,该参数才有效 + pCallBack :返回发送的消息和进度 + 类型为 TCallBackFunc = procedure(szMessagge:string;nProgress:integer); stdcall; + 返回值 :详见返回状态代码定义。 + -------------------------------------------------------------------------------*/ + [DllImport("BX_IV.dll")] + public static extern int AddScreen(int nControlType, int nScreenNo, int nSendMode, + int nWidth, int nHeight, int nScreenType, int nPixelMode, int nDataDA, + int nDataOE, int nRowOrder, int nFreqPar, int DataFlow, string pCom, int nBaud, + string pSocketIP, int nSocketPort, int nServerMode, string pBarcode, string pNetworkID, + string pServerIP, int nServerPort, string pServerAccessUser, string pServerAccessPassword, + string pWiFiIP, int nWiFiPort, string pGprsIP, int nGprsPort, string pGprsID, string pScreenStatusFile, CallBack pCallBack); //添加屏显 + + /*------------------------------------------------------------------------------- + 过程名: DeleteScreen + 删除指定显示屏信息,删除显示屏成功后会将该显示屏下所有节目信息从动态库中删除。 + 该函数不与显示屏通讯,只用于动态库中的指定显示屏参数信息配置。 + 参数: + nScreenNo :显示屏屏号;该参数与AddScreen函数中的nScreenNo参数对应。 + 返回值 :详见返回状态代码定义。 + -------------------------------------------------------------------------------}*/ + [DllImport("BX_IV.dll")] + public static extern int DeleteScreen(int nScreenNo);//删除屏显 + /*------------------------------------------------------------------------------- + 过程名: SendScreenInfo + 通过指定的通讯模式,发送相应信息、命令到显示屏。该函数与显示屏进行通讯 + 参数: + nScreenNo :显示屏屏号;该参数与AddScreen函数中的nScreenNo参数对应。 + nSendCmd :通讯命令值 + SEND_CMD_PARAMETER =41471; 加载屏参数。 + SEND_CMD_SENDALLPROGRAM = 41456; 发送所有节目信息。 + SEND_CMD_POWERON =41727; 强制开机 + SEND_CMD_POWEROFF = 41726; 强制关机 + SEND_CMD_TIMERPOWERONOFF = 41725; 定时开关机 + SEND_CMD_CANCEL_TIMERPOWERONOFF = 41724; 取消定时开关机 + SEND_CMD_RESIVETIME = 41723; 校正时间。 + SEND_CMD_ADJUSTLIGHT = 41722; 亮度调整。 + nOtherParam1 :保留参数;0 + 返回值 :详见返回状态代码定义。 + -------------------------------------------------------------------------------*/ + [DllImport("BX_IV.dll")] + public static extern int SendScreenInfo(int nScreenNo, int nSendCmd, int nOtherParam1);//发送相应命令到显示屏。 + + /*------------------------------------------------------------------------------- + 过程名: AddScreenProgram + 向动态库中指定显示屏添加节目;该函数不与显示屏通讯,只用于动态库中的指定显示屏节目信息配置。 + 参数: + nScreenNo :显示屏屏号;该参数与AddScreen函数中的nScreenNo参数对应。 + nProgramType :节目类型;0正常节目。 + nPlayLength :0:表示自动顺序播放;否则表示节目播放的长度;范围1~65535;单位秒 + nStartYear :节目的生命周期;开始播放时间年份。如果为无限制播放的话该参数值为65535;如2010 + nStartMonth :节目的生命周期;开始播放时间月份。如11 + nStartDay :节目的生命周期;开始播放时间日期。如26 + nEndYear :节目的生命周期;结束播放时间年份。如2011 + nEndMonth :节目的生命周期;结束播放时间月份。如11 + nEndDay :节目的生命周期;结束播放时间日期。如26 + nMonPlay :节目在生命周期内星期一是否播放;0:不播放;1:播放. + nTuesPlay :节目在生命周期内星期二是否播放;0:不播放;1:播放. + nWedPlay :节目在生命周期内星期二是否播放;0:不播放;1:播放. + nThursPlay :节目在生命周期内星期二是否播放;0:不播放;1:播放. + bFriPlay :节目在生命周期内星期二是否播放;0:不播放;1:播放. + nSatPlay :节目在生命周期内星期二是否播放;0:不播放;1:播放. + nSunPlay :节目在生命周期内星期二是否播放;0:不播放;1:播放. + nStartHour :节目在当天开始播放时间小时。如8 + nStartMinute :节目在当天开始播放时间分钟。如0 + nEndHour :节目在当天结束播放时间小时。如18 + nEndMinute :节目在当天结束播放时间分钟。如0 + 返回值 :详见返回状态代码定义。 + -------------------------------------------------------------------------------*/ + [DllImport("BX_IV.dll")] + public static extern int AddScreenProgram(int nScreenNo, int nProgramType, int nPlayLength, + int nStartYear, int nStartMonth, int nStartDay, int nEndYear, int nEndMonth, int nEndDay, + int nMonPlay, int nTuesPlay, int nWedPlay, int nThursPlay, int bFriPlay, int nSatPlay, int nSunPlay, + int nStartHour, int nStartMinute, int nEndHour, int nEndMinute); //向指定显示屏添加节目; + + /*------------------------------------------------------------------------------- + 过程名: DeleteScreenProgram + 删除指定显示屏指定节目,删除节目成功后会将该节目下所有区域信息删除。 + 该函数不与显示屏通讯,只用于动态库中的指定显示屏指定节目信息配置。 + 参数: + nScreenNo :显示屏屏号;该参数与AddScreen函数中的nScreenNo参数对应。 + nProgramOrd :节目序号;该序号按照节目添加顺序,从0顺序递增,如删除中间的节目,后面的节目序号自动填充。 + 返回值 :详见返回状态代码定义。 + -------------------------------------------------------------------------------*/ + [DllImport("BX_IV.dll")] + public static extern int DeleteScreenProgram(int nScreenNo, int nProgramOrd); //删除节目 + + /*------------------------------------------------------------------------------- + 过程名: DeleteScreenProgramArea + 删除指定显示屏指定节目的指定区域,删除区域成功后会将该区域下所有信息删除。 + 该函数不与显示屏通讯,只用于动态库中指定显示屏指定节目中指定的区域信息配置。 + 参数: + nScreenNo :显示屏屏号;该参数与AddScreen函数中的nScreenNo参数对应。 + nProgramOrd :节目序号;该序号按照节目添加顺序,从0顺序递增,如删除中间的节目,后面的节目序号自动填充。 + nAreaOrd :区域序号;该序号按照区域添加顺序,从0顺序递增,如删除中间的区域,后面的区域序号自动填充。 + 返回值 :详见返回状态代码定义。 + -------------------------------------------------------------------------------*/ + [DllImport("BX_IV.dll")] + public static extern int DeleteScreenProgramArea(int nScreenNo, int nProgramOrd, int nAreaOrd);//删除区域 + + /*------------------------------------------------------------------------------- + 过程名: AddScreenProgramBmpTextArea: + 向动态库中指定显示屏的指定节目添加图文区域;该函数不与显示屏通讯,只用于动态库中的指定显示屏指定节目中的图文区域信息配置。 + 参数: + nScreenNo :显示屏屏号;该参数与AddScreen函数中的nScreenNo参数对应。 + nProgramOrd :节目序号;该序号按照节目添加顺序,从0顺序递增,如删除中间的节目,后面的节目序号自动填充。 + nX :区域的横坐标;显示屏的左上角的横坐标为0;最小值为0 + nY :区域的纵坐标;显示屏的左上角的纵坐标为0;最小值为0 + nWidth :区域的宽度;最大值不大于显示屏宽度-nX + nHeight :区域的高度;最大值不大于显示屏高度-nY + 返回值 :详见返回状态代码定义。 + -------------------------------------------------------------------------------*/ + [DllImport("BX_IV.dll")] + public static extern int AddScreenProgramBmpTextArea(int nScreenNo, int nProgramOrd, int nX, int nY, + int nWidth, int nHeight);//向指定显示屏指定节目添加图文区; + + /*------------------------------------------------------------------------------- + 过程名: AddScreenProgramAreaBmpTextFile + 向动态库中指定显示屏的指定节目的指定图文区域添加文件; + 该函数不与显示屏通讯,只用于动态库中的指定显示屏指定节目中指定图文区域的文件信息配置。 + 参数: + nScreenNo :显示屏屏号;该参数与AddScreen函数中的nScreenNo参数对应。 + nProgramOrd :节目序号;该序号按照节目添加顺序,从0顺序递增,如删除中间的节目,后面的节目序号自动填充。 + nAreaOrd :区域序号;该序号按照区域添加顺序,从0顺序递增,如删除中间的区域,后面的区域序号自动填充。 + pFileName :文件名称 支持.bmp,jpg,jpeg,rtf,txt等文件类型。 + nShowSingle :单、多行显示;1:单行显示;0:多行显示;该参数只有在pFileName为txt类型文件时该参数才有效。 + pFontName :字体名称;支持当前操作系统已经安装的矢量字库;该参数只有pFileName为txt类型文件时该参数才有效。 + nFontSize :字体字号;支持当前操作系统的字号;该参数只有pFileName为txt类型文件时该参数才有效。 + nBold :字体粗体;支持1:粗体;0:正常;该参数只有pFileName为txt类型文件时该参数才有效。 + nFontColor :字体颜色;该参数只有pFileName为txt类型文件时该参数才有效。 + nStunt :显示特技。 + 0x00:随机显示 + 0x01:静态 + 0x02:快速打出 + 0x03:向左移动 + 0x04:向左连移 + 0x05:向上移动 3T类型控制卡无此特技 + 0x06:向上连移 3T类型控制卡无此特技 + 0x07:闪烁 3T类型控制卡无此特技 + 0x08:飘雪 + 0x09:冒泡 + 0x0A:中间移出 + 0x0B:左右移入 + 0x0C:左右交叉移入 + 0x0D:上下交叉移入 + 0x0E:画卷闭合 + 0x0F:画卷打开 + 0x10:向左拉伸 + 0x11:向右拉伸 + 0x12:向上拉伸 + 0x13:向下拉伸 3T类型控制卡无此特技 + 0x14:向左镭射 + 0x15:向右镭射 + 0x16:向上镭射 + 0x17:向下镭射 + 0x18:左右交叉拉幕 + 0x19:上下交叉拉幕 + 0x1A:分散左拉 + 0x1B:水平百页 3T、3A、4A、3A1、3A2、4A1、4A2、4A3、4AQ类型控制卡无此特技 + 0x1C:垂直百页 3T、3A、4A、3A1、3A2、4A1、4A2、4A3、4AQ、3M、4M、4M1、4MC类型控制卡无此特技 + 0x1D:向左拉幕 3T、3A、4A类型控制卡无此特技 + 0x1E:向右拉幕 3T、3A、4A类型控制卡无此特技 + 0x1F:向上拉幕 3T、3A、4A类型控制卡无此特技 + 0x20:向下拉幕 3T、3A、4A类型控制卡无此特技 + 0x21:左右闭合 3T类型控制卡无此特技 + 0x22:左右对开 3T类型控制卡无此特技 + 0x23:上下闭合 3T类型控制卡无此特技 + 0x24:上下对开 3T类型控制卡无此特技 + 0x25:向右连移 + 0x26:向右连移 + 0x27:向下移动 3T类型控制卡无此特技 + 0x28:向下连移 3T类型控制卡无此特技 + nRunSpeed :运行速度;0~63;值越大运行速度越慢。 + nShowTime :停留时间;0~65525;单位0.5秒 + + 返回值: :详见返回状态代码定义。 + -------------------------------------------------------------------------------*/ + [DllImport("BX_IV.dll")] + public static extern int AddScreenProgramAreaBmpTextFile(int nScreenNo, int nProgramOrd, int nAreaOrd, + string pFileName, int nShowSingle, string pFontName, int nFontSize, int nBold, int nFontColor, + int nStunt, int nRunSpeed, int nShowTime); //向指定显示屏指定节目指定区域添加文件 + + /*------------------------------------------------------------------------------- + 过程名: AddScreenProgramAreaBmpTextText + 向动态库中指定显示屏的指定节目的指定图文区域添加文本; + 该函数不与显示屏通讯,只用于动态库中的指定显示屏指定节目中指定图文区域的文件信息配置。 + 参数: + nScreenNo :显示屏屏号;该参数与AddScreen函数中的nScreenNo参数对应。 + nProgramOrd :节目序号;该序号按照节目添加顺序,从0顺序递增,如删除中间的节目,后面的节目序号自动填充。 + nAreaOrd :区域序号;该序号按照区域添加顺序,从0顺序递增,如删除中间的区域,后面的区域序号自动填充。 + pText :文本 + nShowSingle :单、多行显示;1:单行显示;0:多行显示;该参数只有在pFileName为txt类型文件时该参数才有效。 + pFontName :字体名称;支持当前操作系统已经安装的矢量字库;该参数只有pFileName为txt类型文件时该参数才有效。 + nFontSize :字体字号;支持当前操作系统的字号;该参数只有pFileName为txt类型文件时该参数才有效。 + nBold :字体粗体;支持1:粗体;0:正常;该参数只有pFileName为txt类型文件时该参数才有效。 + nFontColor :字体颜色;该参数只有pFileName为txt类型文件时该参数才有效。 + nStunt :显示特技。 + 0x00:随机显示 + 0x01:静态 + 0x02:快速打出 + 0x03:向左移动 + 0x04:向左连移 + 0x05:向上移动 3T类型控制卡无此特技 + 0x06:向上连移 3T类型控制卡无此特技 + 0x07:闪烁 3T类型控制卡无此特技 + 0x08:飘雪 + 0x09:冒泡 + 0x0A:中间移出 + 0x0B:左右移入 + 0x0C:左右交叉移入 + 0x0D:上下交叉移入 + 0x0E:画卷闭合 + 0x0F:画卷打开 + 0x10:向左拉伸 + 0x11:向右拉伸 + 0x12:向上拉伸 + 0x13:向下拉伸 3T类型控制卡无此特技 + 0x14:向左镭射 + 0x15:向右镭射 + 0x16:向上镭射 + 0x17:向下镭射 + 0x18:左右交叉拉幕 + 0x19:上下交叉拉幕 + 0x1A:分散左拉 + 0x1B:水平百页 3T、3A、4A、3A1、3A2、4A1、4A2、4A3、4AQ类型控制卡无此特技 + 0x1C:垂直百页 3T、3A、4A、3A1、3A2、4A1、4A2、4A3、4AQ、3M、4M、4M1、4MC类型控制卡无此特技 + 0x1D:向左拉幕 3T、3A、4A类型控制卡无此特技 + 0x1E:向右拉幕 3T、3A、4A类型控制卡无此特技 + 0x1F:向上拉幕 3T、3A、4A类型控制卡无此特技 + 0x20:向下拉幕 3T、3A、4A类型控制卡无此特技 + 0x21:左右闭合 3T类型控制卡无此特技 + 0x22:左右对开 3T类型控制卡无此特技 + 0x23:上下闭合 3T类型控制卡无此特技 + 0x24:上下对开 3T类型控制卡无此特技 + 0x25:向右连移 + 0x26:向右连移 + 0x27:向下移动 3T类型控制卡无此特技 + 0x28:向下连移 3T类型控制卡无此特技 + nRunSpeed :运行速度;0~63;值越大运行速度越慢。 + nShowTime :停留时间;0~65525;单位0.5秒 + + 返回值: :详见返回状态代码定义。 +-------------------------------------------------------------------------------*/ + [DllImport("BX_IV.dll")] + public static extern int AddScreenProgramAreaBmpTextText(int nScreenNo, int nProgramOrd, int nAreaOrd, + string pText, int nShowSingle, string pFontName, int nFontSize, int nBold, int nFontColor, + int nStunt, int nRunSpeed, int nShowTime); + + /*------------------------------------------------------------------------------- + 过程名: DeleteScreenProgramAreaBmpTextFile + 删除指定显示屏指定节目指定图文区域的指定文件,删除文件成功后会将该文件信息删除。 + 该函数不与显示屏通讯,只用于动态库中的指定显示屏指定节目指定区域中的指定文件信息配置。 + 参数: + nScreenNo :显示屏屏号;该参数与AddScreen函数中的nScreenNo参数对应。 + nProgramOrd :节目序号;该序号按照节目添加顺序,从0顺序递增,如删除中间的节目,后面的节目序号自动填充。 + nAreaOrd :区域序号;该序号按照区域添加顺序,从0顺序递增,如删除中间的区域,后面的区域序号自动填充。 + nFileOrd :文件序号;该序号按照文件添加顺序,从0顺序递增,如删除中间的文件,后面的文件序号自动填充。 + 返回值 :详见返回状态代码定义。 + -------------------------------------------------------------------------------*/ + [DllImport("BX_IV.dll")] + public static extern int DeleteScreenProgramAreaBmpTextFile(int nScreenNo, int nProgramOrd, int nAreaOrd, int nFileOrd); //删除指定显示屏指定节目指定图文区域的指定文件,删除文件成功后会将该文件信息删除 + + /*------------------------------------------------------------------------------- + 过程名: QuerryServerDeviceList + 查询中转服务器设备的列表信息。 + 该函数与显示屏进行通讯 + 参数: nScreenNo, nSendMode: Integer + nScreenNo :显示屏屏号;该参数与AddScreen函数中的nScreenNo参数对应。 + nSendMode :与显示屏的通讯模式; + 0:串口模式、BX-5A2&RF、BX-5A4&RF等控制器为RF串口无线模式; + 2:网络模式; + 4:WiFi模式 + 5:ONBON服务器-GPRS + 6:ONBON服务器-3G + pDeviceList : 保存查询的设备列表信息 + 将设备的信息用组成字符串, 比如: + 设备1:名称 条形码 状态 类型 网络ID + 设备2:名称 条形码 状态 类型 网络ID + 组成字符串为:'设备1名称,设备1条形码,设备1状态,设备1类型,设备1网络ID;设备2名称,设备2条形码,设备2状态,设备2类型,设备2网络ID' + 设备状态(Byte): $10:设备未知 + $11:设备在线 + $12:设备不在线 + + 设备类型(Byte): $16:设备为2G + $17:设备为3G + pDeviceCount : 查询的设备个数 + + 返回值 :详见返回状态代码定义。 + -------------------------------------------------------------------------------*/ + [DllImport("BX_IV.dll")] + public static extern int QuerryServerDeviceList(int nScreenNo, int nSendMode, byte[] pDeviceList, ref int nDeviceCount); + + /*------------------------------------------------------------------------------- + 过程名: BindServerDevice + 绑定中转服务器设备。 + 该函数不与显示屏进行通讯 + 参数: nScreenNo, nSendMode: Integer + nScreenNo :显示屏屏号;该参数与AddScreen函数中的nScreenNo参数对应。 + pBarcode :绑定设备的条形码; + pNetworkId :绑定设备的网络ID; + + 返回值 :详见返回状态代码定义。 + -------------------------------------------------------------------------------*/ + [DllImport("BX_IV.dll")] + public static extern int BindServerDevice(int nScreenNo, string pBarcode, string pNetworkId); + + private const int RETURN_ERROR_AERETYPE = 0xF7;//区域类型错误,在添加、删除图文区域文件时区域类型出错返回此类型错误。 + private const int RETURN_ERROR_RA_SCREENNO = 0xF8; //已经有该显示屏信息。如要重新设定请先DeleteScreen删除该显示屏再添加; + private const int RETURN_ERROR_NOFIND_AREAFILE = 0xF9; //没有找到有效的区域文件(图文区域); + private const int RETURN_ERROR_NOFIND_AREA = 0xFA; //没有找到有效的显示区域;可以使用AddScreenProgramBmpTextArea添加区域信息。 + private const int RETURN_ERROR_NOFIND_PROGRAM = 0xFB; //没有找到有效的显示屏节目;可以使用AddScreenProgram函数添加指定节目 + private const int RETURN_ERROR_NOFIND_SCREENNO = 0xFC; //系统内没有查找到该显示屏;可以使用AddScreen函数添加显示屏 + private const int RETURN_ERROR_NOW_SENDING = 0xFD; //系统内正在向该显示屏通讯,请稍后再通讯; + private const int RETURN_ERROR_OTHER = 0xFF; //其它错误; + private const int RETURN_NOERROR = 0; //没有错误 + + /*------------------------------------------------------------------------------- + 过程名: SetScreenAdjustLight + 设定显示屏的亮度调整参数,该函数可设置手工调亮和定时调亮两种模式。该函数不与显示屏通讯, + 只用于动态库中对指定显示屏的亮度调整信息配置。如需将设定的亮度调整值发送到显示屏上, + 只需使用SendScreenInfo函数发送亮度调整命令即可。 + 参数: + nScreenNo :显示屏屏号;该参数与AddScreen函数中的nScreenNo参数对应。 + nAdjustType :亮度调整类型;0:手工调亮;1:定时调亮 + nHandleLight:手工调亮的亮度值,只有nAdjustType=0时该参数有效。 + nHour1 :第一组定时调亮时间的小时 + nMinute1 :第一组定时调亮时间的分钟 + nLight1 :第一组定时调亮的亮度值 + nHour2 :第二组定时调亮时间的小时 + nMinute2 :第二组定时调亮时间的分钟 + nLight2 :第二组定时调亮的亮度值 + nHour3 :第三组定时调亮时间的小时 + nMinute3 :第三组定时调亮时间的分钟 + nLight3 :第三组定时调亮的亮度值 + nHour4 :第四组定时调亮时间的小时 + nMinute4 :第四组定时调亮时间的分钟 + nLight4 :第四组定时调亮的亮度值 + 返回值 :详见返回状态代码定义。 + -------------------------------------------------------------------------------*/ + + + [DllImport("BX_IV.dll")] + public static extern int SetScreenAdjustLight(int nScreenNo, int nAdjustType, int nHandleLight, + int nHour1, int nMinute1, int nLight1, + int nHour2, int nMinute2, int nLight2, + int nHour3, int nMinute3, int nLight3, + int nHour4, int nMinute4, int nLight4); + + /*------------------------------------------------------------------------------- + 过程名: SetScreenTimerPowerONOFF + 设定显示屏的定时开关机参数,可以设置3组开关机时间。该函数不与显示屏通讯, + 只用于动态库中对指定显示屏的定时开关机信息配置。如需将设定的定时开关值发送到显示屏上, + 只需使用SendScreenInfo函数发送定时开关命令即可。 + 参数: + nScreenNo :显示屏屏号;该参数与AddScreen函数中的nScreenNo参数对应。 + nOnHour1 :第一组定时开关的开机时间的小时 + nOnMinute1 :第一组定时开关的开机时间的分钟 + nOffHour1 :第一组定时开关的关机时间的小时 + nOffMinute1 :第一组定时开关的关机时间的分钟 + nOnHour2 :第二组定时开关的开机时间的小时 + nOnMinute2 :第二组定时开关的开机时间的分钟 + nOffHour2 :第二组定时开关的关机时间的小时 + nOffMinute2 :第二组定时开关的关机时间的分钟 + nOnHour3 :第三组定时开关的开机时间的小时 + nOnMinute3 :第三组定时开关的开机时间的分钟 + nOffHour3 :第三组定时开关的关机时间的小时 + nOffMinute3 :第三组定时开关的关机时间的分钟 + 返回值 :详见返回状态代码定义。 + -------------------------------------------------------------------------------*/ + [DllImport("BX_IV.dll")] + public static extern int SetScreenTimerPowerONOFF(int nScreenNo, + int nOnHour1, int nOnMinute1, int nOffHour1, int nOffMinute1, + int nOnHour2, int nOnMinute2, int nOffHour2, int nOffMinute2, + int nOnHour3, int nOnMinute3, int nOffHour3, int nOffMinute3); + /* + 过程名: AddScreenProgramTimeArea + 向动态库中指定显示屏的指定节目添加时间区域;该函数不与显示屏通讯,只用于动态库中的指定显示屏指定节目中的时间区域信息配置。 + 参数: + nScreenNo :显示屏屏号;该参数与AddScreen函数中的nScreenNo参数对应。 + nProgramOrd :节目序号;该序号按照节目添加顺序,从0顺序递增,如删除中间的节目,后面的节目序号自动填充。 + nX :区域的横坐标;显示屏的左上角的横坐标为0;最小值为0 + nY :区域的纵坐标;显示屏的左上角的纵坐标为0;最小值为0 + nWidth :区域的宽度;最大值不大于显示屏宽度-nX + nHeight :区域的高度;最大值不大于显示屏高度-nY + 返回值 :详见返回状态代码定义。 + -----------------------------------------------------------------------------*/ + [DllImport("BX_IV.dll")] + public static extern int AddScreenProgramTimeArea(int nScreenNo, + int nProgramOrd, int nX, int nY, int nWidth, int nHeight); + + /*-------------------------------------------------------------------------- + 过程名: AddScreenProgramTimeAreaFile + 向动态库中指定显示屏的指定节目的指定时间区域属性;该函数不与显示屏通讯, + 只用于动态库中的指定显示屏指定节目中指定时间区域属性信息配置。 + 参数: + nScreenNo :显示屏屏号;该参数与AddScreen函数中的nScreenNo参数对应。 + nProgramOrd :节目序号;该序号按照节目添加顺序,从0顺序递增,如删除中间的节目,后面的节目序号自动填充。 + nAreaOrd :区域序号;该序号按照区域添加顺序,从0顺序递增,如删除中间的区域,后面的区域序号自动填充。 + pInputtxt :固定文字 + pFontName :文字的字体 + nSingal :单行多行,0为单行 1为多行,单行模式下nAlign不起作用 + nAlign :文字对齐模式,对多行有效,0为左1为中2为右 + nFontSize :文字的大小 + nBold :是否加粗,0为不1为是 + nItalic :是否斜体,0为不1为是 + nUnderline :是否下滑线,0为不1为是 + nUsetxt :是否使用固定文字,0为不1为是 + nTxtcolor :固定文字颜色,传递颜色的10进制 红255 绿65280 黄65535 + nUseymd :是否使用年月日,0为不1为是 + nYmdstyle :年月日格式,详见使用说明文档的附件1 + nYmdcolor :年月日颜色,传递颜色的10进制 + nUseweek :是否使用星期,0为不1为是 + nWeekstyle :星期格式,详见使用说明文档的附件1 + nWeekcolor :星期颜色,传递颜色的10进制 + nUsehns :是否使用时分秒,0为不1是 + nHnsstyle :时分秒格式,详见使用说明文档的附件1 + nHnscolor :时分秒颜色,传递颜色的10进制 + nAutoset :是否自动设置大小对应宽度,0为不1为是(默认不使用) + 返回值 :详见返回状态代码定义。 + -------------------------------------------------------------------------------} + ---------------------------------------------------------------------------------*/ + [DllImport("BX_IV.dll")] + public static extern int AddScreenProgramTimeAreaFile(int nScreenNo, int nProgramOrd, int nAreaOrd, + string pInputtxt, string pFontName, + int nSingal, int nAlign, int nFontSize, int nBold, int nItalic, int nUnderline, + int nUsetxt, int nTxtcolor, + int nUseymd, int nYmdstyle, int nYmdcolor, + int nUseweek, int nWeekstyle, int nWeekcolor, + int nUsehns, int nHnsstyle, int nHnscolor, int nAutoset); + + /*----------------------------------------------------------------------- + 过程名: AddScreenProgramLunarArea + 向动态库中指定显示屏的指定节目添加农历区域;该函数不与显示屏通讯,只用于动态库中的指定显示屏指定节目中的农历区域信息配置。 + 参数: + nScreenNo :显示屏屏号;该参数与AddScreen函数中的nScreenNo参数对应。 + nProgramOrd :节目序号;该序号按照节目添加顺序,从0顺序递增,如删除中间的节目,后面的节目序号自动填充。 + nX :区域的横坐标;显示屏的左上角的横坐标为0;最小值为0 + nY :区域的纵坐标;显示屏的左上角的纵坐标为0;最小值为0 + nWidth :区域的宽度;最大值不大于显示屏宽度-nX + nHeight :区域的高度;最大值不大于显示屏高度-nY + 返回值 :详见返回状态代码定义。 + ---------------------------------------------------------------------------} + ------------------------------------------------------------------------- * */ + [DllImport("BX_IV.dll")] + public static extern int AddScreenProgramLunarArea(int nScreenNo, int nProgramOrd, + int nX, int nY, int nWidth, int nHeight); + + /*------------------------------------------------------------------------------- + 过程名: AddScreenProgramLunarAreaFile + 向动态库中指定显示屏的指定节目的指定农历区域属性;该函数不与显示屏通讯, + 只用于动态库中的指定显示屏指定节目中指定农历区域属性信息配置。 + 参数: + nScreenNo :显示屏屏号;该参数与AddScreen函数中的nScreenNo参数对应。 + nProgramOrd :节目序号;该序号按照节目添加顺序,从0顺序递增,如删除中间的节目,后面的节目序号自动填充。 + nAreaOrd :区域序号;该序号按照区域添加顺序,从0顺序递增,如删除中间的区域,后面的区域序号自动填充。 + pInputtxt :固定文字 + pFontName :文字的字体 + nSingal :单行多行,0为单行 1为多行,单行模式下nAlign不起作用 + nAlign :文字对齐模式,对多行有效,0为左1为中2为右 + nFontSize :文字的大小 + nBold :是否加粗,0为不1为是 + nItalic :是否斜体,0为不1为是 + nUnderline :是否下滑线,0为不1为是 + nUsetxt :是否使用固定文字,0为不1为是 + nTxtcolor :固定文字颜色,传递颜色的10进制 + nUseyear :是否使用天干,0为不1为是 (辛卯兔年) + nYearcolor :天干颜色,传递颜色的10进制 + nUsemonth :是否使用农历,0为不1为是 (九月三十) + nMonthcolor :农历颜色,传递颜色的10进制 + nUsesolar :是否使用节气,0为不1是 + nSolarcolor :节气颜色,传递颜色的10进制 + nAutoset :是否自动设置大小对应宽度,0为不1为是(默认不使用) + 返回值 :详见返回状态代码定义。 + -----------------------------------------------------------------------} + -----------------------------------------------------------------------* */ + [DllImport("BX_IV.dll")] + public static extern int AddScreenProgramLunarAreaFile(int nScreenNo, int nProgramOrd, int nAreaOrd, + string pInputtxt, string pFontName, + int nSingal, int nAlign, int nFontSize, int nBold, int nItalic, int nUnderline, + int nUsetxt, int nTxtcolor, int nUseyear, int nYearcolor, int nUsemonth, int nMonthcolor, + int nUsesolar, int nSolarcolor, int nAutoset); + /*---------------------------------------------------------------------------- + 过程名: AddScreenProgramClockArea + 向动态库中指定显示屏的指定节目添加表盘区域;该函数不与显示屏通讯,只用于动态库中的指定显示屏指定节目中的表盘区域信息配置。 + 参数: + nScreenNo :显示屏屏号;该参数与AddScreen函数中的nScreenNo参数对应。 + nProgramOrd :节目序号;该序号按照节目添加顺序,从0顺序递增,如删除中间的节目,后面的节目序号自动填充。 + nX :区域的横坐标;显示屏的左上角的横坐标为0;最小值为0 + nY :区域的纵坐标;显示屏的左上角的纵坐标为0;最小值为0 + nWidth :区域的宽度;最大值不大于显示屏宽度-nX + nHeight :区域的高度;最大值不大于显示屏高度-nY + 返回值 :详见返回状态代码定义。 + -------------------------------------------------------------------------------} + -------------------------------------------------------------------------------* */ + [DllImport("BX_IV.dll")] + public static extern int AddScreenProgramClockArea(int nScreenNo, int nProgramOrd, + int nX, int nY, int nWidth, int nHeight); + + /*------------------------------------------------------------------------- + {------------------------------------------------------------------------------- + 过程名: AddScreenProgramClockAreaFile + 向动态库中指定显示屏的指定节目的指定表盘区域属性;该函数不与显示屏通讯, + 只用于动态库中的指定显示屏指定节目中指定表盘区域属性信息配置。 + 参数: + nScreenNo :显示屏屏号;该参数与AddScreen函数中的nScreenNo参数对应。 + nProgramOrd :节目序号;该序号按照节目添加顺序,从0顺序递增,如删除中间的节目,后面的节目序号自动填充。 + nAreaOrd :区域序号;该序号按照区域添加顺序,从0顺序递增,如删除中间的区域,后面的区域序号自动填充。 + nusetxt :是否使用固定文字 0为不1为是 + nusetime :是否使用年月日时间 0为不1为是 + nuseweek :是否使用星期 0为不1为是 + ntimeStyle :年月日时间格式,参考时间区的表格说明 + nWeekStyle :星期时间格式,参考时间区的表格说明 + ntxtfontsize :固定文字的字大小 + ntxtfontcolor :固定文字的颜色;传递颜色的10进制;红255绿65280黄65535 + ntxtbold :固定文字是否加粗 0为不1为是 + ntxtitalic :固定文字是否斜体 0为不1为是 + ntxtunderline :固定文字是否下划线 0为不1为是 + txtleft :固定文字在表盘区域中的X坐标 + txttop :固定文字在表盘区域中的Y坐标 + ntimefontsize :年月日文字的字大小 + ntimefontcolor:年月日文字的颜色; 传递颜色的10进制 + ntimebold :年月日文字是否加粗 0为不1为是 + ntimeitalic :年月日文字是否斜体 0为不1为是 + ntimeunderline:年月日文字是否下划线 0为不1为是 + timeleft :年月日文字在表盘区域中的X坐标 + timetop :年月日文字在表盘区域中的X坐标 + nweekfontsize :星期文字的字大小 + nweekfontcolor:星期文字的颜色;传递颜色的10进制 + nweekbold :星期文字是否加粗 0为不1为是 + nweekitalic :星期文字是否斜体 0为不1为是 + nweekunderline:星期文字是否下划线 0为不1为是 + weekleft :星期文字在表盘区域中的X坐标 + weektop :星期文字在表盘区域中的X坐标 + nclockfontsize:表盘文字的字大小 + nclockfontcolor:表盘文字的颜色;传递颜色的10进制 + nclockbold :表盘文字是否加粗 0为不1为是 + nclockitalic :表盘文字是否斜体 0为不1为是 + nclockunderline:表盘文字是否下划线 0为不1为是 + clockcentercolor:表盘中心颜色;传递颜色的10进制 + mhrdotstyle :3/6/9时点类型 0线形1圆形2方形3数字4罗马 + mhrdotsize :3/6/9时点尺寸 0-8 + mhrdotcolor :3/6/9时点颜色;传递颜色的10进制 + hrdotstyle :3/6/9外的时点类型 0线形1圆形2方形3数字4罗马 + hrdotsize :3/6/9外的时点尺寸 0-8 + hrdotcolor :3/6/9外的时点颜色;传递颜色的10进制 + mindotstyle :分钟点类型 0线形1圆形2方形 + mindotsize :分钟点尺寸 0-1 + mindotcolor :分钟点颜色;传递颜色的10进制 + hrhandsize :时针尺寸 0-8 + hrhandcolor :时针颜色;传递颜色的10进制 + minhandsize :分针尺寸 0-8 + minhandcolor :分针颜色;传递颜色的10进制 + sechandsize :秒针尺寸 0-8 + sechandcolor :秒针颜色;传递颜色的10进制 + nAutoset :自适应位置设置,0为不1为是 如果为1,那txtleft/txttop/ weekleft/weektop/timeleft/timetop需要自己设坐标值 + btxtcontent :固定文字信息 + btxtfontname :固定文字字体 + btimefontname :时间文字字体 + bweekfontname :星期文字字体 + bclockfontname:表盘文字字体 + 返回值 :详见返回状态代码定义。 + -------------------------------------------------------------------------------} + -------------------------------------------------------------------------------* */ + [DllImport("BX_IV.dll")] + public static extern int AddScreenProgramClockAreaFile(int nScreenNo, int nProgramOrd, int nAreaOrd, + int nusetxt, int nusetime, int nuseweek, int ntimeStyle, int nWeekStyle, + int ntxtfontsize, int ntxtfontcolor, int ntxtbold, int ntxtitalic, int ntxtunderline, int txtleft, int txttop, + int ntimefontsize, int ntimefontcolor, int ntimebold, int ntimeitalic, int ntimeunderline, int timeleft, int timetop, + int nweekfontsize, int nweekfontcolor, int nweekbold, int nweekitalic, int nweekunderline, int weekleft, int weektop, + int nclockfontsize, int nclockfontcolor, int nclockbold, int nclockitalic, int nclockunderline, + int clockcentersize, int clockcentercolor, int mhrdotstyle, int mhrdotsize, int mhrdotcolor, + int hrdotstyle, int hrdotsize, int hrdotcolor, int mindotstyle, int mindotsize, int mindotcolor, + int hrhandsize, int hrhandcolor, int minhandsize, int minhandcolor, int sechandsize, int sechandcolor, int nAutoset, + string btxtcontent, string btxtfontname, string btimefontname, string bweekfontname, string bclockfontname); + + [DllImport("BX_IV.dll")] + public static extern int AddScreenProgramChroArea(int nScreenNo, int nProgramOrd, int nX, int nY, int nWidth, int nHeight); + + /**--------------------------------------------------------------------------------------------- + 过程名: AddScreenProgramChroAreaFile + 向动态库中指定显示屏的指定节目的指定计时区域属性;该函数不与显示屏通讯, + 只用于动态库中的指定显示屏指定节目中指定计时区域属性信息配置。 + 参数: + nScreenNo :显示屏屏号;该参数与AddScreen函数中的nScreenNo参数对应。 + nProgramOrd :节目序号;该序号按照节目添加顺序,从0顺序递增,如删除中间的节目,后面的节目序号自动填充。 + nAreaOrd :区域序号;该序号按照区域添加顺序,从0顺序递增,如删除中间的区域,后面的区域序号自动填充。 + pInputtxt :固定文字 + pDaystr :天单位 + pHourstr :小时单位 + pMinstr :分钟单位 + pSecstr :秒单位 + pFontName :文字的字体 + nSingal :单行多行,0为单行 1为多行,单行模式下nAlign不起作用 + nAlign :文字对齐模式,对多行有效,0为左1为中2为右 + nFontSize :文字的大小 + nBold :是否加粗,0为不1为是 + nItalic :是否斜体,0为不1为是 + nUnderline :是否下滑线,0为不1为是 + nTxtcolor :固定文字颜色,传递颜色的10进制 红255 绿65280 黄65535 + nFontcolor :计时显示颜色,传递颜色的10进制 红255 绿65280 黄65535 + nShowstr :是否显示单位,对应于所有的天,时,分,秒单位 + nShowAdd :是否计时累加显示 默认是累加的 + nUsetxt :是否使用固定文字,0为不1为是 + nUseDay :是否使用天,0为不1为是 + nUseHour :是否使用小时,0为不1为是 + nUseMin :是否使用分钟,0为不1为是 + nUseSec :是否使用秒,0为不1为是 + nDayLength :天显示位数 默认为0 自动 + nHourLength :小时显示位数 默认为0 自动 + nMinLength :分显示位数 默认为0 自动 + nSecLength :秒显示位数 默认为0 自动 + + EndYear :目标年值 + EndMonth :目标月值 + EndDay :目标日值 + EndHour :目标时值 + EndMin :目标分值 + EndSec :目标秒值 + + + nAutoset :是否自动设置大小对应宽度,0为不1为是(默认不使用) + 返回值 :详见返回状态代码定义。 + ----------------------------------------------------------------------} + ----------------------------------------------------------------------* */ + [DllImport("BX_IV.dll")] + public static extern int AddScreenProgramChroAreaFile(int nScreenNo, int nProgramOrd, int nAreaOrd, + string pInputtxt, string pDaystr, string pHourstr, string pMinstr, string pSecstr, string pFontName, + int nSingal, int nAlign, int nFontSize, int nBold, int nItalic, int nUnderline, + int nTxtcolor, int nFontcolor, + int nShowstr, int nShowAdd, int nUseTxt, int nUseDay, int nUseHour, int nUseMin, int nUseSec, + int nDayLength, int nHourLength, int nMinLength, int nSecLength, + int EndYear, int EndMonth, int EndDay, int EndHour, int EndMin, int EndSec, + int nAutoset); + + /*------------------------------------------------------------------------------------ + 过程名: AddScreenProgramTemperatureArea + 向动态库中指定显示屏的指定节目添加温度区域;该函数不与显示屏通讯,只用于动态库中的指定显示屏节目中的温度区域信息配置。 + 参数: + nScreenNo :显示屏屏号;该参数与AddScreen函数中的nScreenNo参数对应。 + nProgramOrd :节目序号;该序号按照节目添加顺序,从0顺序递增,如删除中间的节目,后面的节目序号自动填充。 + nX :区域的横坐标;显示屏的左上角的横坐标为0;最小值为0 + nY :区域的纵坐标;显示屏的左上角的纵坐标为0;最小值为0 + nWidth :区域的宽度;最大值不大于显示屏宽度-nX + nHeight :区域的高度;最大值不大于显示屏高度-nY + nSensorType :温度传感器类型; + 0:"Temp sensor S-T1"; + 1:"Temp and hum sensor S-RHT 1"; + 2:"Temp and hum sensor S-RHT 2" + nTemperatureUnit:温度显示单位;0:摄氏度(℃);1:华氏度(℉);2:摄氏度(无) + nTemperatureMode:温度显示模式;0:整数型;1:小数型。 + nTemperatureUnitScale:温度单位显示比例;50~100;默认为100. + nTemperatureValueWidth:温度数值字符显示宽度; + nTemperatureCorrectionPol:温度值误差修正值极性;0;正;1:负 + nTemperatureCondition:温度值误差修正值; + nTemperatureThreshPol:温度阈值条件;0:表示小于此值触发事情;1:表示大于此值触发条件 + nTemperatureThresh:温度阈值 + nTemperatureColor:正常温度颜色 + nTemperatureErrColor:温度超过阈值时显示的颜色 + pStaticText :温度区域前缀固定文本;该参数可为空 + pStaticFont :字体名称;支持当前操作系统已经安装的矢量字库; + nStaticSize :字体字号;支持当前操作系统的字号; + nStaticColor :字体颜色; + nStaticBold :字体粗体;支持1:粗体;0:正常; + 返回值 :详见返回状态代码定义。 + ---------------------------------------------------------------------------} + ---------------------------------------------------------------------------* */ + [DllImport("BX_IV.dll")] + public static extern int AddScreenProgramTemperatureArea(int nScreenNo, int nProgramOrd, + int nX, int nY, int nWidth, int nHeight, + int nSensorType, + int nTemperatureUnit, + int nTemperatureMode, + int nTemperatureUnitScale, + int nTemperatureValueWidth, + int nTemperatureCorrectionPol, + int nTemperatureCondition, + int nTemperatureThreshPol, + int nTemperatureThresh, + int nTemperatureColor, + int nTemperatureErrColor, + string pStaticText, + string pStaticFont, + int nStaticSize, + int intnStaticColor, + int nStaticBold); + /**----------------------------------------------------------------------------------------------------- + 过程名: AddScreenProgramHumidityArea + 向动态库中指定显示屏的指定节目添加湿度区域;该函数不与显示屏通讯,只用于动态库中的指定显示屏节目中的湿度区域信息配置。 + 参数: + nScreenNo :显示屏屏号;该参数与AddScreen函数中的nScreenNo参数对应。 + nProgramOrd :节目序号;该序号按照节目添加顺序,从0顺序递增,如删除中间的节目,后面的节目序号自动填充。 + nX :区域的横坐标;显示屏的左上角的横坐标为0;最小值为0 + nY :区域的纵坐标;显示屏的左上角的纵坐标为0;最小值为0 + nWidth :区域的宽度;最大值不大于显示屏宽度-nX + nHeight :区域的高度;最大值不大于显示屏高度-nY + nSensorType :湿度传感器类型; + 0:"Temp and hum sensor S-RHT 1"; + 1:"Temp and hum sensor S-RHT 2" + nHumidityUnit :湿度显示单位;0:相对湿度(%RH);1:相对湿度(无) + nHumidityMode :湿度显示模式;0:整数型;1:小数型。 + nHumidityUnitScale:湿度单位显示比例;50~100;默认为100. + nHumidityValueWidth:湿度数值字符显示宽度; + nHumidityConditionPol:湿度值误差修正值极性;0;正;1:负 + nHumidityCondition:湿度值误差修正值; + nHumidityThreshPol:湿度阈值条件;0:表示小于此值触发事情;1:表示大于此值触发条件 + nHumidityThresh :湿度阈值 + nHumidityColor :正常湿度颜色 + nHumidityErrColor:湿度超过阈值时显示的颜色 + pStaticText :湿度区域前缀固定文本;该参数可为空 + pStaticFont :字体名称;支持当前操作系统已经安装的矢量字库; + nStaticSize :字体字号;支持当前操作系统的字号; + nStaticColor :字体颜色; + nStaticBold :字体粗体;支持1:粗体;0:正常; + 返回值 :详见返回状态代码定义。 + ------------------------------------------------------------------------} + ------------------------------------------------------------------------* */ + [DllImport("BX_IV.dll")] + public static extern int AddScreenProgramHumidityArea(int nScreenNo, int nProgramOrd, + int nX, int nY, int nWidth, int nHeight, + int nSensorType, + int nHumidityUnit, + int nHumidityMode, + int nHumidityUnitScale, + int nHumidityValueWidth, + int nHumidityConditionPol, + int nHumidityCondition, + int nHumidityThreshPol, + int nHumidityThresh, + int nHumidityColor, + int nHumidityErrColor, + string pStaticText, + string pStaticFont, + int nStaticSize, + int nStaticColor, + int nStaticBold); + + /** + {------------------------------------------------------------------------------- + 过程名: AddScreenProgramNoiseArea + 向动态库中指定显示屏的指定节目添加噪声区域;该函数不与显示屏通讯,只用于动态库中的指定显示屏节目中的噪声区域信息配置。 + 参数: + nScreenNo :显示屏屏号;该参数与AddScreen函数中的nScreenNo参数对应。 + nProgramOrd :节目序号;该序号按照节目添加顺序,从0顺序递增,如删除中间的节目,后面的节目序号自动填充。 + nX :区域的横坐标;显示屏的左上角的横坐标为0;最小值为0 + nY :区域的纵坐标;显示屏的左上角的纵坐标为0;最小值为0 + nWidth :区域的宽度;最大值不大于显示屏宽度-nX + nHeight :区域的高度;最大值不大于显示屏高度-nY + nSensorType :噪声传感器类型; + 0:"I-声级仪"; + 1:"II-声级仪" + nNoiseUnit :噪声显示单位;0:相对湿度(%RH);1:相对湿度(无) + nNoiseMode :噪声显示模式;0:整数型;1:小数型。 + nNoiseUnitScale :噪声单位显示比例;50~100;默认为100. + nNoiseValueWidth:噪声数值字符显示宽度; + nNoiseConditionPol:噪声值误差修正值极性;0;正;1:负 + nNoiseCondition :噪声值误差修正值; + nNoiseThreshPol :噪声阈值条件;0:表示小于此值触发事情;1:表示大于此值触发条件 + nNoiseThresh :噪声阈值 + nNoiseColor :正常噪声颜色 + nNoiseErrColor :噪声超过阈值时显示的颜色 + pStaticText :噪声区域前缀固定文本;该参数可为空 + pStaticFont :字体名称;支持当前操作系统已经安装的矢量字库; + nStaticSize :字体字号;支持当前操作系统的字号; + nStaticColor :字体颜色; + nStaticBold :字体粗体;支持1:粗体;0:正常; + 返回值 :详见返回状态代码定义。 +-------------------------------------------------------------------------------} + ------------------------------------------------------------------------ * */ + [DllImport("BX_IV.dll")] + public static extern int AddScreenProgramNoiseArea(int nScreenNo, int nProgramOrd, + int nX, int nY, int nWidth, int nHeight, + int nSensorType, + int nNoiseUnit, + int nNoiseMode, + int nNoiseUnitScale, + int nNoiseValueWidth, + int nNoiseConditionPol, + int nNoiseCondition, + int nNoiseThreshPol, + int nNoiseThresh, + int nNoiseColor, + int nNoiseErrColor, + string pStaticText, + string pStaticFont, + int nStaticSize, + int nStaticColor, + int nStaticBold); + /*------------------------------------------------------------------------------- + {------------------------------------------------------------------------------- + 过程名: GetScreenStatus + 查询当前显示屏状态,将查询状态参数保存到AddScreen函数中的pScreenStatusFile的INI类型文件中。 + 该函数与显示屏进行通讯 + 参数: nScreenNo, nSendMode: Integer + nScreenNo :显示屏屏号;该参数与AddScreen函数中的nScreenNo参数对应。 + nSendMode :与显示屏的通讯模式; + 0:串口模式、BX-5A2&RF、BX-5A4&RF等控制器为RF串口无线模式; + 2:网络模式; + 4:WiFi模式 + 返回值 :详见返回状态代码定义。 + ------------------------------------------------------------------------------} + ------------------------------------------------------------------------------ * */ + [DllImport("BX_IV.dll")] + public static extern int GetScreenStatus(int nScreenNo, int nSendMode); + + /*------------------------------------------------------------------------------- + {------------------------------------------------------------------------------- + 过程名: SaveUSBScreenInfo + 保存显示屏数据信息到USB设备。方便用户用USB方式更新显示屏信息。该函数与LedshowTW软件配套的USB下载功能一致。 + 使用该功能时,注意当前控制器是否支持USB下载功能。 + 参数: nScreenNo, bCorrectTime: nAdvanceHour,nAdvanceMinute,pUSBDisk + nScreenNo :显示屏屏号;该参数与AddScreen函数中的nScreenNo参数对应。 + bCorrectTime :是否校正时间 + 0:不校正时间; + 1:校正时间。 + nAdvanceHour :校正时间比当前计算机时间提前的小时值。范围0~23;只有当bCorrectTime=1时有效。 + nAdvanceMinute :校正时间比当前计算机时间提前的分钟值。范围0~59;只有当bCorrectTime=1时有效。 + pUSBDisk :USB设备的路径名称;格式为"盘符:\"的格式。 + 返回值 :详见返回状态代码定义。 + ------------------------------------------------------------------------------} + ------------------------------------------------------------------------------ * */ + [DllImport("BX_IV.dll")] + public static extern int SaveUSBScreenInfo(int nScreenNo, int bCorrectTime, int nAdvanceHour, int nAdvanceMinute, string pUSBDisk); + + /*------------------------------------------------------------------------------- + 过程名: StartServer + 启动服务器,用于网络模式下的服务器模式和GPRS通讯模式。 + 参数: + nSendMode :与显示屏的通讯模式; + 0:串口模式、BX-5A2&RF、BX-5A4&RF等控制器为RF串口无线模式; + 1:GPRS模式 + 2:网络模式 + 4:WiFi模式 + 5:ONBON服务器-GPRS + 6:ONBON服务器-3G + pServerIP :中转服务器IP地址 + nServerPort :中转服务器网络端口 + 返回值 :详见返回状态代码定义。 + -------------------------------------------------------------------------------*/ + [DllImport("BX_IV.dll")] + public static extern int StartServer(int nSendMode, string pServerIP, int nServerPort); + + /*------------------------------------------------------------------------------- + 过程名: StopServer + 关闭服务器,用于网络模式下的服务器模式和GPRS通讯模式。 + 参数: + nSendMode :与显示屏的通讯模式; + 0:串口模式、BX-5A2&RF、BX-5A4&RF等控制器为RF串口无线模式; + 1:GPRS模式 + 2:网络模式 + 4:WiFi模式 + 5:ONBON服务器-GPRS + 6:ONBON服务器-3G + 返回值 :详见返回状态代码定义。 + -------------------------------------------------------------------------------*/ + [DllImport("BX_IV.dll")] + public static extern int StopServer(int nSendMode); + + /*------------------------------------------------------------------------------- + {------------------------------------------------------------------------------- + 过程名: GetScreenParameter + 查询当前显示屏参数,将查询状态参数保存到szFileName的INI类型文件中。该函数与显示屏进行通讯 + 参数: + nScreenNo :显示屏屏号;该参数与AddScreen函数中的nScreenNo参数对应。 + nSendMode :与显示屏的通讯模式; + szFilename :保存的Ini文件路径; + 返回值 :详见返回状态代码定义。 + ------------------------------------------------------------------------------} + ------------------------------------------------------------------------------ * */ + [DllImport("BX_IV.dll", EntryPoint = "GetScreenParameter", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)] + public static extern int GetScreenParameter(int nScreenNo, int nSendMode, string szFilename); + + #region 输出错误日志 + public static void OutputErrorLog(string FunctionName, int nResult) + { + switch (nResult) + { + case 0xF7: + ErrorFollow.TraceWrite("LED日志", FunctionName, "区域类型错误,在添加、删除图文区域文件时区域类型出错返回此类型错误。"); + break; + case 0xF8: + ErrorFollow.TraceWrite("LED日志", FunctionName, "已经有该显示屏信息。如要重新设定请先DeleteScreen删除该显示屏再添加。"); + break; + case 0xF9: + ErrorFollow.TraceWrite("LED日志", FunctionName, "没有找到有效的区域文件(图文区域)。"); + break; + case 0xFA: + ErrorFollow.TraceWrite("LED日志", FunctionName, "没有找到有效的显示区域可以使用AddScreenProgramBmpTextArea添加区域信息。"); + break; + case 0xFB: + ErrorFollow.TraceWrite("LED日志", FunctionName, "没有找到有效的显示屏节目可以使用AddScreenProgram函数添加指定节目。"); + break; + case 0xFC: + ErrorFollow.TraceWrite("LED日志", FunctionName, "系统内没有查找到该显示屏可以使用AddScreen函数添加显示屏。"); + break; + case 0xFD: + ErrorFollow.TraceWrite("LED日志", FunctionName, "系统内正在向该显示屏通讯,请稍后再通讯。"); + break; + case 0x01: + ErrorFollow.TraceWrite("LED日志", FunctionName, "通讯错误。"); + break; + case 0x02: + ErrorFollow.TraceWrite("LED日志", FunctionName, "通讯错误。"); + break; + case 0x03: + ErrorFollow.TraceWrite("LED日志", FunctionName, "通讯错误。"); + break; + case 0x04: + ErrorFollow.TraceWrite("LED日志", FunctionName, "通讯错误。"); + break; + case 0x05: + ErrorFollow.TraceWrite("LED日志", FunctionName, "通讯错误。"); + break; + case 0x06: + ErrorFollow.TraceWrite("LED日志", FunctionName, "通讯错误。"); + break; + case 0x07: + ErrorFollow.TraceWrite("LED日志", FunctionName, "通讯错误。"); + break; + case 0x08: + ErrorFollow.TraceWrite("LED日志", FunctionName, "通讯错误。"); + break; + case 0x09: + ErrorFollow.TraceWrite("LED日志", FunctionName, "通讯错误。"); + break; + case 0x0A: + ErrorFollow.TraceWrite("LED日志", FunctionName, "通讯错误。"); + break; + case 0x0B: + ErrorFollow.TraceWrite("LED日志", FunctionName, "通讯错误。"); + break; + case 0x0C: + ErrorFollow.TraceWrite("LED日志", FunctionName, "通讯错误。"); + break; + case 0x0D: + ErrorFollow.TraceWrite("LED日志", FunctionName, "通讯错误。"); + break; + case 0x0E: + ErrorFollow.TraceWrite("LED日志", FunctionName, "通讯错误。"); + break; + case 0x0F: + ErrorFollow.TraceWrite("LED日志", FunctionName, "通讯错误。"); + break; + case 0x10: + ErrorFollow.TraceWrite("LED日志", FunctionName, "通讯错误。"); + break; + case 0x11: + ErrorFollow.TraceWrite("LED日志", FunctionName, "通讯错误。"); + break; + case 0x12: + ErrorFollow.TraceWrite("LED日志", FunctionName, "通讯错误。"); + break; + case 0x13: + ErrorFollow.TraceWrite("LED日志", FunctionName, "通讯错误。"); + break; + case 0x14: + ErrorFollow.TraceWrite("LED日志", FunctionName, "通讯错误。"); + break; + case 0x15: + ErrorFollow.TraceWrite("LED日志", FunctionName, "通讯错误。"); + break; + case 0x16: + ErrorFollow.TraceWrite("LED日志", FunctionName, "通讯错误。"); + break; + case 0x17: + ErrorFollow.TraceWrite("LED日志", FunctionName, "通讯错误。"); + break; + case 0x18: + ErrorFollow.TraceWrite("LED日志", FunctionName, "通讯错误。"); + break; + case 0xFE: + ErrorFollow.TraceWrite("LED日志", FunctionName, "通讯错误。"); + break; + default: + ErrorFollow.TraceWrite("LED日志", FunctionName, "其他错误。"); + break; + } + } + #endregion + + } +} diff --git a/基础类库/HuizhongLibrary/ListGridView.cs b/基础类库/HuizhongLibrary/ListGridView.cs new file mode 100644 index 0000000..7ba94e8 --- /dev/null +++ b/基础类库/HuizhongLibrary/ListGridView.cs @@ -0,0 +1,3702 @@ +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.Data; +using System.Drawing; +using System.Globalization; +using System.Security.Permissions; +using HuizhongLibrary.RegularExpressions; +using System.Text.RegularExpressions; +using System.IO; +using System.Diagnostics; +using System.Web.UI.HtmlControls; +using HuizhongLibrary.Common.Configuration; +using NPOI.HSSF.UserModel; +using NPOI.SS.UserModel; +using NPOI.SS.Util; + +namespace HuizhongLibrary.Control +{ + + [ToolboxData("<{0}:ListGridView runat=server>"), ParseChildren(true), PersistChildren(false)] + public class ListGridView : System.Web.UI.WebControls.GridView, INamingContainer, IPostBackDataHandler + { + private GridViewColumnLabel ColumnLabel; + private GridViewColumnRadioButton ColumnRadioButton; + private GridViewColumnCheckBox ColumnCheckBox; + private CommandField ColumnButton; + + private Label FirstPagerCount; //总页数<1/10> + private Label FirstRowCount; //总行数<366> + private Label FirstGo; + private HtmlButton FirstButtonFirst; //第一页 + private HtmlButton FirstButtonPrev; //上一页 + private HtmlButton FirstButtonNext; //下一页 + private HtmlButton FirstButtonLast; //末页 + private HtmlButton FirstButtonExcel; //末页 + private DropDownList FirstDownListPager; //下拉框选择页 + private Label FirstPageRowCount; //分页行数 + private HtmlInputText FirstTextBoxPageRowCount; // 分页行数 + + private Label LastPagerCount; //总页数<1/10> + private Label LastRowCount; //总行数<366> + private Label LastGo; + private HtmlButton LastButtonFirst; //第一页 + private HtmlButton LastButtonPrev; //上一页 + private HtmlButton LastButtonNext; //下一页 + private HtmlButton LastButtonLast; //末页 + private HtmlButton LastButtonExcel; //末页 + private DropDownList LastDownListPager; //下拉框选择页 + private Label LastPageRowCount; //分页行数 + private HtmlInputText LastTextBoxPageRowCount; // 分页行数 + + private ImageButton FirstImageButtonFirst; //第一页 + private ImageButton FirstImageButtonPrev; //上一页 + private ImageButton FirstImageButtonNext; //下一页 + private ImageButton FirstImageButtonLast; //末页 + + private ImageButton LastImageButtonFirst; //第一页 + private ImageButton LastImageButtonPrev; //上一页 + private ImageButton LastImageButtonNext; //下一页 + private ImageButton LastImageButtonLast; //末页 + + + + + /// + /// 当前页改变时触发 + /// + public event EventHandler PagerChanged; + /// + /// 当前页眉改变时触发 + /// + public event HeaderChangedEventHandler HeaderChanged; + public delegate void HeaderChangedEventHandler(object sender,HeaderEventArgs e); + /// + /// 当前鼠标双击行时触发 + /// + public event GridViewRowEventHandler RowDoubleClick; + + + private UserPagerStyle m_UserPagerStyle; + /// + /// 自定义分页设置 + /// + [Description("自定义分页设置"), Category("扩展"), NotifyParentProperty(true), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), PersistenceMode(PersistenceMode.InnerProperty)] + public UserPagerStyle UserPagerStyle + { + get { return m_UserPagerStyle; } + set { m_UserPagerStyle = value; } + } + + private bool _isFixHeader=false; + /// + /// 是否固定表头 + /// + [Description("是否固定表头"), DefaultValue("false"), Category("扩展"),NotifyParentProperty(true)] + public virtual bool IsFixHeader + { + get { return _isFixHeader; } + set + { + _isFixHeader = value; + } + } + private int _FixLeftColumns=0; + /// + /// 左边固定列数量 + /// + [Description("左边固定列数量"), DefaultValue("0"), Category("扩展"), NotifyParentProperty(true)] + public virtual int FixLeftColumns + { + get { return _FixLeftColumns; } + set + { + _FixLeftColumns = value; + } + } + + private bool _CellWrap=true; + /// + /// 单元格文本是否换行 + /// + [Description("单元格文本是否换行"), DefaultValue("true"), Category("扩展"),NotifyParentProperty(true)] + public virtual bool CellWrap + { + get { return _CellWrap; } + set + { + _CellWrap = value; + } + } + //private bool m_ShowExcelReport=false; + /// + /// 是否显示导出按钮 + /// + [Description("是否显示导出按钮"), DefaultValue("false"), Category("扩展"),NotifyParentProperty(true)] + public virtual bool ShowExcelReport + { + get { return this.UserPagerStyle.ShowExcelReport; } + set { this.UserPagerStyle.ShowExcelReport = value; } + } + //private bool m_ShowSelectPager=false; + /// + /// 是否显示分页选择 + /// + [Description("是否显示分页选择"), DefaultValue("false"), Category("扩展"),NotifyParentProperty(true)] + public virtual bool ShowSelectPager + { + get { return this.UserPagerStyle.ShowSelectPager; } + set { this.UserPagerStyle.ShowSelectPager = value; } + } + //private bool m_ShowPagerButton=true; + /// + /// 是否显示分页按钮 + /// + [Description("是否显示分页按钮"), DefaultValue("false"), Category("扩展"),NotifyParentProperty(true)] + public virtual bool ShowPagerButton + { + get { return this.UserPagerStyle.ShowPagerButton; } + set { this.UserPagerStyle.ShowPagerButton = value; } + } + + private bool _enableScrollState=false; + /// + /// 是否保持滚动条的状态 + /// + [Description("是否保持滚动条的状态"), DefaultValue("false"), Category("扩展"),NotifyParentProperty(true)] + public bool EnableScrollState + { + get { return _enableScrollState;} + set { _enableScrollState = value; } + } + + //private bool m_ShowFirstPager=false; + /// + /// 是否显示自定义分页按钮在上面 + /// + [Description("是否显示自定义分页按钮在上面"), DefaultValue("false"), Category("扩展"),NotifyParentProperty(true)] + public bool ShowFirstPager + { + get { return this.UserPagerStyle.ShowFirstPager; } + set { this.UserPagerStyle.ShowFirstPager = value; } + } + //private bool m_ShowLastPager=false; + /// + /// 是否显示自定义分页按钮在下面 + /// + [Description("是否显示自定义分页按钮在下面"), DefaultValue("false"), Category("扩展"),NotifyParentProperty(true)] + public bool ShowLastPager + { + get { return this.UserPagerStyle.ShowLastPager; } + set { this.UserPagerStyle.ShowLastPager = value; } + } + private bool m_ShowRowColor=true; + /// + /// 是否显示鼠标经过时的行颜色 + /// + [Description("是否显示鼠标经过时的行颜色"), DefaultValue("true"), Category("扩展"),NotifyParentProperty(true)] + public bool ShowRowColor + { + get { return m_ShowRowColor; } + set { m_ShowRowColor = value; } + } + public int RowCount + { + get + { + if (this.ViewState["RowCount"] == null) return 0; + return (int)this.ViewState["RowCount"]; + } + set { this.ViewState["RowCount"] = value; } + } + private Unit m_Height; + public new Unit Height + { + get { return m_Height; } + set { m_Height = value; } + } + private SelectMode m_SelectMode=SelectMode.None; + [Description("选择模式"), DefaultValue("None"), Category("扩展"),NotifyParentProperty(true)] + public SelectMode SelectMode + { + get{return this.m_SelectMode;} + set{this.m_SelectMode=value;} + } + + + public SortDirection ViewSortDirection + { + get { if (this.ViewState["ViewSortDirection"] == null)return SortDirection.Ascending; return (SortDirection)(this.ViewState["ViewSortDirection"]); } + set { this.ViewState["ViewSortDirection"] = value; } + } + + public string ViewSortString + { + get { if (this.ViewState["ViewSortString"] == null)return ""; return (string)(this.ViewState["ViewSortString"]); } + set { this.ViewState["ViewSortString"] = value; } + } + + public int PaperModel + { + get { if (this.ViewState["PaperModel"] == null)return 1; return (int)(this.ViewState["PaperModel"]); } + set { this.ViewState["PaperModel"] = value; } + } + + public int PaperCount + { + get { if (this.ViewState["PaperCount"] == null)return 0; return (int)(this.ViewState["PaperCount"]); } + set { this.ViewState["PaperCount"] = value; } + } + + private bool m_ShowIndexColumn=false; + /// + /// 是否显示索引列 + /// + [Description("是否显示索引列"), DefaultValue("false"), Category("扩展"), Browsable(true),NotifyParentProperty(true), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible), PersistenceMode(PersistenceMode.Attribute)] + public bool ShowIndexColumn + { + get + { + return m_ShowIndexColumn; + } + set + { + this.m_ShowIndexColumn=value; + } + } + + + private bool m_IsExport=false; + public int SelectPagerIndex + { + get { if (this.ViewState["SelectPagerIndex"] == null)return 0; return (int)(this.ViewState["SelectPagerIndex"]); } + set { this.ViewState["SelectPagerIndex"] = value; } + } + public System.Web.UI.WebControls.Table m_Header; + + + + #region 只可以访问的公共属性 + private int _yy_SmartGridViewAlpha_x; + /// + /// 固定行、列的时候X滚动条的位置 + /// + public int ScrollX + { + get { return this._yy_SmartGridViewAlpha_x; } + } + private int _yy_SmartGridViewAlpha_y; + /// + /// 固定行、列的时候Y滚动条的位置 + /// + public int ScrollY + { + get { return this._yy_SmartGridViewAlpha_y; } + } + #endregion + + public DataTable View + { + get + { + if (this.Page == null) return null; + if (this.Page.Session[this.Page.GetType().ToString() + this.ID] == null) return null; return (DataTable)(this.Page.Session[this.Page.GetType().ToString() + this.ID]); + } + set + { + this.Page.Session[this.Page.GetType().ToString() + this.ID] = value; + + + } + } + + + public ListGridView(): base() + { + string button_css = "FONT-SIZE: 8pt; COLOR: steelblue; BORDER-TOP-STYLE: none; BORDER-RIGHT-STYLE: none; BORDER-LEFT-STYLE: none; HEIGHT: 14px; BACKGROUND-COLOR: transparent; BORDER-BOTTOM-STYLE: none"; + m_Header=new Table(); + //this.AllowPaging = true; + //this.PagerSettings.Visible = false; + //this.AutoGenerateColumns = false; + //this.AllowSorting = false; + //this.HorizontalAlign = HorizontalAlign.Left; + //this.CssClass = "grid_back"; + //this.HeaderStyle.CssClass = "grid_header"; + //this.RowStyle.CssClass = "grid_item"; + //this.SelectedRowStyle.CssClass = "grid_select"; + //this.FooterStyle.CssClass = "grid_footer"; + //this.EditRowStyle.CssClass = "grid_edit"; + + //this.Width=new Unit("100%"); + //this.CellPadding=1; + //this.BorderWidth=new Unit("1px"); + //this.BorderStyle=BorderStyle.Solid; + //this.BorderColor=Color.Black; + //this.AutoGenerateColumns=false; + //this.BackColor=Color.White; + //this.AllowSorting=false; + //this.HorizontalAlign=HorizontalAlign.Left; + //this.HeaderStyle.Font.Bold=true; + //this.HeaderStyle.ForeColor=Color.White; + //this.HeaderStyle.BackColor=Color.FromName("#006699"); + + //this.RowStyle.HorizontalAlign=HorizontalAlign.Center; + //this.SelectedRowStyle.Wrap=false; + //this.SelectedRowStyle.HorizontalAlign=HorizontalAlign.Center; + //this.SelectedRowStyle.BackColor=Color.FromName("#669999"); + //this.SelectedRowStyle.Font.Bold=true; + //this.SelectedRowStyle.ForeColor=Color.White; + + m_UserPagerStyle = new UserPagerStyle(); + + + //上面分页按钮 + this.FirstPagerCount = new Label(); + this.FirstPagerCount.Text = "第0页/共0页"; + this.FirstPagerCount.Font.Size = new FontUnit("100%"); + //this.FirstPagerCount.Font.Name = "宋体"; + + this.FirstRowCount = new Label(); + this.FirstRowCount.Font.Size = new FontUnit("100%"); + this.FirstRowCount.Text = "记录总数:0条"; + //this.FirstRowCount.Font.Name = "宋体"; + + + + this.FirstButtonFirst = new HtmlButton(); + this.FirstButtonFirst.ID = "FirstButtonFirst"; + //this.FirstButtonFirst.ControlStyle.BorderStyle = BorderStyle.None; + //this.FirstButtonFirst.ControlStyle.BackColor = Color.Transparent; + this.FirstButtonFirst.InnerText = "首页"; + //this.FirstButtonFirst.Font.Name = "宋体"; + //this.FirstButtonFirst.Font.Size = new FontUnit("12px"); + ////this.FirstButtonFirst.ForeColor = Color.SteelBlue; + //this.FirstButtonFirst.Height = new Unit("14px"); + this.FirstButtonFirst.Attributes.Add("onmouseout", "style.textDecorationUnderline=false;"); + this.FirstButtonFirst.Attributes.Add("onmouseover", "style.textDecorationUnderline=true;"); + this.FirstButtonFirst.Attributes.Add("onclick", "doPostBack('ButtonFirst','ButtonFirst');"); + this.FirstButtonFirst.Attributes.Add("style", button_css); + + this.FirstButtonPrev = new HtmlButton(); + this.FirstButtonPrev.ID = "FirstButtonPrev"; + //this.FirstButtonPrev.ControlStyle.BorderStyle = BorderStyle.None; + //this.FirstButtonPrev.ControlStyle.BackColor = Color.Transparent; + //this.FirstButtonPrev.Font.Name = "宋体"; + //this.FirstButtonPrev.Font.Size = new FontUnit("12px"); + this.FirstButtonPrev.InnerText = "上一页"; + //this.FirstButtonPrev.ForeColor = Color.SteelBlue; + //this.FirstButtonPrev.Height = new Unit("14px"); + this.FirstButtonPrev.Attributes.Add("onmouseout", "style.textDecorationUnderline=false;"); + this.FirstButtonPrev.Attributes.Add("onmouseover", "style.textDecorationUnderline=true;"); + this.FirstButtonPrev.Attributes.Add("onclick", "doPostBack('ButtonFirst','ButtonFirst');"); + this.FirstButtonPrev.Attributes.Add("style", button_css); + + this.FirstButtonNext = new HtmlButton(); + this.FirstButtonNext.ID = "FirstButtonNext"; + //this.FirstButtonNext.ControlStyle.BorderStyle = BorderStyle.None; + //this.FirstButtonNext.ControlStyle.BackColor = Color.Transparent; + //this.FirstButtonNext.Font.Name = "宋体"; + //this.FirstButtonNext.Font.Size = new FontUnit("12px"); + this.FirstButtonNext.InnerText = "下一页"; + //this.FirstButtonNext.ForeColor = Color.SteelBlue; + //this.FirstButtonNext.Height = new Unit("14px"); + this.FirstButtonNext.Attributes.Add("onmouseout", "style.textDecorationUnderline=false;"); + this.FirstButtonNext.Attributes.Add("onmouseover", "style.textDecorationUnderline=true;"); + this.FirstButtonNext.Attributes.Add("onclick", "doPostBack('ButtonNext','ButtonNext');"); + this.FirstButtonNext.Attributes.Add("style", button_css); + + this.FirstButtonLast = new HtmlButton(); + this.FirstButtonLast.ID = "FirstButtonLast"; + //this.FirstButtonLast.ControlStyle.BorderStyle = BorderStyle.None; + //this.FirstButtonLast.ControlStyle.BackColor = Color.Transparent; + //this.FirstButtonLast.Font.Name = "宋体"; + //this.FirstButtonLast.Font.Size = new FontUnit("12px"); + this.FirstButtonLast.InnerText = "末页"; + //this.FirstButtonLast.ForeColor = Color.SteelBlue; + //this.FirstButtonLast.Height = new Unit("14px"); + this.FirstButtonLast.Attributes.Add("onmouseout", "style.textDecorationUnderline=false;"); + this.FirstButtonLast.Attributes.Add("onmouseover", "style.textDecorationUnderline=true;"); + this.FirstButtonLast.Attributes.Add("onclick", "doPostBack('ButtonLast','ButtonLast');"); + this.FirstButtonLast.Attributes.Add("style", button_css); + + this.FirstButtonExcel = new HtmlButton(); + this.FirstButtonExcel.ID = "FirstButtonExcel"; + //this.FirstButtonExcel.ControlStyle.BorderStyle = BorderStyle.None; + //this.FirstButtonExcel.ControlStyle.BackColor = Color.Transparent; + //this.FirstButtonExcel.Font.Name = "宋体"; + //this.FirstButtonExcel.Font.Size = new FontUnit("12px"); + this.FirstButtonExcel.InnerText = "导出"; + //this.FirstButtonExcel.ForeColor = Color.SteelBlue; + //this.FirstButtonExcel.Height = new Unit("14px"); + this.FirstButtonExcel.Attributes.Add("onmouseout", "style.textDecorationUnderline=false;"); + this.FirstButtonExcel.Attributes.Add("onmouseover", "style.textDecorationUnderline=true;"); + this.FirstButtonExcel.Attributes.Add("onclick", "doPostBack('ButtonExcel','ButtonExcel');"); + this.FirstButtonExcel.Attributes.Add("style", button_css); + + this.FirstGo = new Label(); + this.FirstGo.Text = "跳转至"; + //this.FirstGo.Font.Size = new FontUnit("100%"); + //this.FirstGo.Font.Name = "宋体"; + + this.FirstDownListPager = new DropDownList(); + //this.FirstDownListPager.Font.Name = "宋体"; + //this.FirstDownListPager.Font.Size = new FontUnit("10pt"); + this.FirstDownListPager.Width = new Unit("40px"); + //this.FirstDownListPager.Height = new Unit("100%"); + this.FirstDownListPager.Items.Add(new ListItem("0", "0")); + + + this.FirstPageRowCount = new Label(); + this.FirstPageRowCount.Text = "每页行数:"; + //this.FirstPageRowCount.Font.Size = new FontUnit("100%"); + //this.FirstPageRowCount.Font.Name = "宋体"; + + this.FirstTextBoxPageRowCount = new HtmlInputText(); + //this.FirstTextBoxPageRowCount.Width = new Unit("40px"); + this.FirstTextBoxPageRowCount.Value = "10"; + this.FirstTextBoxPageRowCount.Attributes.Add("onchange", "document.getElementById('" + FirstTextBoxPageRowCount.ClientID+ "').focus();doPostBack('TextBoxPageRowCount',this.value)"); + this.FirstTextBoxPageRowCount.Attributes.Add("style", "FONT-FAMILY: 宋体;width:40px;"); + + + + + //下面分页按钮 + this.LastPagerCount = new Label(); + //this.LastPagerCount.Font.Size = new FontUnit("100%"); + //this.LastPagerCount.Font.Name = "宋体"; + this.LastPagerCount.Text = "第0页/共0页"; + + + this.LastRowCount = new Label(); + //this.LastRowCount.Font.Name = "宋体"; + //this.LastRowCount.Font.Size = new FontUnit("100%"); + this.LastRowCount.Text = "记录总数:0条"; + + + + this.LastButtonFirst = new HtmlButton(); + this.LastButtonFirst.ID = "LastButtonFirst"; + //this.LastButtonFirst.ControlStyle.BorderStyle = BorderStyle.None; + //this.LastButtonFirst.ControlStyle.BackColor = Color.Transparent; + //this.LastButtonFirst.Font.Name = "宋体"; + //this.LastButtonFirst.Font.Size = new FontUnit("12px"); + this.LastButtonFirst.InnerText = "首页"; + //this.LastButtonFirst.ForeColor = Color.SteelBlue; + //this.LastButtonFirst.Height = new Unit("14px"); + this.LastButtonFirst.Attributes.Add("onmouseout", "style.textDecorationUnderline=false;"); + this.LastButtonFirst.Attributes.Add("onmouseover", "style.textDecorationUnderline=true;"); + this.LastButtonFirst.Attributes.Add("onclick", "doPostBack('ButtonFirst','ButtonFirst');"); + this.LastButtonFirst.Attributes.Add("style", button_css); + + this.LastButtonPrev = new HtmlButton(); + this.LastButtonPrev.ID = "LastButtonPrev"; + //this.LastButtonPrev.ControlStyle.BorderStyle = BorderStyle.None; + //this.LastButtonPrev.ControlStyle.BackColor = Color.Transparent; + //this.LastButtonPrev.Font.Name = "宋体"; + //this.LastButtonPrev.Font.Size = new FontUnit("12px"); + this.LastButtonPrev.InnerText = "上一页"; + //this.LastButtonPrev.ForeColor = Color.SteelBlue; + //this.LastButtonPrev.Height = new Unit("14px"); + this.LastButtonPrev.Attributes.Add("onmouseout", "style.textDecorationUnderline=false;"); + this.LastButtonPrev.Attributes.Add("onmouseover", "style.textDecorationUnderline=true;"); + this.LastButtonPrev.Attributes.Add("onclick", "doPostBack('ButtonPrev','ButtonPrev');"); + this.LastButtonPrev.Attributes.Add("style", button_css); + + this.LastButtonNext = new HtmlButton(); + this.LastButtonNext.ID = "LastButtonNext"; + //this.LastButtonNext.ControlStyle.BorderStyle = BorderStyle.None; + //this.LastButtonNext.ControlStyle.BackColor = Color.Transparent; + //this.LastButtonNext.Font.Name = "宋体"; + //this.LastButtonNext.Font.Size = new FontUnit("12px"); + this.LastButtonNext.InnerText = "下一页"; + //this.LastButtonNext.ForeColor = Color.SteelBlue; + //this.LastButtonNext.Height = new Unit("14px"); + this.LastButtonNext.Attributes.Add("onmouseout", "style.textDecorationUnderline=false;"); + this.LastButtonNext.Attributes.Add("onmouseover", "style.textDecorationUnderline=true;"); + this.LastButtonNext.Attributes.Add("onclick", "doPostBack('ButtonNext','ButtonNext');"); + this.LastButtonNext.Attributes.Add("style", button_css); + + this.LastButtonLast = new HtmlButton(); + this.LastButtonLast.ID = "LastButtonLast"; + //this.LastButtonLast.ControlStyle.BorderStyle = BorderStyle.None; + //this.LastButtonLast.ControlStyle.BackColor = Color.Transparent; + //this.LastButtonLast.Font.Name = "宋体"; + //this.LastButtonLast.Font.Size = new FontUnit("12px"); + this.LastButtonLast.InnerText = "末页"; + //this.LastButtonLast.ForeColor = Color.SteelBlue; + //this.LastButtonLast.Height = new Unit("14px"); + this.LastButtonLast.Attributes.Add("onmouseout", "style.textDecorationUnderline=false;"); + this.LastButtonLast.Attributes.Add("onmouseover", "style.textDecorationUnderline=true;"); + this.LastButtonLast.Attributes.Add("onclick", "doPostBack('ButtonLast','ButtonLast');"); + this.LastButtonLast.Attributes.Add("style", button_css); + + this.LastButtonExcel = new HtmlButton(); + this.LastButtonExcel.ID = "LastButtonExcel"; + //this.LastButtonExcel.ControlStyle.BorderStyle = BorderStyle.None; + //this.LastButtonExcel.ControlStyle.BackColor = Color.Transparent; + //this.LastButtonExcel.Font.Name = "宋体"; + //this.LastButtonExcel.Font.Size = new FontUnit("12px"); + this.LastButtonExcel.InnerText = "导出"; + //this.LastButtonExcel.ForeColor = Color.SteelBlue; + //this.LastButtonExcel.Height = new Unit("14px"); + this.LastButtonExcel.Attributes.Add("onmouseout", "style.textDecorationUnderline=false;"); + this.LastButtonExcel.Attributes.Add("onmouseover", "style.textDecorationUnderline=true;"); + this.LastButtonExcel.Attributes.Add("onclick", "doPostBack('ButtonExcel','ButtonExcel');"); + this.LastButtonExcel.Attributes.Add("style", button_css); + + this.LastGo = new Label(); + this.LastGo.Text = "跳转至"; + //this.LastGo.Font.Size = new FontUnit("100%"); + //this.LastGo.Font.Name = "宋体"; + + this.LastDownListPager = new DropDownList(); + //this.LastDownListPager.Font.Name = "宋体"; + //this.LastDownListPager.Font.Size = new FontUnit("10pt"); + this.LastDownListPager.Width = new Unit("40px"); + //this.LastDownListPager.Height = new Unit("100%"); + this.LastDownListPager.Items.Add(new ListItem("0", "0")); + + + this.LastPageRowCount = new Label(); + this.LastPageRowCount.Text = "每页行数:"; + //this.LastPageRowCount.Font.Size = new FontUnit("100%"); + //this.LastPageRowCount.Font.Name = "宋体"; + + this.LastTextBoxPageRowCount = new HtmlInputText(); + this.LastTextBoxPageRowCount.ID = "LastTextBoxPageRowCount"; + //this.LastTextBoxPageRowCount.Font.Name = "宋体"; + //this.LastTextBoxPageRowCount.Width = new Unit("40px"); + this.LastTextBoxPageRowCount.Attributes.Add("onchange", "doPostBack('TextBoxPageRowCount',this.value);"); + this.LastTextBoxPageRowCount.Value = "10"; + this.LastTextBoxPageRowCount.Attributes.Add("style", "FONT-FAMILY: 宋体;width:40px;"); + + this.FirstDownListPager.Attributes.Add("onchange", "javascript:doPostBack('ListPager',this.options(this.selectedIndex).value)"); + this.LastDownListPager.Attributes.Add("onchange", "javascript:doPostBack('ListPager',this.options(this.selectedIndex).value)"); + + this.FirstImageButtonFirst = new ImageButton(); + this.FirstImageButtonFirst.Width = new Unit("12px"); + this.FirstImageButtonFirst.Height = new Unit("10px"); + this.FirstImageButtonFirst.Attributes.Add("onclick", "doPostBack('ButtonFirst','ButtonFirst');"); + + this.FirstImageButtonLast = new ImageButton(); + this.FirstImageButtonLast.Width = new Unit("12px"); + this.FirstImageButtonLast.Height = new Unit("10px"); + this.FirstImageButtonLast.Attributes.Add("onclick", "doPostBack('ButtonLast','ButtonLast');"); + + this.FirstImageButtonNext = new ImageButton(); + this.FirstImageButtonNext.Width = new Unit("12px"); + this.FirstImageButtonNext.Height = new Unit("10px"); + this.FirstImageButtonNext.Attributes.Add("onclick", "doPostBack('ButtonNext','ButtonNext');"); + + this.FirstImageButtonPrev = new ImageButton(); + this.FirstImageButtonPrev.Width = new Unit("12px"); + this.FirstImageButtonPrev.Height = new Unit("10px"); + this.FirstImageButtonPrev.Attributes.Add("onclick", "doPostBack('ButtonPrev','ButtonPrev');"); + + this.LastImageButtonFirst = new ImageButton(); + this.LastImageButtonFirst.Width = new Unit("12px"); + this.LastImageButtonFirst.Height = new Unit("10px"); + this.LastImageButtonFirst.Attributes.Add("onclick", "doPostBack('ButtonFirst','ButtonFirst');"); + + this.LastImageButtonLast = new ImageButton(); + this.LastImageButtonLast.Width = new Unit("12px"); + this.LastImageButtonLast.Height = new Unit("10px"); + this.LastImageButtonLast.Attributes.Add("onclick", "doPostBack('ButtonLast','ButtonLast');"); + + this.LastImageButtonNext = new ImageButton(); + this.LastImageButtonNext.Width = new Unit("12px"); + this.LastImageButtonNext.Height = new Unit("10px"); + this.LastImageButtonNext.Attributes.Add("onclick", "doPostBack('ButtonNext','ButtonNext');"); + + this.LastImageButtonPrev = new ImageButton(); + this.LastImageButtonPrev.Width = new Unit("12px"); + this.LastImageButtonPrev.Height = new Unit("10px"); + this.LastImageButtonPrev.Attributes.Add("onclick", "doPostBack('ButtonPrev','ButtonPrev');"); + +// this.Attributes.CssStyle.Add("BORDER-COLLAPSE","collapse"); +// this.Attributes.CssStyle.Add("TABLE-LAYOUT","fixed"); + + this.PreRender += new EventHandler(GridView_PreRender); + this.RowCreated += new GridViewRowEventHandler(ListGridView_RowCreated); + this.Sorting += new GridViewSortEventHandler(ListGridView_Sorting); + + //this.DataBinding += new EventHandler(ListGridView_DataBinding); + //this.DataBound += new EventHandler(ListGridView_DataBound); + this.AllowSorting = true; + + + } + + void ListGridView_Sorting(object sender, GridViewSortEventArgs e) + { + if (this.View == null) return; + DataView dv = this.View.DefaultView; + if (this.ViewSortDirection==SortDirection.Ascending) + { + dv.Sort =e.SortExpression+" desc"; + this.ViewSortString = dv.Sort; + this.ViewSortDirection = SortDirection.Descending; + } + else + { + dv.Sort =e.SortExpression; + this.ViewSortString = dv.Sort; + this.ViewSortDirection = SortDirection.Ascending; + } + this.DataSource = dv; + this.DataBind(); + } + + + + + + + #region 返回选择行 + /// + /// 返回选择行 + /// + /// 控件ID + /// + public GridViewRow GetRadioButtonSelectRow(string ControlID) + { + foreach(GridViewRow dgi in this.Rows) + { + bool ck=((RadioButton)(dgi.FindControl(ControlID))).Checked; + if (ck==true)return dgi; + } + return null; + } + /// + /// 返回选择行索引 + /// + /// + /// + public int GetRadioButtonSelectRowIndex(string ControlID,bool IsPager) + { + for (int i=0;i + /// 返回分页选择行索引 + /// + /// + public int GetSelectRowIndex + { + get { return this.PageSize * this.PageIndex + this.SelectedIndex; } + } + + + /// + /// 返回多选行 + /// + /// 控件ID + /// key=行索引,value=GridViewRow + public Dictionary GetCheckedSelectRow(string ControlID, bool IsPager) + { + Dictionary listdgi = new Dictionary(); + for (int i = this.Rows.Count-1; i >= 0; i--) + { + bool ck = ((CheckBox)(this.Rows[i].FindControl(ControlID))).Checked; + if (ck==false)continue; + if (IsPager==true){listdgi.Add(this.PageSize*this.PageIndex+i,this.Rows[i]);} + else{listdgi.Add(i,this.Rows[i]);} + } + return listdgi; + } + /// + /// 返回系统选择列的选择行 + /// + public GridViewRow GetRadioButtonSelectRow() + { + foreach (GridViewRow dgi in this.Rows) + { + bool ck=((RadioButton)(dgi.FindControl("RadioButtonSelect_123456789"))).Checked; + if (ck==true)return dgi; + } + return null; + } + /// + /// 返回系统选择列的选择行索引 + /// + /// + public int GetRadioButtonSelectRowIndex(bool IsPager) + { + for (int i=0;i + /// 返回系统选择列的多选行 + /// + /// 是否计算分页 + /// key=行索引,value=GridViewRow + public Dictionary GetCheckedSelectRow(bool IsPager) + { + Dictionary listdgi = new Dictionary(); + for (int i = this.Rows.Count - 1; i >= 0; i--) + { + bool ck=((CheckBox)(this.Rows[i].FindControl("CheckBoxSelect_123456789"))).Checked; + if (ck==false)continue; + if (IsPager==true){listdgi.Add(this.PageSize*this.PageIndex+i,this.Rows[i]);} + else{listdgi.Add(i,this.Rows[i]);} + } + return listdgi; + } + #endregion + + + + #region 显示特定列 + private void ShowIndex(bool Visible) + { + if (Visible == true) + { + bool bk = false; + foreach (DataControlField item in this.Columns) + { + if (item.AccessibleHeaderText != "txtIndex_123456789") continue; + bk = true; + break; + } + if (bk == false) + { + ColumnLabel = new GridViewColumnLabel("txtIndex_123456789", "", "", "txtIndex_123456789", "", 50); + ColumnLabel.HeaderText = "序号"; + ColumnLabel.AccessibleHeaderText = "txtIndex_123456789"; + ColumnLabel.ItemStyle.VerticalAlign = VerticalAlign.Middle; + ColumnLabel.ItemStyle.HorizontalAlign = HorizontalAlign.Center; + this.Columns.Insert(0, ColumnLabel); + } + } + else + { + foreach (DataControlField item in this.Columns) + { + if (item.AccessibleHeaderText == "txtIndex_123456789") + { + this.Columns.Remove(item); + return; + } + } + } + } + + private void ShowCheckBox(bool Visible) + { + if (Visible==true) + { + bool bk = false; + foreach (DataControlField item in this.Columns) + { + if (item.AccessibleHeaderText != "CheckBoxSelect_123456789") continue; + bk = true; + break; + } + if (bk == false) + { + ColumnCheckBox = new GridViewColumnCheckBox(); + ColumnCheckBox.ControlID = "CheckBoxSelect_123456789"; + ColumnCheckBox.AccessibleHeaderText = "CheckBoxSelect_123456789"; + ColumnCheckBox.HeaderTemplate = new GridTemplateCheckBox("CheckBoxSelectAll_123456789", ""); + ColumnCheckBox.HeaderText = " "; + ColumnCheckBox.ItemStyle.VerticalAlign = VerticalAlign.Middle; + ColumnCheckBox.ItemStyle.HorizontalAlign = HorizontalAlign.Center; + this.Columns.Insert(0, ColumnCheckBox); + } + } + else + { + foreach (DataControlField item in this.Columns) + { + if (item.AccessibleHeaderText == "CheckBoxSelect_123456789") + { + this.Columns.Remove(item); + return; + } + } + } + } + + private void ShowRadioButton(bool Visible) + { + if (Visible==true) + { + bool bk = false; + foreach (DataControlField item in this.Columns) + { + if (item.AccessibleHeaderText != "RadioButtonSelect_123456789") continue; + bk = true; + break; + } + if (bk == false) + { + ColumnRadioButton = new GridViewColumnRadioButton(); + ColumnRadioButton.ControlID = "RadioButtonSelect_123456789"; + ColumnRadioButton.HeaderText = " "; + ColumnRadioButton.AccessibleHeaderText = "RadioButtonSelect_123456789"; + ColumnRadioButton.ItemStyle.VerticalAlign = VerticalAlign.Middle; + ColumnRadioButton.ItemStyle.HorizontalAlign = HorizontalAlign.Center; + this.Columns.Insert(0, ColumnRadioButton); + } + } + else + { + foreach (DataControlField item in this.Columns) + { + if (item.AccessibleHeaderText == "RadioButtonSelect_123456789") + { + this.Columns.Remove(item); + return; + } + } + } + } + + private void ShowButton(bool Visible) + { + if (Visible == true) + { + bool bk = false; + foreach (DataControlField item in this.Columns) + { + if (item.AccessibleHeaderText != "ColumnButton_123456789") continue; + bk = true; + break; + } + if (bk == false) + { + ColumnButton = new CommandField(); + ColumnButton.AccessibleHeaderText = "ColumnButton_123456789"; + ColumnButton.Visible = false; + ColumnButton.ShowSelectButton = true; + ColumnButton.ButtonType = ButtonType.Link; + this.Columns.Insert(0, ColumnButton); + } + + } + else + { + foreach (DataControlField item in this.Columns) + { + if (item.AccessibleHeaderText == "ColumnButton_123456789") + { + this.Columns.Remove(item); + return; + } + } + } + } + #endregion + + public System.Web.UI.WebControls.TableRow NewRow() + { + TableRow row=new TableRow(); + for (int i=0;idocument.getElementById('" + this.ClientID + "_MyDiv').scrollLeft=" + _yy_SmartGridViewAlpha_x + ";document.getElementById('" + this.ClientID + "_MyDiv').scrollTop=" + _yy_SmartGridViewAlpha_y + ";"); + // 将控件注册为要求在页回发至服务器时进行回发处理的控件 + } + if (this.RowCount > 0) + { + this.PaperCount =(int)Math.Ceiling(Convert.ToDecimal(this.RowCount) / Convert.ToDecimal(this.PageSize)); + this.FirstRowCount.Text = "记录总数:" + this.RowCount.ToString() + "条"; + this.FirstPagerCount.Text = "第" + Convert.ToString(this.PageIndex + 1) + "页/共" + this.PaperCount.ToString() + "页"; + this.LastRowCount.Text = "记录总数:" + this.RowCount.ToString() + "条"; + this.LastPagerCount.Text = "第" + Convert.ToString(this.PageIndex + 1) + "页/共" + this.PaperCount + "页"; + this.FirstDownListPager.Items.Clear(); + this.LastDownListPager.Items.Clear(); + for (int i = 1; i <= this.PaperCount; i++) + { + FirstDownListPager.Items.Add(new ListItem(i.ToString(), i.ToString())); + LastDownListPager.Items.Add(new ListItem(i.ToString(), i.ToString())); + } + if (this.PageIndex == 0) + { + this.SelectPagerIndex = 1; + FirstDownListPager.SelectedIndex = 0; + LastDownListPager.SelectedIndex = 0; + } + else + { + if (SelectPagerIndex != 0) + { + FirstDownListPager.SelectedValue = SelectPagerIndex.ToString(); + LastDownListPager.SelectedValue = SelectPagerIndex.ToString(); + } + } + } + + if (Page != null) Page.RegisterRequiresPostBack(this); + + } + + + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + if (this.DesignMode == false && this.Page.Request.Cookies[this.Page.GetType().ToString() + this.ClientID] != null) this.PageSize = Convert.ToInt32(this.Page.Request.Cookies[this.Page.GetType().ToString() + this.ClientID].Value); + ShowIndex(this.ShowIndexColumn); + switch (this.SelectMode) + { + case SelectMode.None: + ShowRadioButton(false); + ShowCheckBox(false); + ShowButton(false); + break; + case SelectMode.Post: + ShowButton(true); + ShowRadioButton(false); + ShowCheckBox(false); + break; + case SelectMode.RadioButton: + ShowRadioButton(true); + ShowCheckBox(false); + ShowButton(false); + break; + case SelectMode.CheckBox: + ShowCheckBox(true); + ShowRadioButton(false); + ShowButton(false); + break; + default: + break; + } + } + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + + } + protected override void OnDataBound(EventArgs e) + { + if (this.DesignMode == false && this.DataSource!=null) + { + if (this.PaperModel == 1) + { + if (this.DataSource.GetType() == typeof(DataSet)) + { + DataSet ds = (DataSet)this.DataSource; + if (this.DataMember != "") { this.View = ds.Tables[this.DataMember]; } + else { this.View = ds.Tables[0]; } + } + if (this.DataSource.GetType() == typeof(DataTable)) this.View = (DataTable)this.DataSource; + if (this.DataSource.GetType() == typeof(DataView)) this.View = ((DataView)this.DataSource).Table; + if (this.View != null) this.RowCount = this.View.DefaultView.Count; + } + } + base.OnDataBound(e); + } + + protected override void OnDataBinding(EventArgs e) + { + + //if (this.ShowIndexColumn==false)ShowIndex(false); + //switch (this.SelectMode) + //{ + // case SelectMode.None: + // ShowRadioButton(false); + // ShowCheckBox(false); + // ShowButton(false); + // break; + // case SelectMode.Post: + // ShowButton(true); + // ShowRadioButton(false); + // ShowCheckBox(false); + // break; + // case SelectMode.RadioButton: + // ShowRadioButton(true); + // ShowCheckBox(false); + // ShowButton(false); + // break; + // case SelectMode.CheckBox: + // ShowCheckBox(true); + // ShowRadioButton(false); + // ShowButton(false); + // break; + // default: + // break; + //} + if (this.RowCount > 0 && this.RowCount <= this.PageIndex * this.PageSize) { this.PageIndex = this.PageIndex - 1; this.SelectPagerIndex = this.PageIndex + 1; } + if (this.PageIndex * this.PageSize > this.RowCount) { this.PageIndex = 0; this.SelectPagerIndex = 1; } + base.OnDataBinding(e); + } + + + + + private void ListGridView_RowCreated(object sender, GridViewRowEventArgs e) + { + if (e.Row.RowType==DataControlRowType.Header) + { + if (this.HeaderChanged!=null) + { + HeaderEventArgs arg=new HeaderEventArgs(); + arg.Header=this.m_Header; + this.m_Header.Rows.Clear(); + this.HeaderChanged(this,arg); + e.Row.SetRenderMethodDelegate(new System.Web.UI.RenderMethod(this.HeradItemCreated)); + } + } + } + + void HeradItemCreated(HtmlTextWriter output,System.Web.UI.Control ctl) + { + + foreach (TableRow row in this.m_Header.Rows) + { + foreach (TableCell cell in row.Cells) + { + int colIndex = row.Cells.GetCellIndex(cell); + cell.BorderColor=this.BorderColor; + cell.BorderStyle=this.BorderStyle; + cell.BorderWidth=this.BorderWidth; + //cell.Width=this.Columns[row.Cells.GetCellIndex(cell)].ItemStyle.Width; + cell.Height=this.HeaderStyle.Height; + //cell.HorizontalAlign=this.HeaderStyle.HorizontalAlign; + cell.HorizontalAlign = HorizontalAlign.Center; + cell.VerticalAlign=this.HeaderStyle.VerticalAlign; + cell.BackColor=this.HeaderStyle.BackColor; + cell.Font.Bold=this.HeaderStyle.Font.Bold; + cell.Font.Italic=this.HeaderStyle.Font.Italic; + cell.Font.Name=this.HeaderStyle.Font.Name; + cell.Font.Names=this.HeaderStyle.Font.Names; + cell.Font.Overline=this.HeaderStyle.Font.Overline; + cell.Font.Size=this.HeaderStyle.Font.Size; + cell.Font.Strikeout=this.HeaderStyle.Font.Strikeout; + cell.Font.Underline=this.HeaderStyle.Font.Underline; + cell.ForeColor=this.HeaderStyle.ForeColor; + cell.CssClass = this.HeaderStyle.CssClass; + + if (this.IsFixHeader == true) + { + //e.Row.Attributes.Add("Style","z-index:999;vnd.ms-excel.numberformat:@;height:18px; position: relative; top: expression(this.offsetParent.scrollTop-2);"); + if (this.FixLeftColumns == 0 || colIndex >=this.FixLeftColumns) + { + cell.Attributes.Add("Style", "z-index:9998;vnd.ms-excel.numberformat:@; position: relative; top: expression(this.offsetParent.scrollTop-2);"); + } + else + { + cell.Attributes.Add("Style", "z-index:9999;vnd.ms-excel.numberformat:@; position: relative; top: expression(this.offsetParent.scrollTop-2);left: expression(this.offsetParent.scrollLeft);"); + } + + } + + cell.RenderControl(output); + } + output.WriteEndTag("TR"); + string style=""; + style=style+"color:"+this.HeaderStyle.ForeColor.Name.Replace("ff","#")+";"; + style=style+"background-color:"+this.HeaderStyle.BackColor.Name.Replace("ff","#")+";"; + style = style + "font-weight:bold;height:18px;"; + //this.HeaderStyle.AddAttributesToRender(output); + + + + if (this.m_Header.Rows.GetRowIndex(row) != this.m_Header.Rows.Count - 1) { output.Write(""); } + else + { + this.m_Header.Rows[this.m_Header.Rows.Count - 1].Attributes.Add("Style", style); + } + } +// for (int i=0;i 0) + { + colIndex = 0; + foreach (TableCell cell in e.Row.Cells) + { + //if (this.Columns[e.Row.Cells.GetCellIndex(cell)].Visible == false) continue; + if (colIndex == this.FixLeftColumns) break; + cell.Attributes.Add("Style", "z-index:999;vnd.ms-excel.numberformat:@;position: relative; left: expression(this.offsetParent.scrollLeft);FONT-WEIGHT: bold; BACKGROUND-COLOR: #ffffcc"); + colIndex++; + } + } + + if (this.ShowIndexColumn == true) + { + Label txtIndex = (Label)e.Row.FindControl("txtIndex_123456789"); + if (txtIndex!=null) txtIndex.Text = Convert.ToString(e.Row.RowIndex + 1 + this.PageIndex * this.PageSize); + } + + e.Row.Attributes.Add("Style", "vnd.ms-excel.numberformat:@;"); + if (this.ShowRowColor == true) + { + //e.Row.Attributes["onmouseover"] = "this.bgColor='#61AAF5';"; + //e.Row.Attributes["onmouseout"] = "this.bgColor='#ffffff';"; + e.Row.Attributes["onmouseover"] = "this.className='RowStyleSelect';"; + e.Row.Attributes["onmouseout"] = "this.className='RowStyle';"; + } + if (this.SelectMode == SelectMode.Post) + { + int CellIndex = 0; + if (this.ShowIndexColumn == true) CellIndex = 1; + LinkButton csel = new LinkButton(); + csel = (LinkButton)(e.Row.Cells[CellIndex].Controls[0]); + e.Row.Attributes["onclick"] = Page.ClientScript.GetPostBackClientHyperlink(csel, ""); + } + if (this.RowDoubleClick != null) + { + e.Row.Attributes["ondblclick"] = "doPostBack('ListGridView_DoubleClick','" + e.Row.RowIndex.ToString() + "');"; + } + + } + + if (e.Row.RowType == DataControlRowType.Header || e.Row.RowType == DataControlRowType.DataRow) + { + if (this.m_IsExport == true) + { + for (int i = 0; i < e.Row.Cells.Count; i++) + { + if (e.Row.Cells[i].Controls.Count == 0) continue; + //if (e.Row.Cells[i].Controls.Count>1) + //{ + // this.Columns[i].Visible=false; + // continue; + //} + for (int ii = 0; ii < e.Row.Cells[i].Controls.Count; ii++) + { + if (e.Row.Cells[i].Controls[ii].GetType().BaseType == typeof(Button) || e.Row.Cells[i].Controls[ii].GetType().BaseType == typeof(LinkButton) || e.Row.Cells[i].Controls[ii].GetType().BaseType == typeof(ImageButton) || e.Row.Cells[i].Controls[ii].GetType().BaseType == typeof(RadioButton) || e.Row.Cells[i].Controls[ii].GetType().BaseType == typeof(CheckBox) || e.Row.Cells[i].Controls[ii].GetType().BaseType == typeof(GridView) || e.Row.Cells[i].Controls[ii].GetType().BaseType == typeof(ListGridView) || e.Row.Cells[i].Controls[ii].GetType().Name == "GridViewLinkButton" || e.Row.Cells[i].Controls[ii].GetType().Name == "LinkButton" || e.Row.Cells[i].Controls[ii].GetType().Name == "TextBox") + { + this.Columns[i].Visible = false; + continue; + } + if (e.Row.Cells[i].Controls[0].GetType().BaseType == typeof(HyperLink)) + { + HyperLink hl = (HyperLink)e.Row.Cells[i].Controls[0]; + hl.Visible = false; + e.Row.Cells[i].Text = hl.Text; + continue; + } + if (e.Row.Cells[i].Controls[0].GetType().BaseType == typeof(TextBox)) + { + TextBox textBox = (TextBox)e.Row.Cells[i].Controls[0]; + textBox.Visible = false; + e.Row.Cells[i].Text = textBox.Text; + } + } + } + } + } + + base.OnRowDataBound(e); + + } + + + + #region 控件呈现 + /// + /// 将此控件呈现给指定的输出参数。 + /// + /// 要写出到的 HTML 编写器 + protected override void Render(HtmlTextWriter output) + { + base.EnsureChildControls(); + if (this.Rows.Count == 0) this.Height = Unit.Empty; + //如果固定页眉那么取消所有单元格文本换行 + if (this.CellWrap == false) + { + foreach (DataControlField col in this.Columns) + { col.HeaderStyle.Wrap = false; col.FooterStyle.Wrap = false; col.ItemStyle.Wrap = false; } + } + string TbStyle = " Style=\""; + foreach (string s in this.Style.Keys) + { + TbStyle = TbStyle + s + ":" + this.Style[s].ToString() + ";"; + } + if (this.Style.Keys.Count == 0) { TbStyle = ""; } + else { TbStyle = TbStyle + "\""; } + // if (this.Width.IsEmpty==false) + // { + // TbStyle=TbStyle+ " width=\""+this.Width.ToString()+"\""; + // } + + output.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID + "_123456789", false); + output.AddAttribute(HtmlTextWriterAttribute.Border, "0", false); + output.AddAttribute(HtmlTextWriterAttribute.Cellpadding, "0", false); + output.AddAttribute(HtmlTextWriterAttribute.Cellspacing, "0", false); + if (this.Width.ToString() != "") output.AddAttribute(HtmlTextWriterAttribute.Width, this.Width.ToString(), false); + if (this.Height.ToString() != "") output.AddAttribute(HtmlTextWriterAttribute.Height, this.Height.ToString(), false); + output.RenderBeginTag(HtmlTextWriterTag.Table); + + + + + #region 显示上面的分页按钮 + if (this.ShowFirstPager == true) + { + this.FirstButtonExcel.Style.Add("COLOR",this.UserPagerStyle.ForeColor.Name); + this.FirstButtonExcel.Attributes.Add("class",this.UserPagerStyle.TextCssClass); + //this.FirstButtonExcel.Attributes.Add("onclick",this.UserPagerStyle.MouseClickForeColor.Name); + //this.FirstButtonExcel.Attributes.Add("onmouseover", this.UserPagerStyle.MouseOverForeColor.Name); + //this.FirstButtonExcel.Attributes.Add("onmouseout", this.UserPagerStyle.ForeColor.Name); + + this.FirstButtonFirst.Style.Add("COLOR", this.UserPagerStyle.ForeColor.Name); + this.FirstButtonFirst.Attributes.Add("class", this.UserPagerStyle.TextCssClass); + //this.FirstButtonFirst.Attributes.Add("onclick", this.UserPagerStyle.MouseClickForeColor.Name); + //this.FirstButtonFirst.Attributes.Add("onmouseover", this.UserPagerStyle.MouseOverForeColor.Name); + //this.FirstButtonFirst.Attributes.Add("onmouseout", this.UserPagerStyle.ForeColor.Name); + + this.FirstButtonLast.Style.Add("COLOR", this.UserPagerStyle.ForeColor.Name); + this.FirstButtonLast.Attributes.Add("class", this.UserPagerStyle.TextCssClass); + //this.FirstButtonLast.Attributes.Add("onclick", this.UserPagerStyle.MouseClickForeColor.Name); + //this.FirstButtonLast.Attributes.Add("onmouseover", this.UserPagerStyle.MouseOverForeColor.Name); + //this.FirstButtonLast.Attributes.Add("onmouseout", this.UserPagerStyle.ForeColor.Name); + + this.FirstButtonNext.Style.Add("COLOR", this.UserPagerStyle.ForeColor.Name); + this.FirstButtonNext.Attributes.Add("class", this.UserPagerStyle.TextCssClass); + //this.FirstButtonNext.Attributes.Add("onclick", this.UserPagerStyle.MouseClickForeColor.Name); + //this.FirstButtonNext.Attributes.Add("onmouseover", this.UserPagerStyle.MouseOverForeColor.Name); + //this.FirstButtonNext.Attributes.Add("onmouseout", this.UserPagerStyle.ForeColor.Name); + + this.FirstButtonPrev.Style.Add("COLOR", this.UserPagerStyle.ForeColor.Name); + this.FirstButtonPrev.Attributes.Add("class", this.UserPagerStyle.TextCssClass); + //this.FirstButtonPrev.Attributes.Add("onclick", this.UserPagerStyle.MouseClickForeColor.Name); + //this.FirstButtonPrev.Attributes.Add("onmouseover", this.UserPagerStyle.MouseOverForeColor.Name); + //this.FirstButtonPrev.Attributes.Add("onmouseout", this.UserPagerStyle.ForeColor.Name); + + + this.FirstImageButtonFirst.ImageUrl = this.UserPagerStyle.FirstImageUrl; + this.FirstImageButtonLast.ImageUrl = this.UserPagerStyle.LastImageUrl; + this.FirstImageButtonNext.ImageUrl = this.UserPagerStyle.NextImageUrl; + this.FirstImageButtonPrev.ImageUrl = this.UserPagerStyle.PrevImageUrl; + + output.AddAttribute(HtmlTextWriterAttribute.Class, UserPagerStyle.PagerCssClass, false); + output.AddAttribute(HtmlTextWriterAttribute.Bgcolor, UserPagerStyle.BackColor.Name, false); + output.AddAttribute(HtmlTextWriterAttribute.Style, "font-size: 12px;", false); + output.RenderBeginTag(HtmlTextWriterTag.Tr); + string align = "Center"; + if (UserPagerStyle.Align == StringAlignment.Far) align = "left"; + if (UserPagerStyle.Align == StringAlignment.Near) align = "right"; + output.AddAttribute(HtmlTextWriterAttribute.Align, align, false); + output.AddAttribute(HtmlTextWriterAttribute.Valign, "Middle", false); + output.RenderBeginTag(HtmlTextWriterTag.Td); + if (this.UserPagerStyle.ShowExcelReport == true) + { + output.Write(" "); + this.FirstButtonExcel.Attributes.Add("class", this.UserPagerStyle.TextCssClass); + this.FirstButtonExcel.RenderControl(output); + } + if (this.UserPagerStyle.ShowPagerButton == true) + { + this.FirstTextBoxPageRowCount.Value = this.PageSize.ToString(); + output.Write(" "); + if (string.IsNullOrEmpty(this.UserPagerStyle.FirstImageUrl) == false) this.FirstImageButtonFirst.RenderControl(output); + this.FirstButtonFirst.RenderControl(output); + output.Write(" "); + if (string.IsNullOrEmpty(this.UserPagerStyle.PrevImageUrl)==false) this.FirstImageButtonPrev.RenderControl(output); + this.FirstButtonPrev.RenderControl(output); + output.Write(" "); + if (string.IsNullOrEmpty(this.UserPagerStyle.NextImageUrl)==false) this.FirstImageButtonNext.RenderControl(output); + this.FirstButtonNext.RenderControl(output); + output.Write(" "); + if (string.IsNullOrEmpty(this.UserPagerStyle.LastImageUrl)==false) this.FirstImageButtonLast.RenderControl(output); + this.FirstButtonLast.RenderControl(output); + output.Write(" "); + + this.FirstRowCount.ForeColor = this.UserPagerStyle.ForeColor; + this.FirstRowCount.CssClass = this.UserPagerStyle.TextCssClass; + this.FirstRowCount.RenderControl(output); + output.Write("  "); + this.FirstPagerCount.ForeColor = this.UserPagerStyle.ForeColor; + this.FirstPagerCount.CssClass = this.UserPagerStyle.TextCssClass; + this.FirstPagerCount.RenderControl(output); + output.Write("  "); + this.FirstPageRowCount.ForeColor = this.UserPagerStyle.ForeColor; + this.FirstPageRowCount.CssClass = this.UserPagerStyle.TextCssClass; + this.FirstPageRowCount.RenderControl(output); + //this.FirstTextBoxPageRowCount.ForeColor = this.UserPagerStyle.ForeColor; + //this.FirstTextBoxPageRowCount.CssClass = this.UserPagerStyle.TextCssClass; + this.FirstTextBoxPageRowCount.Style.Add("COLOR", this.UserPagerStyle.ForeColor.Name); + this.FirstTextBoxPageRowCount.Attributes.Add("class", this.UserPagerStyle.TextCssClass); + this.FirstTextBoxPageRowCount.RenderControl(output); + } + if (this.UserPagerStyle.ShowSelectPager == true) + { + output.Write("  "); + this.FirstGo.ForeColor = this.UserPagerStyle.ForeColor; + this.FirstGo.CssClass = this.UserPagerStyle.TextCssClass; + this.FirstGo.RenderControl(output); + this.FirstDownListPager.ForeColor = this.UserPagerStyle.ForeColor; + this.FirstDownListPager.CssClass = this.UserPagerStyle.TextCssClass; + this.FirstDownListPager.RenderControl(output); + } + output.RenderEndTag(); //结束TD + output.RenderEndTag(); //结束TR + } + #endregion + #region 显示GridView + output.AddAttribute(HtmlTextWriterAttribute.Width, "100%", false); + output.AddAttribute(HtmlTextWriterAttribute.Height, "100%", false); + output.RenderBeginTag(HtmlTextWriterTag.Tr); + output.AddAttribute(HtmlTextWriterAttribute.Valign, "top", false); + output.AddAttribute(HtmlTextWriterAttribute.Bgcolor, "white", false); + output.RenderBeginTag(HtmlTextWriterTag.Td); + if (this.IsFixHeader == true)//如果固定表头 + { + + output.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID + "_MyDiv", false); + string DivStyle = "POSITION: relative;OVERFLOW: auto; align: left;"; + if (this.Width.ToString() != "") DivStyle = DivStyle + "width:" + this.Width.ToString() + ";"; + if (this.Height.ToString() != "") DivStyle = DivStyle + "height:" + this.Height.ToString() + ";"; + output.AddAttribute(HtmlTextWriterAttribute.Style, DivStyle, false); + if (this.EnableScrollState == true) //如果保持滚动条的状态的话,用隐藏字段记录滚动条的位置 + { + output.AddAttribute("onscroll", "document.getElementById('" + this.ClientID + "yy_SmartGridViewAlpha_x').value = this.scrollLeft; document.getElementById('" + this.ClientID + "yy_SmartGridViewAlpha_y').value = this.scrollTop;", false); + } + //output.RenderBeginTag(HtmlTextWriterTag.Iframe); + } + //AddAttributesToRender(output); + if (this.Rows.Count == 0 && this.EmptyDataTemplate==null) + { + Table tb = new Table(); + tb.BorderWidth = this.BorderWidth; + tb.CssClass = this.CssClass; + tb.Width = this.Width; + tb.CellPadding = this.CellPadding; + tb.CellSpacing =this.CellSpacing; + TableHeaderRow row = new TableHeaderRow(); + row.CssClass= this.HeaderStyle.CssClass; + row.BackColor= this.HeaderStyle.BackColor; + row.BorderColor= this.HeaderStyle.BorderColor; + row.BorderStyle= this.HeaderStyle.BorderStyle; + row.ForeColor= this.HeaderStyle.ForeColor; + row.Height = this.HeaderStyle.Height; + row.HorizontalAlign= this.HeaderStyle.HorizontalAlign; + row.VerticalAlign = this.HeaderStyle.VerticalAlign; + row.Width= this.HeaderStyle.Width; + row.Font.Bold = this.HeaderStyle.Font.Bold; + row.Font.Italic = this.HeaderStyle.Font.Italic; + row.Font.Name = this.HeaderStyle.Font.Name; + row.Font.Names = this.HeaderStyle.Font.Names; + row.Font.Overline = this.HeaderStyle.Font.Overline; + row.Font.Size = this.HeaderStyle.Font.Size; + row.Font.Strikeout = this.HeaderStyle.Font.Strikeout; + row.Font.Underline = this.HeaderStyle.Font.Underline; + TableHeaderCell cel = null; + foreach (DataControlField col in this.Columns) + { + if (col.Visible == false) continue; + cel = new TableHeaderCell(); + cel.Text = col.HeaderText; + row.Cells.Add(cel); + } + tb.Rows.Add(row); + tb.RenderControl(output); + } + else + { + base.Render(output); + } + //if (this.IsFixHeader == true) output.RenderEndTag(); + output.RenderEndTag(); //结束TD + output.RenderEndTag(); //结束TR + #endregion + #region 显示下面的分页按钮 + if (this.ShowLastPager == true) + { + //this.LastButtonExcel.ForeColor = this.UserPagerStyle.ForeColor; + //this.LastButtonExcel.CssClass = this.UserPagerStyle.TextCssClass; + + this.LastButtonExcel.Style.Add("COLOR", this.UserPagerStyle.ForeColor.Name); + this.LastButtonExcel.Attributes.Add("class", this.UserPagerStyle.TextCssClass); + + //this.LastButtonExcel.Attributes.Add("onclick", "style.color="+this.UserPagerStyle.MouseClickForeColor.Name); + //this.LastButtonExcel.Attributes.Add("onmouseover", "style.color=" + this.UserPagerStyle.MouseOverForeColor.Name); + //this.LastButtonExcel.Attributes.Add("onmouseout", "style.color=" + this.UserPagerStyle.ForeColor.Name); + + + this.LastButtonFirst.Style.Add("COLOR", this.UserPagerStyle.ForeColor.Name); + this.LastButtonFirst.Attributes.Add("class", this.UserPagerStyle.TextCssClass); + //this.LastButtonFirst.Attributes.Add("onmouseout", "style.textDecorationUnderline=false;style.color=" + this.UserPagerStyle.MouseClickForeColor.Name); + //this.LastButtonFirst.Attributes.Add("onmouseover", "style.textDecorationUnderline=true;style.color=" + this.UserPagerStyle.MouseOverForeColor.Name); + //this.LastButtonFirst.Attributes.Add("onclick", "doPostBack('ButtonFirst','ButtonFirst');style.color=" + this.UserPagerStyle.ForeColor.Name); + + + this.LastButtonLast.Style.Add("COLOR", this.UserPagerStyle.ForeColor.Name); + this.LastButtonLast.Attributes.Add("class", this.UserPagerStyle.TextCssClass); + //this.LastButtonLast.Attributes.Add("onclick", "style.color=" + this.UserPagerStyle.MouseClickForeColor.Name); + //this.LastButtonLast.Attributes.Add("onmouseover", "style.color=" + this.UserPagerStyle.MouseOverForeColor.Name); + //this.LastButtonLast.Attributes.Add("onmouseout", "style.color=" + this.UserPagerStyle.ForeColor.Name); + + this.LastButtonNext.Style.Add("COLOR", this.UserPagerStyle.ForeColor.Name); + this.LastButtonNext.Attributes.Add("class", this.UserPagerStyle.TextCssClass); + //this.LastButtonNext.Attributes.Add("onclick", this.UserPagerStyle.MouseClickForeColor.Name); + //this.LastButtonNext.Attributes.Add("onmouseover", this.UserPagerStyle.MouseOverForeColor.Name); + //this.LastButtonNext.Attributes.Add("onmouseout", this.UserPagerStyle.ForeColor.Name); + + + this.LastButtonPrev.Style.Add("COLOR", this.UserPagerStyle.ForeColor.Name); + this.LastButtonPrev.Attributes.Add("class", this.UserPagerStyle.TextCssClass); + //this.LastButtonPrev.Attributes.Add("onclick", this.UserPagerStyle.MouseClickForeColor.Name); + //this.LastButtonPrev.Attributes.Add("onmouseover", this.UserPagerStyle.MouseOverForeColor.Name); + //this.LastButtonPrev.Attributes.Add("onmouseout", this.UserPagerStyle.ForeColor.Name); + + + this.LastImageButtonFirst.ImageUrl = this.UserPagerStyle.FirstImageUrl; + this.LastImageButtonLast.ImageUrl = this.UserPagerStyle.LastImageUrl; + this.LastImageButtonNext.ImageUrl = this.UserPagerStyle.NextImageUrl; + this.LastImageButtonPrev.ImageUrl = this.UserPagerStyle.PrevImageUrl; + + output.AddAttribute(HtmlTextWriterAttribute.Class, UserPagerStyle.PagerCssClass, false); + //output.AddAttribute(HtmlTextWriterAttribute.Bgcolor, UserPagerStyle.BackColor.Name, false); + output.AddAttribute(HtmlTextWriterAttribute.Style, "font-size: 12px;", false); + output.RenderBeginTag(HtmlTextWriterTag.Tr); + string align = "Center"; + if (UserPagerStyle.Align == StringAlignment.Far) align = "left"; + if (UserPagerStyle.Align == StringAlignment.Near) align = "right"; + output.AddAttribute(HtmlTextWriterAttribute.Align, align, false); + output.AddAttribute(HtmlTextWriterAttribute.Valign, "Middle", false); + output.RenderBeginTag(HtmlTextWriterTag.Td); + if (this.UserPagerStyle.ShowExcelReport == true) + { + output.Write(" "); + this.LastButtonExcel.Attributes.Add("class", this.UserPagerStyle.TextCssClass); + this.LastButtonExcel.RenderControl(output); + } + if (this.UserPagerStyle.ShowPagerButton == true) + { + //this.LastTextBoxPageRowCount.CssClass = this.UserPagerStyle.TextCssClass; + this.LastTextBoxPageRowCount.Style.Add("COLOR", this.UserPagerStyle.ForeColor.Name); + this.LastTextBoxPageRowCount.Attributes.Add("class", this.UserPagerStyle.TextCssClass); + this.LastTextBoxPageRowCount.Value = this.PageSize.ToString(); + output.Write(" "); + if (string.IsNullOrEmpty(this.UserPagerStyle.FirstImageUrl)==false) this.LastImageButtonFirst.RenderControl(output); + this.LastButtonFirst.RenderControl(output); + output.Write(" "); + if (string.IsNullOrEmpty(this.UserPagerStyle.PrevImageUrl)==false) this.LastImageButtonPrev.RenderControl(output); + this.LastButtonPrev.RenderControl(output); + output.Write(" "); + if (string.IsNullOrEmpty(this.UserPagerStyle.NextImageUrl)==false) this.LastImageButtonNext.RenderControl(output); + this.LastButtonNext.RenderControl(output); + output.Write(" "); + if (string.IsNullOrEmpty(this.UserPagerStyle.LastImageUrl) == false) this.LastImageButtonLast.RenderControl(output); + this.LastButtonLast.RenderControl(output); + output.Write(" "); + this.LastRowCount.CssClass = this.UserPagerStyle.TextCssClass; + this.LastRowCount.RenderControl(output); + output.Write("  "); + this.LastPagerCount.CssClass = this.UserPagerStyle.TextCssClass; + this.LastPagerCount.RenderControl(output); + output.Write(" "); + this.LastPageRowCount.CssClass = this.UserPagerStyle.TextCssClass; + this.LastPageRowCount.RenderControl(output); + this.LastTextBoxPageRowCount.RenderControl(output); + } + if (this.UserPagerStyle.ShowSelectPager == true) + { + output.Write(" "); + this.LastGo.CssClass = this.UserPagerStyle.TextCssClass; + this.LastGo.RenderControl(output); + this.LastDownListPager.CssClass = this.UserPagerStyle.TextCssClass; + this.LastDownListPager.RenderControl(output); + } + output.RenderEndTag(); //结束TD + output.RenderEndTag(); //结束TR + } + #endregion + output.RenderEndTag(); //结束TABLE + + + } + #endregion + + + + protected override void LoadViewState(object savedState) + { + base.LoadViewState(savedState); + if (ViewState["m_UserPagerStyle"] != null) m_UserPagerStyle = (UserPagerStyle)ViewState["m_UserPagerStyle"]; + + } + + protected override object SaveViewState() + { + if (m_UserPagerStyle != null) ViewState["m_UserPagerStyle"] = m_UserPagerStyle; + return base.SaveViewState(); + } + + protected override void TrackViewState() + { + base.TrackViewState(); + } + + + + + + #region 要继承IPostBackDataHandler接口 + void IPostBackDataHandler.RaisePostDataChangedEvent() + { + + } + + + bool IPostBackDataHandler.LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection) + { + // 获取两个保存了 固定行、列后 的GridView滚动条的位置信息 + if (postCollection[this.ClientID + "yy_SmartGridViewAlpha_x"] != null) this._yy_SmartGridViewAlpha_x = Convert.ToInt32(postCollection[this.ClientID + "yy_SmartGridViewAlpha_x"]); + if (postCollection[this.ClientID + "yy_SmartGridViewAlpha_y"] != null) this._yy_SmartGridViewAlpha_y = Convert.ToInt32(postCollection[this.ClientID + "yy_SmartGridViewAlpha_y"]); + string CommandArgument = ""; + if (postCollection["__EVENTTARGET"] != null) CommandArgument = Convert.ToString(postCollection["__EVENTTARGET"]); + if (CommandArgument != "ListGridView_DoubleClick" && CommandArgument != "ButtonFirst" && CommandArgument != "ButtonPrev" && CommandArgument != "ButtonNext" && CommandArgument != "ButtonLast" && CommandArgument != "ButtonExcel" && CommandArgument != "TextBoxPageRowCount" && CommandArgument != "ListPager") return false; + switch (CommandArgument) + { + case "ListGridView_DoubleClick": + this.RowDoubleClick(null,new GridViewRowEventArgs(this.Rows[Convert.ToInt32(postCollection["__EVENTARGUMENT"])])); + break; + case "ButtonFirst": + ButtonFirst_Click(null, null); + break; + case "ButtonPrev": + ButtonPrev_Click(null, null); + break; + case "ButtonNext": + ButtonNext_Click(null, null); + break; + case "ButtonLast": + ButtonLast_Click(null, null); + break; + case "ButtonExcel": + ExcelReport("utf-8"); + break; + case "TextBoxPageRowCount": + string s = Convert.ToString(postCollection["__EVENTARGUMENT"]); + if (DataRegex.IsNumberInteger(s, true) == false) return false; + this.PageIndex = 0; + if (Convert.ToInt32(s) > 0) { this.PageSize = Convert.ToInt32(s); } + else { this.PageSize = 10; } + this.Page.Response.Cookies[this.Page.GetType().ToString() + this.ClientID].Expires = DateTime.Now.AddDays(7); + this.Page.Response.Cookies[this.Page.GetType().ToString() + this.ClientID].Value = this.PageSize.ToString(); + //if (this.PagerChanged != null) this.PagerChanged(this, null); + this.View.DefaultView.Sort = this.ViewSortString; + this.DataSource = this.View.DefaultView; + this.DataBind(); + break; + case "ListPager": + SetPager(Convert.ToInt32(postCollection["__EVENTARGUMENT"])); + break; + default: + break; + } + + return false; + } + #endregion + + #region Excel导出 + public static void ExcelReportOWC(System.Web.UI.Page page, string EncodingName, string fileName, DataTable tb, HuizhongLibrary.ReportPrint.TableColumnCollection Columns) + { + HSSFWorkbook workbook = new HSSFWorkbook(); + HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet("Sheet1"); + //填充表头 + HSSFRow dataRow = (HSSFRow)sheet.CreateRow(0); + foreach (HuizhongLibrary.ReportPrint.TableColumn item in Columns) + { + int index = Columns.IndexOf(item); + HSSFCell dataCell = (HSSFCell)dataRow.CreateCell(index); + dataCell.SetCellValue(item.Caption); + dataCell.CellStyle.Alignment = HorizontalAlignment.Center; + } + + //填充内容 + for (int i = 0; i < tb.Rows.Count; i++) + { + dataRow = (HSSFRow)sheet.CreateRow(i + 1); + HSSFCell dataCell = null; + foreach (HuizhongLibrary.ReportPrint.TableColumn item in Columns) + { + int j = Columns.IndexOf(item); + dataCell = (HSSFCell)dataRow.CreateCell(j); + if (item.Format != "") + { + dataCell.SetCellValue(DataConvert.Format(tb.Rows[i][item.Name].ToString(), item.Format)); + } + else + { + dataCell.SetCellValue(tb.Rows[i][item.Name].ToString()); + } + dataCell.CellStyle.Alignment = HorizontalAlignment.Center; + } + } + + string filename = Guid.NewGuid().ToString() + ".xls"; + string DirectoryName = AppDomain.CurrentDomain.BaseDirectory + "ServerCookies"; + if (System.IO.Directory.Exists(DirectoryName) == false) System.IO.Directory.CreateDirectory(DirectoryName); + string ServerFileName = DirectoryName + "/" + filename; + //保存 + using (FileStream fs = new FileStream(ServerFileName, FileMode.Create, FileAccess.Write)) + { + workbook.Write(fs); + } + workbook.Close(); + + FileStream fs2 = new FileStream(ServerFileName, FileMode.Open, FileAccess.Read); + int FileLength = (int)fs2.Length; + byte[] FileBuffer = new byte[FileLength]; + fs2.Read(FileBuffer, 0, FileLength); + fs2.Close(); + fs2.Dispose(); + + + string cFileName = Path.GetFileName(fileName); + page.Response.Clear(); + page.Response.Buffer = true; + page.Response.ContentType = "application/octet-stream"; + page.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(cFileName, System.Text.Encoding.GetEncoding(EncodingName))); + // Response.AppendHeader("Content-Length",FileLength.ToString()); + page.Response.ContentEncoding = System.Text.Encoding.GetEncoding(EncodingName); //设置输出流为简体中文 + System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true); + page.Response.BinaryWrite(FileBuffer); + page.Response.End(); + + + } + + + public static void ExcelReportOWC(System.Web.UI.Page page, string EncodingName, string fileName, DataTable tb, string HeaderName, HuizhongLibrary.ReportPrint.TableColumnCollection Columns) + { + HSSFWorkbook workbook = new HSSFWorkbook(); + HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet("Sheet1"); + HSSFRow dataRow = null; + HSSFCell dataCell = null; + int RowIndex = 0; + if (HeaderName != "") + { + dataRow = (HSSFRow)sheet.CreateRow(0); + dataCell = (HSSFCell)dataRow.CreateCell(0); + dataCell.SetCellValue(HeaderName); + dataCell.CellStyle.Alignment = HorizontalAlignment.Center; + sheet.AddMergedRegion(new NPOI.SS.Util.Region(0, 0, 0, Columns.Count - 1)); + RowIndex++; + } + //填充表头 + dataRow = (HSSFRow)sheet.CreateRow(RowIndex); + foreach (HuizhongLibrary.ReportPrint.TableColumn item in Columns) + { + int index = Columns.IndexOf(item); + dataCell = (HSSFCell)dataRow.CreateCell(index); + dataCell.SetCellValue(item.Caption); + dataCell.CellStyle.Alignment = HorizontalAlignment.Center; + } + RowIndex++; + + //填充内容 + for (int i = 0; i < tb.Rows.Count; i++) + { + dataRow = (HSSFRow)sheet.CreateRow(i + RowIndex); + foreach (HuizhongLibrary.ReportPrint.TableColumn item in Columns) + { + int j = Columns.IndexOf(item); + dataCell = (HSSFCell)dataRow.CreateCell(j); + if (item.Format != "") + { + dataCell.SetCellValue(DataConvert.Format(tb.Rows[i][item.Name].ToString(), item.Format)); + } + else + { + dataCell.SetCellValue(tb.Rows[i][item.Name].ToString()); + } + dataCell.CellStyle.Alignment = HorizontalAlignment.Center; + } + } + + string filename = Guid.NewGuid().ToString() + ".xls"; + string DirectoryName = AppDomain.CurrentDomain.BaseDirectory + "ServerCookies"; + if (System.IO.Directory.Exists(DirectoryName) == false) System.IO.Directory.CreateDirectory(DirectoryName); + string ServerFileName = DirectoryName + "/" + filename; + //保存 + using (FileStream fs = new FileStream(ServerFileName, FileMode.Create, FileAccess.Write)) + { + workbook.Write(fs); + } + workbook.Close(); + + FileStream fs2 = new FileStream(ServerFileName, FileMode.Open, FileAccess.Read); + int FileLength = (int)fs2.Length; + byte[] FileBuffer = new byte[FileLength]; + fs2.Read(FileBuffer, 0, FileLength); + fs2.Close(); + fs2.Dispose(); + + string cFileName = Path.GetFileName(fileName); + page.Response.Clear(); + page.Response.Buffer = true; + page.Response.ContentType = "application/octet-stream"; + page.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(cFileName, System.Text.Encoding.GetEncoding(EncodingName))); + // Response.AppendHeader("Content-Length",FileLength.ToString()); + page.Response.ContentEncoding = System.Text.Encoding.GetEncoding(EncodingName); //设置输出流为简体中文 + System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true); + page.Response.BinaryWrite(FileBuffer); + page.Response.End(); + + + } + + public static string ExcelReportOWC(DataTable tb, HuizhongLibrary.ReportPrint.TableColumnCollection Columns) + { + HSSFWorkbook workbook = new HSSFWorkbook(); + HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet("Sheet1"); + //填充表头 + HSSFRow dataRow = (HSSFRow)sheet.CreateRow(0); + foreach (HuizhongLibrary.ReportPrint.TableColumn item in Columns) + { + int index = Columns.IndexOf(item); + HSSFCell dataCell = (HSSFCell)dataRow.CreateCell(index); + dataCell.SetCellValue(item.Caption); + dataCell.CellStyle.Alignment = HorizontalAlignment.Center; + } + + //填充内容 + for (int i = 0; i < tb.Rows.Count; i++) + { + dataRow = (HSSFRow)sheet.CreateRow(i + 1); + HSSFCell dataCell = null; + foreach (HuizhongLibrary.ReportPrint.TableColumn item in Columns) + { + int j = Columns.IndexOf(item); + dataCell = (HSSFCell)dataRow.CreateCell(j); + if (item.Format != "") + { + dataCell.SetCellValue(DataConvert.Format(tb.Rows[i][item.Name].ToString(), item.Format)); + } + else + { + dataCell.SetCellValue(tb.Rows[i][item.Name].ToString()); + } + dataCell.CellStyle.Alignment = HorizontalAlignment.Center; + } + } + + string filename = Guid.NewGuid().ToString() + ".xls"; + string DirectoryName = AppDomain.CurrentDomain.BaseDirectory + "ServerCookies"; + if (System.IO.Directory.Exists(DirectoryName) == false) System.IO.Directory.CreateDirectory(DirectoryName); + string ServerFileName = DirectoryName + "/" + filename; + //保存 + using (FileStream fs = new FileStream(ServerFileName, FileMode.Create, FileAccess.Write)) + { + workbook.Write(fs); + } + workbook.Close(); + return "ServerCookies/" + filename; + } + + #endregion + + + + + public void ExcelReport(string EncodingName) + { + this.SelectedIndex = -1; + this.ShowFirstPager = false; + this.ShowLastPager = false; + this.PageIndex = 0; + this.AllowPaging = false; + this.m_IsExport = true; + if (this.PagerChanged != null) this.PagerChanged(this, null); + this.Page.Response.Clear(); + this.Page.Response.Buffer = true; + this.Page.Response.Charset = EncodingName; + string filename=DateTime.Today.ToString("yyyyMMdd") + ".xls"; + this.Page.Response.AppendHeader("Content-Disposition","attachment;filename=" + HttpUtility.UrlEncode(filename,System.Text.Encoding.GetEncoding("utf-7"))); + this.Page.Response.ContentEncoding =System.Text.Encoding.GetEncoding(EncodingName); //设置输出流为简体中文 + this.Page.Response.ContentType = "application/ms-excel"; //设置输出文件类型为excel文件。 + this.EnableViewState = false; + System.Globalization.CultureInfo myCItrad= new System.Globalization.CultureInfo("ZH-CN", true); + System.IO.StringWriter oStringWriter=new System.IO.StringWriter(myCItrad); +// System.IO.StringWriter oStringWriter=new System.IO.StringWriter(); + System.Web.UI.HtmlTextWriter oHtmlTextWriter= new System.Web.UI.HtmlTextWriter(oStringWriter); + this.RenderControl(oHtmlTextWriter); + + this.Page.Response.Write(oStringWriter.ToString()); + this.Page.Response.End(); + } + + + private void SetPager(int pagerID) + { + this.SelectPagerIndex=pagerID; + this.PageIndex=pagerID-1; + if (this.View == null) { if (this.PagerChanged != null)this.PagerChanged(null, null); } + else + { + this.View.DefaultView.Sort = this.ViewSortString; + this.DataSource = this.View.DefaultView; + this.DataBind(); + } + } + + protected void ButtonFirst_Click(object sender, EventArgs e) + { + if (this.PaperCount==0)return; + this.PageIndex=0; + this.SelectPagerIndex=PageIndex+1; + if (this.View == null) { if (this.PagerChanged != null)this.PagerChanged(sender, e); } + else + { + this.View.DefaultView.Sort = this.ViewSortString; + this.DataSource = this.View.DefaultView; + this.DataBind(); + } + } + + protected void ButtonPrev_Click(object sender, EventArgs e) + { + if (this.PaperCount==0)return; + if (this.PageIndex > 0){this.PageIndex -= 1;} + this.SelectPagerIndex=PageIndex+1; + if (this.View == null) { if (this.PagerChanged != null)this.PagerChanged(sender, e); } + else + { + this.View.DefaultView.Sort = this.ViewSortString; + this.DataSource = this.View.DefaultView; + this.DataBind(); + } + } + + protected void ButtonNext_Click(object sender, EventArgs e) + { + if (this.PaperCount==0)return; + if (this.PageIndex < (this.PaperCount - 1)){this.PageIndex += 1;} + this.SelectPagerIndex=PageIndex+1; + if (this.View == null) { if (this.PagerChanged != null)this.PagerChanged(sender, e); } + else + { + + this.View.DefaultView.Sort = this.ViewSortString; + //Microsoft.Practices.EnterpriseLibrary.Follow.ErrorFollow.TraceWrite(this.GetType().ToString(), "", this.View.DefaultView.Sort); + this.DataSource = this.View.DefaultView; + this.DataBind(); + } + } + + protected void ButtonLast_Click(object sender, EventArgs e) + { + if (this.PaperCount==0)return; + this.PageIndex = (this.PaperCount - 1); + this.SelectPagerIndex=PageIndex+1; + if (this.View == null) { if (this.PagerChanged != null)this.PagerChanged(sender, e); } + else + { + this.View.DefaultView.Sort = this.ViewSortString; + this.DataSource = this.View.DefaultView; + this.DataBind(); + } + + + } + + + } + + public enum SelectMode + { + None = 0, + Post = 1, + RadioButton = 2, + CheckBox = 3 + } + + + + #region DropDownList列 + public class DropDownListField : BoundField + { + + /// + ///获取或设置要生成的控件ID + /// + public string ControlID + { + get { return (string)this.ViewState["ControlID"]; } + set { this.ViewState["ControlID"] = value; } + } + + public Unit Width + { + get { return this.ItemStyle.Width; } + set { this.ItemStyle.Width = value; } + } + + /// + /// 样式 + /// + public string CssClass + { + get { return (string)this.ViewState["CssClass"]; } + set { this.ViewState["CssClass"] = value; } + } + + public object DataSource + { + get { return this.ViewState["DataSource"]; } + set { this.ViewState["DataSource"] = value; } + } + + public string DataTextField + { + get { return (string)this.ViewState["DataTextField"]; } + set { this.ViewState["DataTextField"] = value; } + } + + public string DataValueField + { + get { return (string)this.ViewState["DataValueField"]; } + set { this.ViewState["DataValueField"] = value; } + } + + public Dictionary ListItems + { + get { return (Dictionary)this.ViewState["ListItems"]; } + set { this.ViewState["ListItems"] = value; } + } + + + protected override void InitializeDataCell(DataControlFieldCell cell, DataControlRowState rowState) + { + DropDownList child = new DropDownList(); + child.ID = this.ControlID; + child.CssClass = this.CssClass; + child.Attributes.Add("ColName", this.DataField); + if (DataSource != null) + { + child.DataSource = DataSource; + if (DataTextField!="") child.DataTextField = DataTextField; + if (DataValueField != "") child.DataValueField = DataValueField; + child.DataBind(); + } + else + { + foreach (string item in this.ListItems.Keys) + { + child.Items.Add(new ListItem(this.ListItems[item].ToString(), item)); + } + } + + + + if (child != null) + { + cell.Controls.Add(child); + } + if ((child != null) && base.Visible) + { + child.DataBinding += new EventHandler(this.OnDataBindField); + } + } + + protected override void OnDataBindField(object sender, EventArgs e) + { + DropDownList control = (DropDownList)sender; + //System.Web.UI.Control namingContainer = control.NamingContainer; + + GridViewRow dgi = (GridViewRow)control.Parent.NamingContainer; + DataRowView drv = (DataRowView)dgi.DataItem; + string value = Convert.ToString(drv[this.DataField]); + if (value == "") return; + if (control.Items.FindByValue(value)==null)return; + control.SelectedValue = value; + } + + + + + } + #endregion + + #region MaskedTextBox列 + public class MaskedTextBoxField : BoundField + { + + /// + ///获取或设置要生成的控件ID + /// + public string ControlID + { + get { return (string)this.ViewState["ControlID"]; } + set { this.ViewState["ControlID"] = value; } + } + + public Unit Width + { + get { return this.ItemStyle.Width; } + set { this.ItemStyle.Width = value; } + } + + /// + /// 样式 + /// + public string CssClass + { + get { return (string)this.ViewState["CssClass"]; } + set { this.ViewState["CssClass"] = value; } + } + + /// + /// 最小值 + /// + public float MinValue + { + get + { + if (this.ViewState["MinValue"] == null) return 0; + return (float)this.ViewState["MinValue"]; + } + set { this.ViewState["MinValue"] = value; } + } + + /// + /// 最大值 + /// + public float MaxValue + { + get + { + if (this.ViewState["MaxValue"] == null) return float.MaxValue; + return (float)this.ViewState["MaxValue"]; + } + set { this.ViewState["MaxValue"] = value; } + } + + public InputMode InputMode + { + get + { + if (this.ViewState["InputMode"] == null) return InputMode.None; + return (InputMode)this.ViewState["InputMode"]; + } + set { this.ViewState["InputMode"] = value; } + } + + /// + /// 文本框行模式 + /// + public TextBoxMode TextMode + { + get + { + if (this.ViewState["TextMode"] == null) return TextBoxMode.SingleLine; + return (TextBoxMode)this.ViewState["TextMode"]; + } + set { this.ViewState["TextMode"] = value; } + } + private Unit m_TextBoxHeight; + /// + /// 文本框高度 + /// + public Unit TextBoxHeight + { + get { return m_TextBoxHeight; } + set { m_TextBoxHeight = value; } + } + + protected override void InitializeDataCell(DataControlFieldCell cell, DataControlRowState rowState) + { + MaskedTextBox child = new MaskedTextBox(); + child.ID = this.ControlID; + child.CssClass = this.CssClass; + child.MinValue = MinValue; + child.MaxValue = MaxValue; + child.InputMode = InputMode; + child.CssClass = CssClass; + child.Width = new Unit("100%"); + child.TextMode = TextMode; + if (m_TextBoxHeight != null) child.Height = m_TextBoxHeight; + child.Attributes.Add("autocomplete", "off"); + if (InputMode == InputMode.DateTime) { child.Attributes.Add("style", "text-align: Center;"); } + if (InputMode == InputMode.Int || InputMode == InputMode.Float) { child.Attributes.Add("style", "ime-mode: disabled;text-align: Center;"); } + if (child != null) + { + cell.Controls.Add(child); + } + if ((child != null) && base.Visible) + { + child.DataBinding += new EventHandler(this.OnDataBindField); + } + } + + protected override void OnDataBindField(object sender, EventArgs e) + { + MaskedTextBox control = (MaskedTextBox)sender; + //System.Web.UI.Control namingContainer = control.NamingContainer; + + GridViewRow dgi = (GridViewRow)control.Parent.NamingContainer; + DataRowView drv = (DataRowView)dgi.DataItem; + //string FormatString = ""; + //string[] ss = this.DataFormatString.Split(':'); + //if (ss.Length == 2) + //{ + // FormatString = ss[1].Remove(ss[1].Length - 1); + //} + string value = DataConvert.Format(drv[this.DataField], this.DataFormatString); + control.Text = value; + + } + + + + + } + #endregion + #region DropDownList列 + public class CheckField : BoundField + { + + /// + ///获取或设置要生成的控件ID + /// + public string ControlID + { + get { return (string)this.ViewState["ControlID"]; } + set { this.ViewState["ControlID"] = value; } + } + + public Unit Width + { + get { return this.ItemStyle.Width; } + set { this.ItemStyle.Width = value; } + } + + /// + /// 样式 + /// + public string CssClass + { + get { return (string)this.ViewState["CssClass"]; } + set { this.ViewState["CssClass"] = value; } + } + + + + + protected override void InitializeDataCell(DataControlFieldCell cell, DataControlRowState rowState) + { + CheckBox child = new CheckBox(); + child.ID = this.ControlID; + child.CssClass = this.CssClass; + child.Attributes.Add("ColName", this.DataField); + + if (child != null) + { + cell.Controls.Add(child); + } + if ((child != null) && base.Visible) + { + child.DataBinding += new EventHandler(this.OnDataBindField); + } + } + + protected override void OnDataBindField(object sender, EventArgs e) + { + CheckBox control = (CheckBox)sender; + //System.Web.UI.Control namingContainer = control.NamingContainer; + + GridViewRow dgi = (GridViewRow)control.Parent.NamingContainer; + DataRowView drv = (DataRowView)dgi.DataItem; + string value = Convert.ToString(drv[this.DataField]); + if (value == "") return; + try + { + control.Checked =Convert.ToBoolean(value); + } + catch + { + } + + } + + + + + } + #endregion + + + #region Label列 + public class GridViewColumnLabel : TemplateField + { + GridTemplateLabel Templat = new GridTemplateLabel(); + /// + /// 获取或设置要生成的控件ID + /// + [Description("获取或设置要生成的控件ID"), DefaultValue("Label1"), Category("扩展")] + public string ControlID + { + get { return Templat.ControlID; } + set { Templat.ControlID = value; } + } + /// + /// 获取或设置要绑定到数据源的字段名称 + /// + [Description("获取或设置要绑定到数据源的字段名称"), DefaultValue(""), Category("扩展")] + public string DataField + { + get { return Templat.DataField; } + set { Templat.DataField = value; } + } + [Description("宽度"), DefaultValue("100px"), Category("扩展")] + public Unit Width + { + get { return this.ItemStyle.Width; } + set { this.ItemStyle.Width = value; } + } + + /// + /// 空值时显示的字符串 + /// + [Description("空值时显示的字符串ID"), DefaultValue(""), Category("扩展")] + public string NullText + { + get { return Templat.NullText; } + set { Templat.NullText = value; } + } + /// + /// 格式化方式 + /// + [Description("格式化方式ID"), DefaultValue(""), Category("扩展")] + public string FormatString + { + get { return Templat.FormatString; } + set { Templat.FormatString = value; } + } + /// + /// 获取或设置要在列中显示的最大字数(默认10) + /// + [Description("获取或设置要在列中显示的最大字数"), DefaultValue("10"), Category("扩展")] + public int ShowWordCount + { + get { return Templat.ShowWordCount; } + set { Templat.ShowWordCount = value; } + } + + + public GridViewColumnLabel() + { + this.ItemTemplate = Templat; + } + public GridViewColumnLabel(string ControlID, string HeaderText, string DataField, string AccessibleHeaderText,string FormatString) + { + Templat.ControlID = ControlID; + Templat.DataField = DataField; + Templat.FormatString = FormatString; + Templat.NullText = NullText; + Templat.ShowWordCount = ShowWordCount; + this.HeaderText = HeaderText; + this.ItemTemplate = Templat; + this.AccessibleHeaderText = AccessibleHeaderText; + } + public GridViewColumnLabel(string ControlID, string HeaderText, string DataField, string AccessibleHeaderText,string FormatString, Unit Width) + { + Templat.ControlID = ControlID; + Templat.DataField = DataField; + Templat.FormatString = FormatString; + Templat.NullText = NullText; + Templat.ShowWordCount = ShowWordCount; + this.HeaderText = HeaderText; + this.ItemStyle.Width = Width; + this.ItemTemplate = Templat; + this.AccessibleHeaderText = AccessibleHeaderText; + } + } + #endregion + #region 模板列Label + public class GridTemplateLabel : ITemplate + { //模板列Label + private string m_ControlID = "Label1"; + /// + /// 获取或设置要生成的控件ID + /// + [Description("获取或设置要生成的控件"), DefaultValue(""), Category("扩展"), Browsable(true)] + public string ControlID + { + get { return this.m_ControlID; } + set + { + this.m_ControlID = value; + + } + } + private string m_DataField; + /// + /// 获取或设置要绑定到数据源的字段名称 + /// + [Description("获取或设置要绑定到数据源的字段名称"), DefaultValue(""), Category("扩展"), Browsable(true)] + public string DataField + { + get { return this.m_DataField; } + set { this.m_DataField = value; } + } + private int m_ShowWordCount = 10; + /// + /// 获取或设置要在列中显示的最大字数(默认10) + /// + [Description("获取或设置要在列中显示的最大字数(默认10)"), DefaultValue(""), Category("扩展"), Browsable(true)] + public int ShowWordCount + { + get { return this.m_ShowWordCount; } + set { this.m_ShowWordCount = value; } + } + private string m_NullText=""; + /// + /// 空值时显示的字符串 + /// + [Description("空值时显示的字符串"), DefaultValue(""), Category("扩展"), Browsable(true)] + public string NullText + { + get { return this.m_NullText; } + set { this.m_NullText = value; } + } + private string m_FormatStringString; + /// + /// 格式化方式 + /// + public string FormatString + { + get { return this.m_FormatStringString; } + set { this.m_FormatStringString = value; } + } + private Label m_Label1; + public Label Label + { + get { return this.m_Label1; } + } + + public GridTemplateLabel() + { + + } + public GridTemplateLabel(string controlID, string dataField) + { + this.DataField = dataField; + this.ControlID = controlID; + } + public void InstantiateIn(System.Web.UI.Control container) + { + m_Label1 = new Label(); + m_Label1.ID = ControlID; + if (this.DataField != "" && this.DataField != null) m_Label1.DataBinding += new EventHandler(Label1_DataBinding); + container.Controls.Add(m_Label1); + } + void Label1_DataBinding(object sender, EventArgs e) + { + GridViewRow dgi = (GridViewRow)m_Label1.NamingContainer; + DataRowView drv = (DataRowView)dgi.DataItem; + string Text = DataConvert.Format(drv[this.DataField],this.FormatString); + if (Text == "" || Text==null) Text = this.NullText; + if (Text==null)Text=""; + if (Text.Length > this.ShowWordCount) { m_Label1.Text = Text.Substring(0, this.ShowWordCount); } + else { m_Label1.Text = Text; } + m_Label1.ToolTip = Text; + } + } + #endregion + + + #region RadioButton列 + public class GridViewColumnRadioButton : TemplateField + { + GridTemplateRadioButton Templat = new GridTemplateRadioButton(); + /// + /// 获取或设置要生成的控件ID + /// + [Description("获取或设置要生成的控件"), DefaultValue("false"), Category("扩展"), Browsable(true)] + public string ControlID + { + get { return Templat.ControlID; } + set { Templat.ControlID = value; } + } + [Description("宽度"), DefaultValue("false"), Category("扩展"), Browsable(true)] + public Unit Width + { + get { return this.ItemStyle.Width; } + set { this.ItemStyle.Width = value; } + } + public GridViewColumnRadioButton() + { + this.ItemStyle.Width = new Unit("30px"); + this.ItemTemplate = Templat; + } + public GridViewColumnRadioButton(string ControlID, string HeaderText,string AccessibleHeaderText) + { + Templat.ControlID = ControlID; + this.HeaderText = HeaderText; + this.ItemStyle.Width = new Unit("30px"); + this.ItemTemplate = Templat; + this.AccessibleHeaderText = AccessibleHeaderText; + } + public GridViewColumnRadioButton(string ControlID, string HeaderText, string AccessibleHeaderText, Unit Width) + { + Templat.ControlID = ControlID; + this.HeaderText = HeaderText; + this.ItemStyle.Width = Width; + this.ItemTemplate = Templat; + this.AccessibleHeaderText = AccessibleHeaderText; + } + } + #endregion + #region 模板列RadioButton + public class GridTemplateRadioButton : ITemplate + { //模板列Label + private string m_ControlID = "RadioButton1"; + /// + /// 获取或设置要生成的控件ID + /// + [Description("获取或设置要生成的控件"), DefaultValue("false"), Category("扩展"), Browsable(true)] + public string ControlID + { + get { return this.m_ControlID; } + set + { + this.m_ControlID = value; + } + } + private DataGridRadioButton RadioButton1; + + public GridTemplateRadioButton() + { + + } + public GridTemplateRadioButton(string controlID) + { + this.ControlID = controlID; + } + + public void InstantiateIn(System.Web.UI.Control container) + { + RadioButton1 = new DataGridRadioButton(); + RadioButton1.ID = ControlID; + RadioButton1.GroupName = ControlID; + container.Controls.Add(RadioButton1); + } + } + #endregion + #region CheckBox列 + public class GridViewColumnCheckBox : TemplateField + { + GridTemplateCheckBox Templat = new GridTemplateCheckBox(); + /// + /// 获取或设置要生成的控件ID + /// + public string ControlID + { + get { return Templat.ControlID; } + set { Templat.ControlID = value; } + } + public Unit Width + { + get { return this.ItemStyle.Width; } + set { this.ItemStyle.Width = value; } + } + /// + /// 获取或设置要绑定到数据源的字段名称 + /// + public string DataField + { + get { return Templat.DataField; } + set { Templat.DataField = value; } + } + public GridViewColumnCheckBox() + { + this.ItemStyle.Width = new Unit("30px"); + this.ItemTemplate = Templat; + } + public GridViewColumnCheckBox(string ControlID, string HeaderText, string DataField, string AccessibleHeaderText) + { + Templat.ControlID = ControlID; + Templat.DataField = DataField; + this.HeaderText = HeaderText; + this.ItemStyle.Width = new Unit("30px"); + this.ItemTemplate = Templat; + this.AccessibleHeaderText = AccessibleHeaderText; + } + public GridViewColumnCheckBox(string ControlID, string HeaderText, string DataField, string AccessibleHeaderText, Unit Width) + { + Templat.ControlID = ControlID; + Templat.DataField = DataField; + this.HeaderText = HeaderText; + this.ItemStyle.Width = Width; + this.ItemTemplate = Templat; + this.AccessibleHeaderText = AccessibleHeaderText; + } + } + #endregion + #region 模板列CheckBox + public class GridTemplateCheckBox : ITemplate + { //模板列Label + private string m_ControlID = "CheckBox1"; + /// + /// 获取或设置要生成的控件ID + /// + public string ControlID + { + get { return this.m_ControlID; } + set + { + this.m_ControlID = value; + + } + } + private string m_DataField; + /// + /// 获取或设置要绑定到数据源的字段名称 + /// + public string DataField + { + get { return this.m_DataField; } + set { this.m_DataField = value; } + } + private CheckBox m_CheckBox1; + public CheckBox CheckBox + { + get { return this.m_CheckBox1; } + set { this.m_CheckBox1 = value; } + } + public GridTemplateCheckBox() + { + + } + public GridTemplateCheckBox(string controlID, string DataField) + { + this.ControlID = controlID; + this.DataField = DataField; + } + + public void InstantiateIn(System.Web.UI.Control container) + { + m_CheckBox1 = new CheckBox(); + m_CheckBox1.ID = ControlID; + m_CheckBox1.TabIndex = 0; + if (this.DataField != "" && this.DataField != null) m_CheckBox1.DataBinding += new EventHandler(Control_DataBinding); + container.Controls.Add(m_CheckBox1); + } + void Control_DataBinding(object sender, EventArgs e) + { + GridViewRow dgi = (GridViewRow)m_CheckBox1.NamingContainer; + DataRowView drv = (DataRowView)dgi.DataItem; + m_CheckBox1.Checked = Convert.ToBoolean(drv[this.DataField]); + } + } + #endregion + + + #region MaskedTextBox列 + public class GridViewColumnMaskedTextBox : TemplateField + { + GridTemplateMaskedTextBox Templat = new GridTemplateMaskedTextBox(); + /// + /// 获取或设置要生成的控件ID + /// + [Description("获取或设置要生成的控件ID"), DefaultValue("Label1"), Category("扩展")] + public string ControlID + { + get { return Templat.ControlID; } + set { Templat.ControlID = value; } + } + /// + /// 获取或设置要绑定到数据源的字段名称 + /// + [Description("获取或设置要绑定到数据源的字段名称"), DefaultValue(""), Category("扩展")] + public string DataField + { + get { return Templat.DataField; } + set { Templat.DataField = value; } + } + [Description("宽度"), DefaultValue("100px"), Category("扩展")] + public Unit Width + { + get { return this.ItemStyle.Width; } + set { this.ItemStyle.Width = value; } + } + /// + /// 格式化方式 + /// + [Description("格式化方式ID"), DefaultValue(""), Category("扩展")] + public string FormatString + { + get { return Templat.FormatString; } + set { Templat.FormatString = value; } + } + /// + /// 最小值 + /// + [Description("最小值"), DefaultValue(""), Category("扩展")] + public virtual float MinValue + { + get { return Templat.MinValue; } + set { Templat.MinValue = value; } + } + /// + /// 最大值 + /// + [Description("最大值"), DefaultValue(""), Category("扩展")] + public virtual float MaxValue + { + get { return Templat.MaxValue; } + set { Templat.MaxValue = value;} + } + + [Description("输入方式"), DefaultValue(""), Category("扩展")] + public InputMode InputMode + { + get { return Templat.InputMode; } + set { Templat.InputMode = value; } + } + + /// + /// 样式 + /// + public string CssClass + { + get { return Templat.CssClass; } + set { Templat.CssClass = value; } + } + + /// + /// 文本框行模式 + /// + public TextBoxMode TextMode + { + get { return Templat.TextMode; } + set { Templat.TextMode = value; } + } + + /// + /// 文本框高度 + /// + public Unit TextBoxHeight + { + get { return Templat.TextBoxHeight; } + set { Templat.TextBoxHeight = value; } + } + + public GridViewColumnMaskedTextBox() + { + this.ItemTemplate = Templat; + } + public GridViewColumnMaskedTextBox(string ControlID, string CssClass, string HeaderText, string DataField, string AccessibleHeaderText, string FormatString, InputMode InputMode, float MinValue, float MaxValue) + { + Templat.ControlID = ControlID; + Templat.DataField = DataField; + Templat.FormatString = FormatString; + Templat.MinValue = MinValue; + Templat.MaxValue = MaxValue; + Templat.InputMode = InputMode; + Templat.CssClass = CssClass; + this.HeaderText = HeaderText; + this.ItemTemplate = Templat; + this.AccessibleHeaderText = AccessibleHeaderText; + } + public GridViewColumnMaskedTextBox(string ControlID, string CssClass, string HeaderText, string DataField, string AccessibleHeaderText, string FormatString, InputMode InputMode, float MinValue, float MaxValue, Unit Width) + { + Templat.ControlID = ControlID; + Templat.DataField = DataField; + Templat.FormatString = FormatString; + Templat.MinValue = MinValue; + Templat.MaxValue = MaxValue; + Templat.InputMode = InputMode; + Templat.CssClass = CssClass; + this.HeaderText = HeaderText; + this.ItemStyle.Width = Width; + this.ItemTemplate = Templat; + this.AccessibleHeaderText = AccessibleHeaderText; + } + } + #endregion + #region 模板列MaskedTextBox + class GridTemplateMaskedTextBox : ITemplate + { //模板列Label + private string m_ControlID = "MaskedTextBox1"; + /// + /// 获取或设置要生成的控件ID + /// + public string ControlID + { + get { return this.m_ControlID; } + set + { + this.m_ControlID = value; + + } + } + + private string m_DataField; + /// + /// 获取或设置要绑定到数据源的字段名称 + /// + public string DataField + { + get { return this.m_DataField; } + set { this.m_DataField = value; } + } + private string m_FormatStringString; + /// + /// 格式化方式 + /// + public string FormatString + { + get { return this.m_FormatStringString; } + set { this.m_FormatStringString = value; } + } + private string m_CssClass; + /// + /// 样式 + /// + public string CssClass + { + get { return this.m_CssClass; } + set { this.m_CssClass = value; } + } + private float m_MinValue = 0; + /// + /// 最小值 + /// + public virtual float MinValue + { + get { return m_MinValue; } + set { m_MinValue = value; } + } + private float m_MaxValue = float.MaxValue; + /// + /// 最大值 + /// + public virtual float MaxValue + { + get { return m_MaxValue; } + set { m_MaxValue = value;} + } + private InputMode m_InputMode; + + public InputMode InputMode + { + get { return m_InputMode; } + set { m_InputMode = value; } + } + private MaskedTextBox m_MaskedTextBox1; + public MaskedTextBox MaskedTextBox + { + get { return this.m_MaskedTextBox1; } + set { this.m_MaskedTextBox1 = value; } + } + private TextBoxMode m_TextMode = TextBoxMode.SingleLine; + /// + /// 文本框行模式 + /// + public TextBoxMode TextMode + { + get { return m_TextMode; } + set { m_TextMode = value; } + } + private Unit m_TextBoxHeight; + /// + /// 文本框高度 + /// + public Unit TextBoxHeight + { + get { return m_TextBoxHeight; } + set { m_TextBoxHeight = value; } + } + + + public GridTemplateMaskedTextBox() + { + + } + + public GridTemplateMaskedTextBox(string controlID, string DataField, string FormatString, string CssClass, InputMode InputMode, float MinValue, float MaxValue) + { + this.ControlID = controlID; + this.DataField = DataField; + this.FormatString = FormatString; + this.MinValue = MinValue; + this.MaxValue = MaxValue; + this.InputMode = InputMode; + this.CssClass = CssClass; + } + + public void InstantiateIn(System.Web.UI.Control container) + { + m_MaskedTextBox1 = new MaskedTextBox(); + m_MaskedTextBox1.ID = ControlID; + m_MaskedTextBox1.MinValue = MinValue; + m_MaskedTextBox1.MaxValue = MaxValue; + m_MaskedTextBox1.InputMode = InputMode; + m_MaskedTextBox1.CssClass = CssClass; + m_MaskedTextBox1.Width = new Unit("100%"); + m_MaskedTextBox1.TextMode=m_TextMode; + if (m_TextBoxHeight!=null)m_MaskedTextBox1.Height = m_TextBoxHeight; + m_MaskedTextBox1.Attributes.Add("autocomplete", "off"); + if (InputMode == InputMode.DateTime) { m_MaskedTextBox1.Attributes.Add("style", "text-align: Center;"); } + if (InputMode == InputMode.Int || InputMode == InputMode.Float) { m_MaskedTextBox1.Attributes.Add("style", "ime-mode: disabled;text-align: Center;"); } + if (this.DataField != "" && this.DataField != null) m_MaskedTextBox1.DataBinding += new EventHandler(Control_DataBinding); + container.Controls.Add(m_MaskedTextBox1); + } + void Control_DataBinding(object sender, EventArgs e) + { + GridViewRow dgi = (GridViewRow)m_MaskedTextBox1.NamingContainer; + DataRowView drv = (DataRowView)dgi.DataItem; + m_MaskedTextBox1.Text = DataConvert.Format(drv[this.DataField], this.FormatString); + } + } + #endregion + + + + + #region DropDownList列 + public class GridViewColumnDropDownList : TemplateField + { + GridTemplateDropDownList Templat = new GridTemplateDropDownList(); + /// + /// 获取或设置要生成的控件ID + /// + public string ControlID + { + get { return Templat.ControlID; } + set { Templat.ControlID = value; } + } + public Unit Width + { + get { return this.ItemStyle.Width; } + set { this.ItemStyle.Width = value; } + } + /// + /// 获取或设置要绑定到数据源的字段名称 + /// + public string DataField + { + get { return Templat.DataField; } + set { Templat.DataField = value; } + } + + /// + /// 样式 + /// + public string CssClass + { + get { return Templat.CssClass; } + set { Templat.CssClass = value; } + } + public bool Enabled + { + get { return Templat.Enabled; } + set { Templat.Enabled = value; } + } + public Dictionary DataSource + { + get { return Templat.DataSource; } + set { Templat.DataSource = value; } + } + public GridViewColumnDropDownList() + { + this.ItemTemplate = Templat; + } + public GridViewColumnDropDownList(string ControlID, string CssClass, string HeaderText, string DataField, string AccessibleHeaderText, Dictionary DataSource) + { + Templat.ControlID = ControlID; + Templat.DataField = DataField; + Templat.DataSource = DataSource; + Templat.CssClass = CssClass; + this.HeaderText = HeaderText; + this.ItemTemplate = Templat; + this.AccessibleHeaderText = AccessibleHeaderText; + + + } + public GridViewColumnDropDownList(string ControlID, string CssClass, string HeaderText, string DataField, string AccessibleHeaderText, Dictionary DataSource, Unit Width) + { + Templat.ControlID = ControlID; + Templat.DataField = DataField; + Templat.DataSource = DataSource; + Templat.CssClass = CssClass; + this.HeaderText = HeaderText; + this.ItemStyle.Width = Width; + this.ItemTemplate = Templat; + this.AccessibleHeaderText = AccessibleHeaderText; + } + } + #endregion + #region 模板列DropDownList + public class GridTemplateDropDownList : ITemplate + { //模板列Label + private string m_ControlID = "DropDownList1"; + /// + /// 获取或设置要生成的控件ID + /// + public string ControlID + { + get { return this.m_ControlID; } + set + { + this.m_ControlID = value; + + } + } + private string m_DataField; + /// + /// 获取或设置要绑定到数据源的字段名称 + /// + public string DataField + { + get { return this.m_DataField; } + set { this.m_DataField = value; } + } + private string m_CssClass; + /// + /// 样式 + /// + public string CssClass + { + get { return this.m_CssClass; } + set { this.m_CssClass = value; } + } + private bool m_Enabled=true; + + public bool Enabled + { + get { return m_Enabled; } + set { m_Enabled = value; } + } + + + private DropDownList m_DropDownList1; + public DropDownList DropDownList + { + get { return this.m_DropDownList1; } + set { this.m_DropDownList1 = value; } + } + private Dictionary m_DataSource; + public Dictionary DataSource + { + get { return m_DataSource; } + set { m_DataSource = value; } + } + public GridTemplateDropDownList() + { + + } + public GridTemplateDropDownList(string controlID, string DataField, string CssClass, Dictionary DataSource) + { + this.ControlID = controlID; + this.DataField = DataField; + this.DataSource = DataSource; + this.CssClass = CssClass; + } + + public void InstantiateIn(System.Web.UI.Control container) + { + m_DropDownList1 = new DropDownList(); + m_DropDownList1.ID = ControlID; + m_DropDownList1.Width = new Unit("100%"); + m_DropDownList1.CssClass = CssClass; + m_DropDownList1.Enabled = Enabled; + + + foreach (string item in this.DataSource.Keys) + { + m_DropDownList1.Items.Add(new ListItem(this.DataSource[item].ToString(), item)); + } + if (this.DataField != "" && this.DataField != null) m_DropDownList1.DataBinding += new EventHandler(Control_DataBinding); + container.Controls.Add(m_DropDownList1); + } + void Control_DataBinding(object sender, EventArgs e) + { + GridViewRow dgi = (GridViewRow)m_DropDownList1.NamingContainer; + DataRowView drv = (DataRowView)dgi.DataItem; + foreach (string item in this.DataSource.Keys) + { + string value = Convert.ToString(drv[this.DataField]); + if (item != value) continue; + m_DropDownList1.SelectedValue = value; + return; + } + } + } + #endregion + #region 空数据时的模板 + public class GridViewEmptyDataTemplate : ITemplate + { + private System.Web.UI.WebControls.Table m_Table1; + public System.Web.UI.WebControls.Table Table1 + { + get { return this.m_Table1; } + set { this.m_Table1 = value; } + } + public GridViewEmptyDataTemplate() + { } + public GridViewEmptyDataTemplate(System.Web.UI.WebControls.Table tb) + { + this.Table1 = tb; + } + #region ITemplate 成员 + public void InstantiateIn(System.Web.UI.Control container) + { + if (Table1 != null) container.Controls.Add(Table1); + } + #endregion + } + #endregion + + #region LinkButton列 + public class GridViewColumnLinkButton : TemplateField + { + GridTemplateLinkButton Templat = new GridTemplateLinkButton(); + /// + /// 获取或设置要生成的控件ID + /// + [Description("获取或设置要生成的控件ID"), DefaultValue("LinkButton1"), Category("扩展")] + public string ControlID + { + get { return Templat.ControlID; } + set { Templat.ControlID = value; } + } + /// + /// 获取或设置要绑定到数据源的字段名称 + /// + [Description("获取或设置要绑定到数据源的字段名称"), DefaultValue(""), Category("扩展")] + public string DataField + { + get { return Templat.DataField; } + set { Templat.DataField = value; } + } + [Description("宽度"), DefaultValue("100px"), Category("扩展")] + public Unit Width + { + get { return this.ItemStyle.Width; } + set { this.ItemStyle.Width = value; } + } + + /// + /// 空值时显示的字符串 + /// + [Description("空值时显示的字符串ID"), DefaultValue(""), Category("扩展")] + public string NullText + { + get { return Templat.NullText; } + set { Templat.NullText = value; } + } + /// + /// 格式化方式 + /// + [Description("格式化方式ID"), DefaultValue(""), Category("扩展")] + public string FormatString + { + get { return Templat.FormatString; } + set { Templat.FormatString = value; } + } + [Description("文本"), DefaultValue(""), Category("扩展")] + public string Text + { + get { return this.Templat.Text; } + set { this.Templat.Text = value; } + } + [Description("CommandName"), DefaultValue(""), Category("扩展")] + public string CommandName + { + get { return this.Templat.CommandName; } + set { this.Templat.CommandName = value; } + } + [Description("CommandArgument"), DefaultValue(""), Category("扩展")] + public string CommandArgument + { + get { return this.Templat.CommandArgument; } + set { this.Templat.CommandArgument = value; } + } + [Description("文本颜色"), DefaultValue(""), Category("扩展")] + public Color ForeColor + { + get { return this.Templat.ForeColor; } + set { this.Templat.ForeColor = value; } + } + + public GridViewColumnLinkButton() + { + this.ItemTemplate = Templat; + } + public GridViewColumnLinkButton(string ControlID, string HeaderText, string DataField, string AccessibleHeaderText, string FormatString) + { + Templat.ControlID = ControlID; + Templat.DataField = DataField; + Templat.FormatString = FormatString; + Templat.NullText = NullText; + this.HeaderText = HeaderText; + this.ItemTemplate = Templat; + this.AccessibleHeaderText = AccessibleHeaderText; + } + public GridViewColumnLinkButton(string ControlID, string HeaderText, string DataField, string AccessibleHeaderText, string FormatString, Unit Width) + { + Templat.ControlID = ControlID; + Templat.DataField = DataField; + Templat.FormatString = FormatString; + Templat.NullText = NullText; + this.HeaderText = HeaderText; + this.ItemStyle.Width = Width; + this.ItemTemplate = Templat; + this.AccessibleHeaderText = AccessibleHeaderText; + } + + } + #endregion + #region 模板列LinkButton + public class GridTemplateLinkButton : ITemplate + { //模板列LinkButton + private string m_ControlID = "LinkButton1"; + /// + /// 获取或设置要生成的控件ID + /// + public string ControlID + { + get { return this.m_ControlID; } + set + { + this.m_ControlID = value; + + } + } + private string m_DataField; + /// + /// 获取或设置要绑定到数据源的字段名称 + /// + public string DataField + { + get { return this.m_DataField; } + set { this.m_DataField = value; } + } + private string m_CssClass; + /// + /// 样式 + /// + public string CssClass + { + get { return this.m_CssClass; } + set { this.m_CssClass = value; } + } + private string m_NullText = ""; + /// + /// 空值时显示的字符串 + /// + [Description("空值时显示的字符串"), DefaultValue(""), Category("扩展"), Browsable(true)] + public string NullText + { + get { return this.m_NullText; } + set { this.m_NullText = value; } + } + private string m_FormatStringString; + /// + /// 格式化方式 + /// + public string FormatString + { + get { return this.m_FormatStringString; } + set { this.m_FormatStringString = value; } + } + private LinkButton m_LinkButton1; + public LinkButton LinkButton + { + get { return this.m_LinkButton1; } + set { this.m_LinkButton1 = value; } + } + private string m_Text; + /// + /// 文本 + /// + public string Text + { + get { return this.m_Text; } + set { this.m_Text = value; } + } + private string m_CommandName; + /// + /// CommandName + /// + public string CommandName + { + get { return this.m_CommandName; } + set { this.m_CommandName = value; } + } + private string m_CommandArgument; + /// + /// CommandArgument + /// + public string CommandArgument + { + get { return this.m_CommandArgument; } + set { this.m_CommandArgument = value; } + } + private Color m_ForeColor; + /// + /// 文本颜色 + /// + public Color ForeColor + { + get { return this.m_ForeColor; } + set { this.m_ForeColor = value; } + } + + public GridTemplateLinkButton() + { + + } + public GridTemplateLinkButton(string DataField) + { + this.DataField = DataField; + } + + public void InstantiateIn(System.Web.UI.Control container) + { + m_LinkButton1 = new LinkButton(); + m_LinkButton1.Width = new Unit("100%"); + m_LinkButton1.ID = this.ControlID; + m_LinkButton1.Text = this.Text; + m_LinkButton1.CommandName = this.CommandName; + m_LinkButton1.CommandArgument = this.CommandArgument; + m_LinkButton1.ForeColor = this.ForeColor; + if (this.DataField != "" && this.DataField != null) m_LinkButton1.DataBinding += new EventHandler(Control_DataBinding); + container.Controls.Add(m_LinkButton1); + } + void Control_DataBinding(object sender, EventArgs e) + { + GridViewRow dgi = (GridViewRow)m_LinkButton1.NamingContainer; + DataRowView drv = (DataRowView)dgi.DataItem; + string Text = DataConvert.Format(drv[this.DataField], this.FormatString); + if (Text == "") Text = this.NullText; + m_LinkButton1.Text = Text; + //m_LinkButton1.Text = drv[this.DataField].ToString(); + } + } + #endregion + + + + + #region 模板列PlaceHolder + public class GridTemplatePlaceHolder : ITemplate + { //模板列LinkButton + private string m_ControlID = "PlaceHolder1"; + /// + /// 获取或设置要生成的控件ID + /// + public string ControlID + { + get { return this.m_ControlID; } + set { this.m_ControlID = value;} + } + private PlaceHolder m_PlaceHolder1; + public PlaceHolder PlaceHolder + { + get { return this.m_PlaceHolder1; } + set { this.m_PlaceHolder1 = value; } + } + public GridTemplatePlaceHolder() + { + + } + + + public void InstantiateIn(System.Web.UI.Control container) + { + m_PlaceHolder1 = new PlaceHolder(); + m_PlaceHolder1.ID = this.ControlID; + container.Controls.Add(m_PlaceHolder1); + } + + } + #endregion + + #region 表头 + public class HeaderEventArgs : EventArgs + { + private System.Web.UI.WebControls.Table m_Header; + /// + /// 返回数据 + /// + public System.Web.UI.WebControls.Table Header + { + get { return m_Header; } + set { m_Header = value; } + } + } + #endregion + + [TypeConverter(typeof(PagerStyleConverter))] + public class UserPagerStyle + { + private bool m_ShowExcelReport=false; + /// + /// 是否显示导出按钮 + /// + [Description("是否显示导出按钮"),NotifyParentProperty(true)] + public virtual bool ShowExcelReport + { + get { return m_ShowExcelReport; } + set { m_ShowExcelReport = value; } + } + private bool m_ShowSelectPager=false; + /// + /// 是否显示分页选择 + /// + [Description("是否显示分页选择"), NotifyParentProperty(true)] + public virtual bool ShowSelectPager + { + get { return m_ShowSelectPager; } + set { m_ShowSelectPager = value;} + } + private bool m_ShowPagerButton=true; + /// + /// 是否显示分页按钮 + /// + [Description("是否显示分页按钮"), NotifyParentProperty(true)] + public virtual bool ShowPagerButton + { + get { return m_ShowPagerButton; } + set { m_ShowPagerButton = value; } + } + + private bool m_ShowFirstPager=false; + /// + /// 是否显示自定义分页按钮在上面 + /// + [Description("是否显示自定义分页按钮在上面"), NotifyParentProperty(true)] + public bool ShowFirstPager + { + get { return m_ShowFirstPager; } + set { m_ShowFirstPager = value; } + } + private bool m_ShowLastPager=false; + /// + /// 是否显示自定义分页按钮在下面 + /// + [Description("是否显示自定义分页按钮在下面"), NotifyParentProperty(true)] + public bool ShowLastPager + { + get { return m_ShowLastPager; } + set { m_ShowLastPager = value; } + } + private Color m_BackColor=Color.White; + /// + /// 背景色 + /// + [Description("背景色"), NotifyParentProperty(true)] + public Color BackColor + { + get { return m_BackColor; } + set { m_BackColor = value; } + } + private string m_PagerCssClass; + /// + /// 分页行样式 + /// + [Description("分页行样式"), NotifyParentProperty(true)] + public string PagerCssClass + { + get { return m_PagerCssClass; } + set { m_PagerCssClass = value; } + } + private string m_FirstImageUrl; + /// + /// 首页图像 + /// + [Description("首页图像"), NotifyParentProperty(true)] + public string FirstImageUrl + { + get { return m_FirstImageUrl; } + set { m_FirstImageUrl = value; } + } + private string m_PrevImageUrl; + /// + /// 上一页图像 + /// + [Description("上一页图像"), NotifyParentProperty(true)] + public string PrevImageUrl + { + get { return m_PrevImageUrl; } + set { m_PrevImageUrl = value; } + } + private string m_NextImageUrl; + /// + /// 下一页图像 + /// + [Description("下一页图像"), NotifyParentProperty(true)] + public string NextImageUrl + { + get { return m_NextImageUrl; } + set { m_NextImageUrl = value; } + } + private string m_LastImageUrl; + /// + /// 未页图像 + /// + [Description("未页图像"), NotifyParentProperty(true)] + public string LastImageUrl + { + get { return m_LastImageUrl; } + set { m_LastImageUrl = value; } + } + private Color m_ForeColor=Color.Blue; + /// + /// 文本颜色 + /// + [Description("文本颜色"), NotifyParentProperty(true)] + public Color ForeColor + { + get { return m_ForeColor; } + set { m_ForeColor = value; } + } + private string m_TextCssClass; + /// + /// 文本样式 + /// + [Description("文本样式"), NotifyParentProperty(true)] + public string TextCssClass + { + get { return m_TextCssClass; } + set { m_TextCssClass = value; } + } + //private Color m_MouseClickForeColor = Color.FromName("#660033"); + ///// + ///// 单击后颜色 + ///// + //[Description("单击后颜色"), NotifyParentProperty(true)] + //public Color MouseClickForeColor + //{ + // get { return m_MouseClickForeColor; } + // //set { m_MouseClickForeColor = value; } + //} + //private Color m_MouseOverForeColor = Color.FromName("#CC00CC"); + ///// + ///// 移入时颜色 + ///// + //[Description("移入时颜色"), NotifyParentProperty(true)] + //public Color MouseOverForeColor + //{ + // get { return m_MouseOverForeColor; } + // //set { m_MouseOverForeColor = value; } + //} + private StringAlignment m_Align = StringAlignment.Near; + /// + /// 对齐方式 + /// + [Description("对齐方式"), NotifyParentProperty(true)] + public StringAlignment Align + { + get { return m_Align; } + set { m_Align = value; } + } + + public UserPagerStyle() + { + + } + public UserPagerStyle(bool ShowExcelReport, bool ShowSelectPager, bool ShowPagerButton, bool ShowFirstPager, bool ShowLastPager, Color BackColor, string FirstImageUrl, string PrevImageUrl, string NextImageUrl, string LastImageUrl, Color ForeColor,string PagerCssClass,string TextCssClass,StringAlignment Align) + { + this.ShowExcelReport = ShowExcelReport; + this.ShowSelectPager = ShowSelectPager; + this.ShowPagerButton = ShowPagerButton; + this.ShowFirstPager = ShowFirstPager; + this.ShowLastPager = ShowLastPager; + this.BackColor = BackColor; + this.FirstImageUrl = FirstImageUrl; + this.PrevImageUrl = PrevImageUrl; + this.NextImageUrl = NextImageUrl; + this.LastImageUrl = LastImageUrl; + this.ForeColor = ForeColor; + this.PagerCssClass = PagerCssClass; + this.TextCssClass = TextCssClass; + this.Align = Align; + } + + } + + public class PagerStyleConverter : ExpandableObjectConverter + { + public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) + { + if (sourceType == typeof(string)) + { + return true; + } + return base.CanConvertFrom(context, sourceType); + } + + public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) + { + if (destinationType == typeof(string)) + { + return true; + } + return base.CanConvertTo(context, destinationType); + } + + public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) + { + if (value == null) + { + return new UserPagerStyle(); + } + + if (value is string) + { + string s = (string)value; + if (s.Length == 0) + { + return new UserPagerStyle(); + } + + string[] parts = Regex.Split(s, "@#"); + + if (parts.Length == 14) + { + StringAlignment align = StringAlignment.Center; + if (parts[13] == "Far") align = StringAlignment.Far; + if (parts[13] == "Near") align = StringAlignment.Near; + return new UserPagerStyle(Convert.ToBoolean(parts[0]), Convert.ToBoolean(parts[1]), Convert.ToBoolean(parts[2]), Convert.ToBoolean(parts[3]), Convert.ToBoolean(parts[4]), Color.FromName(parts[5]), parts[6], parts[7], parts[8], parts[9], Color.FromName(parts[10]), parts[11], parts[12], align); + } + } + return base.ConvertFrom(context, culture, value); + } + + public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) + { + if (value != null) + { + if (!(value is UserPagerStyle)) + { + throw new ArgumentException( + "Invalid UserPagerStyle", "value"); + } + } + + if (destinationType == typeof(string)) + { + if (value == null) + { + return String.Empty; + } + + UserPagerStyle auth = (UserPagerStyle)value; + return String.Format("{0}@#{1}@#{2}@#{3}@#{4}@#{5}@#{6}@#{7}@#{8}@#{9}@#{10}@#{11}@#{12}@#{13}", + auth.ShowExcelReport.ToString(), + auth.ShowSelectPager.ToString(), + auth.ShowPagerButton.ToString(), + auth.ShowFirstPager.ToString(), + auth.ShowLastPager.ToString(), + auth.BackColor.Name, + auth.FirstImageUrl, + auth.PrevImageUrl, + auth.NextImageUrl, + auth.LastImageUrl, + auth.ForeColor.Name, + auth.PagerCssClass, + auth.TextCssClass, + auth.Align.ToString()); + + + } + + return base.ConvertTo(context, culture, value, + destinationType); + } + } + + + +} diff --git a/基础类库/HuizhongLibrary/LocalIpAddress.cs b/基础类库/HuizhongLibrary/LocalIpAddress.cs new file mode 100644 index 0000000..b62a624 --- /dev/null +++ b/基础类库/HuizhongLibrary/LocalIpAddress.cs @@ -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格式 + /**//// + /// 判断是否是IP地址格式 0.0.0.0 + /// + /// 待判断的IP地址 + /// true or false + 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 + } +} + diff --git a/基础类库/HuizhongLibrary/MaskedTextBox.cs b/基础类库/HuizhongLibrary/MaskedTextBox.cs new file mode 100644 index 0000000..11bbab3 --- /dev/null +++ b/基础类库/HuizhongLibrary/MaskedTextBox.cs @@ -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>")] + public class MaskedTextBox : TextBox + { +// private InputMode m_InputMode = InputMode.None; + /// + /// 输入模式 + /// + [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; + /// + /// 最小值 + /// + [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; + /// + /// 最大值 + /// + [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 + } +} diff --git a/基础类库/HuizhongLibrary/MicrosoftExcel.cs b/基础类库/HuizhongLibrary/MicrosoftExcel.cs new file mode 100644 index 0000000..0b09b7f --- /dev/null +++ b/基础类库/HuizhongLibrary/MicrosoftExcel.cs @@ -0,0 +1,1994 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.Diagnostics; +using System.IO; +using System.Reflection; +using System.Text; +using HuizhongLibrary.Data; +using NPOI.HSSF.UserModel; +using NPOI.HSSF.Util; +using NPOI.SS.UserModel; +using NPOI.SS.Util; +using NPOI.XSSF.UserModel; + +namespace HuizhongLibrary +{ + public class MicrosoftExcel + { + #region 导出 + /// + /// 导出Excel + /// + /// 表头 + /// DataTable + /// 要导出的列集合 + /// + public string Export(string HeaderName, DataTable tb) + { + ReportPrint.TableColumnCollection listColumns = new ReportPrint.TableColumnCollection(); + foreach (DataColumn item in tb.Columns) + { + listColumns.Add(item.ColumnName, item.ColumnName, DbType.String, ""); + } + HSSFWorkbook workbook = new HSSFWorkbook(); + int sheerIndex = 1; + int start = 0; + while (true) + { + PageExport(workbook, "Sheet" + sheerIndex, HeaderName, tb, start, listColumns); + start = start + 60000; + sheerIndex++; + if (tb.Rows.Count < start) break; + } + string filename = Guid.NewGuid().ToString() + ".xls"; + string DirectoryName = AppDomain.CurrentDomain.BaseDirectory + "ServerCookies"; + if (System.IO.Directory.Exists(DirectoryName) == false) System.IO.Directory.CreateDirectory(DirectoryName); + string ServerFileName = DirectoryName + "/" + filename; + //保存 + using (FileStream fs = new FileStream(ServerFileName, FileMode.Create, FileAccess.Write)) + { + workbook.Write(fs); + } + workbook.Close(); + return "ServerCookies/" + filename; + } + + + + public string Export(DataTable tb, ReportPrint.TableColumnCollection Columns) + { + HSSFWorkbook workbook = new HSSFWorkbook(); + int sheerIndex = 1; + int start = 0; + while (true) + { + PageExport(workbook, "Sheet" + sheerIndex, "", tb, start, Columns); + start = start + 60000; + sheerIndex++; + if (tb.Rows.Count < start) break; + } + string filename = Guid.NewGuid().ToString() + ".xls"; + string DirectoryName = AppDomain.CurrentDomain.BaseDirectory + "ServerCookies"; + if (System.IO.Directory.Exists(DirectoryName) == false) System.IO.Directory.CreateDirectory(DirectoryName); + string ServerFileName = DirectoryName + "/" + filename; + //保存 + using (FileStream fs = new FileStream(ServerFileName, FileMode.Create, FileAccess.Write)) + { + workbook.Write(fs); + } + workbook.Close(); + return "ServerCookies/" + filename; + } + + public string Export(string HeaderName, DataTable tb, ReportPrint.TableColumnCollection Columns) + { + HSSFWorkbook workbook = new HSSFWorkbook(); + int sheerIndex = 1; + int start = 0; + while (true) + { + PageExport(workbook, "Sheet" + sheerIndex, HeaderName, tb, start, Columns); + start = start + 60000; + sheerIndex++; + if (tb.Rows.Count < start) break; + } + string filename = Guid.NewGuid().ToString() + ".xls"; + string DirectoryName = AppDomain.CurrentDomain.BaseDirectory + "ServerCookies"; + if (System.IO.Directory.Exists(DirectoryName) == false) System.IO.Directory.CreateDirectory(DirectoryName); + string ServerFileName = DirectoryName + "/" + filename; + //保存 + using (FileStream fs = new FileStream(ServerFileName, FileMode.Create, FileAccess.Write)) + { + workbook.Write(fs); + } + workbook.Close(); + return "ServerCookies/" + filename; + } + /// + /// 2013-12-27 + /// 石志超 + /// + public string Export(List lst, ReportPrint.TableColumnCollection Columns) where T : class + { + if (lst == null || lst.Count == 0) return ""; + Type t = typeof(T); + HSSFWorkbook workbook = new HSSFWorkbook(); + int sheerIndex = 1; + int start = 0; + while (true) + { + PageExport(workbook, "Sheet" + sheerIndex, "", lst, start, Columns); + start = start + 60000; + sheerIndex++; + if (lst.Count < start) break; + } + string filename = Guid.NewGuid().ToString() + ".xls"; + string DirectoryName = AppDomain.CurrentDomain.BaseDirectory + "ServerCookies"; + if (System.IO.Directory.Exists(DirectoryName) == false) System.IO.Directory.CreateDirectory(DirectoryName); + string ServerFileName = DirectoryName + "/" + filename; + //保存 + using (FileStream fs = new FileStream(ServerFileName, FileMode.Create, FileAccess.Write)) + { + workbook.Write(fs); + } + workbook.Close(); + return "ServerCookies/" + filename; + } + + /// + /// 2014-01-26 + /// 石志超 + /// + public string Export(string HeaderName, List lst, ReportPrint.TableColumnCollection Columns) where T : class + { + HSSFWorkbook workbook = new HSSFWorkbook(); + int sheerIndex = 1; + int start = 0; + while (true) + { + PageExport(workbook, "Sheet" + sheerIndex, HeaderName, lst, start, Columns); + start = start + 60000; + sheerIndex++; + if (lst.Count < start) break; + } + string filename = Guid.NewGuid().ToString() + ".xls"; + string DirectoryName = AppDomain.CurrentDomain.BaseDirectory + "ServerCookies"; + if (System.IO.Directory.Exists(DirectoryName) == false) System.IO.Directory.CreateDirectory(DirectoryName); + string ServerFileName = DirectoryName + "/" + filename; + //保存 + using (FileStream fs = new FileStream(ServerFileName, FileMode.Create, FileAccess.Write)) + { + workbook.Write(fs); + } + workbook.Close(); + return "ServerCookies/" + filename; + } + + public string Export(List> lst) + { + HSSFWorkbook workbook = new HSSFWorkbook(); + int sheerIndex = 1; + int start = 0; + while (true) + { + PageExport(workbook, "Sheet" + sheerIndex, "", lst, start); + start = start + 60000; + sheerIndex++; + if (lst.Count < start) break; + } + string filename = Guid.NewGuid().ToString() + ".xls"; + string DirectoryName = AppDomain.CurrentDomain.BaseDirectory + "ServerCookies"; + if (System.IO.Directory.Exists(DirectoryName) == false) System.IO.Directory.CreateDirectory(DirectoryName); + string ServerFileName = DirectoryName + "/" + filename; + //保存 + using (FileStream fs = new FileStream(ServerFileName, FileMode.Create, FileAccess.Write)) + { + workbook.Write(fs); + } + workbook.Close(); + return "ServerCookies/" + filename; + } + public string Export(string HeaderName, List> lst) + { + HSSFWorkbook workbook = new HSSFWorkbook(); + int sheerIndex = 1; + int start = 0; + while (true) + { + PageExport(workbook, "Sheet" + sheerIndex, HeaderName, lst, start); + start = start + 60000; + sheerIndex++; + if (lst.Count < start) break; + } + string filename = Guid.NewGuid().ToString() + ".xls"; + string DirectoryName = AppDomain.CurrentDomain.BaseDirectory + "ServerCookies"; + if (System.IO.Directory.Exists(DirectoryName) == false) System.IO.Directory.CreateDirectory(DirectoryName); + string ServerFileName = DirectoryName + "/" + filename; + //保存 + using (FileStream fs = new FileStream(ServerFileName, FileMode.Create, FileAccess.Write)) + { + workbook.Write(fs); + } + workbook.Close(); + return "ServerCookies/" + filename; + } + + public string Export(DataTable dt1, ReportPrint.TableColumnCollection Columns1, DataTable dt2, ReportPrint.TableColumnCollection Columns2) + { + HSSFWorkbook workbook = new HSSFWorkbook(); + + DataTable tb = dt1; + HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet("Sheet1"); + sheet.PrintSetup.FitHeight = 0; + sheet.PrintSetup.FitWidth = 0; + sheet.PrintSetup.Scale = 100; + //填充表头 + HSSFRow dataRow = (HSSFRow)sheet.CreateRow(0); + foreach (ReportPrint.TableColumn item in Columns1) + { + int index = Columns1.IndexOf(item); + HSSFCell dataCell = (HSSFCell)dataRow.CreateCell(index); + dataCell.SetCellValue(item.Caption); + dataCell.CellStyle.Alignment = HorizontalAlignment.Center; + //边框 + dataCell.CellStyle.BorderBottom = BorderStyle.Thin; + dataCell.CellStyle.BorderLeft = BorderStyle.Thin; + dataCell.CellStyle.BorderRight = BorderStyle.Thin; + dataCell.CellStyle.BorderTop = BorderStyle.Thin; + //边框颜色 + dataCell.CellStyle.BottomBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.TopBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.LeftBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.RightBorderColor = HSSFColor.Black.Index; + } + + //填充内容 + for (int i = 0; i < tb.Rows.Count; i++) + { + dataRow = (HSSFRow)sheet.CreateRow(i + 1); + HSSFCell dataCell = null; + foreach (ReportPrint.TableColumn item in Columns1) + { + int j = Columns1.IndexOf(item); + dataCell = (HSSFCell)dataRow.CreateCell(j); + if (item.Format != "") + { + dataCell.SetCellValue(DataConvert.Format(tb.Rows[i][item.Name].ToString(), item.Format)); + } + else + { + dataCell.SetCellValue(tb.Rows[i][item.Name].ToString()); + } + dataCell.CellStyle.Alignment = HorizontalAlignment.Center; + //边框 + dataCell.CellStyle.BorderBottom = BorderStyle.Thin; + dataCell.CellStyle.BorderLeft = BorderStyle.Thin; + dataCell.CellStyle.BorderRight = BorderStyle.Thin; + dataCell.CellStyle.BorderTop = BorderStyle.Thin; + //边框颜色 + dataCell.CellStyle.BottomBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.TopBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.LeftBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.RightBorderColor = HSSFColor.Black.Index; + } + } + foreach (ReportPrint.TableColumn item in Columns1) + { + int index = Columns1.IndexOf(item); + if (item.Width > 0) { sheet.SetColumnWidth(index, (int)item.Width); } + else { sheet.AutoSizeColumn(index); } + } + if (dt2 != null) + { + + + HSSFSheet sheet2 = (HSSFSheet)workbook.CreateSheet("Sheet2"); + //填充表头 + HSSFRow dataRow2 = (HSSFRow)sheet2.CreateRow(0); + foreach (ReportPrint.TableColumn item in Columns2) + { + int index = Columns2.IndexOf(item); + HSSFCell dataCell = (HSSFCell)dataRow2.CreateCell(index); + dataCell.SetCellValue(item.Caption); + dataCell.CellStyle.Alignment = HorizontalAlignment.Center; + //边框 + dataCell.CellStyle.BorderBottom = BorderStyle.Thin; + dataCell.CellStyle.BorderLeft = BorderStyle.Thin; + dataCell.CellStyle.BorderRight = BorderStyle.Thin; + dataCell.CellStyle.BorderTop = BorderStyle.Thin; + //边框颜色 + dataCell.CellStyle.BottomBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.TopBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.LeftBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.RightBorderColor = HSSFColor.Black.Index; + } + + //填充内容 + for (int i = 0; i < dt2.Rows.Count; i++) + { + dataRow2 = (HSSFRow)sheet2.CreateRow(i + 1); + HSSFCell dataCell = null; + foreach (ReportPrint.TableColumn item in Columns2) + { + int j = Columns2.IndexOf(item); + dataCell = (HSSFCell)dataRow2.CreateCell(j); + if (item.Format != "") + { + dataCell.SetCellValue(DataConvert.Format(dt2.Rows[i][item.Name].ToString(), item.Format)); + } + else + { + dataCell.SetCellValue(dt2.Rows[i][item.Name].ToString()); + } + dataCell.CellStyle.Alignment = HorizontalAlignment.Center; + //边框 + dataCell.CellStyle.BorderBottom = BorderStyle.Thin; + dataCell.CellStyle.BorderLeft = BorderStyle.Thin; + dataCell.CellStyle.BorderRight = BorderStyle.Thin; + dataCell.CellStyle.BorderTop = BorderStyle.Thin; + //边框颜色 + dataCell.CellStyle.BottomBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.TopBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.LeftBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.RightBorderColor = HSSFColor.Black.Index; + } + } + foreach (ReportPrint.TableColumn item in Columns2) + { + int index = Columns2.IndexOf(item); + if (item.Width > 0) { sheet2.SetColumnWidth(index, (int)item.Width); } + else { sheet2.AutoSizeColumn(index); } + } + + + } + + string filename = Guid.NewGuid().ToString() + ".xls"; + string DirectoryName = AppDomain.CurrentDomain.BaseDirectory + "ServerCookies"; + if (System.IO.Directory.Exists(DirectoryName) == false) System.IO.Directory.CreateDirectory(DirectoryName); + string ServerFileName = DirectoryName + "/" + filename; + //保存 + using (FileStream fs = new FileStream(ServerFileName, FileMode.Create, FileAccess.Write)) + { + workbook.Write(fs); + } + workbook.Close(); + return "ServerCookies/" + filename; + } + + public string Export(string HeaderName, Models.JsonTable tb) + { + HSSFWorkbook workbook = new HSSFWorkbook(); + HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet("Sheet1"); + sheet.PrintSetup.FitHeight = 0; + sheet.PrintSetup.FitWidth = 0; + sheet.PrintSetup.Scale = 100; + HSSFRow dataRow = null; + HSSFCell dataCell = null; + int RowIndex = 0; + if (HeaderName != "") + { + dataRow = (HSSFRow)sheet.CreateRow(0); + dataCell = (HSSFCell)dataRow.CreateCell(0); + dataCell.SetCellValue(HeaderName); + dataCell.CellStyle.Alignment = HorizontalAlignment.Center; + //边框 + dataCell.CellStyle.BorderBottom = BorderStyle.Thin; + dataCell.CellStyle.BorderLeft = BorderStyle.Thin; + dataCell.CellStyle.BorderRight = BorderStyle.Thin; + dataCell.CellStyle.BorderTop = BorderStyle.Thin; + //边框颜色 + dataCell.CellStyle.BottomBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.TopBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.LeftBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.RightBorderColor = HSSFColor.Black.Index; + sheet.AddMergedRegion(new Region(0, 0, 0, tb.ColumnNumber - 1)); + RowIndex++; + } + //填充表头 + if (tb.Cells.Count > 0) + { + int ColIndex = 0; + foreach (var item in tb.Cells) + { + if (ColIndex == 0) + { + dataRow = (HSSFRow)sheet.CreateRow(RowIndex); + RowIndex++; + } + dataCell = (HSSFCell)dataRow.CreateCell(ColIndex); + dataCell.SetCellValue(item.CellText); + dataCell.CellStyle.Alignment = HorizontalAlignment.Center; + //边框 + dataCell.CellStyle.BorderBottom = BorderStyle.Thin; + dataCell.CellStyle.BorderLeft = BorderStyle.Thin; + dataCell.CellStyle.BorderRight = BorderStyle.Thin; + dataCell.CellStyle.BorderTop = BorderStyle.Thin; + //边框颜色 + dataCell.CellStyle.BottomBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.TopBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.LeftBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.RightBorderColor = HSSFColor.Black.Index; + ColIndex++; + if (ColIndex == tb.ColumnNumber) ColIndex = 0; + } + } + else + { + foreach (var item in tb.Rows) + { + dataRow = (HSSFRow)sheet.CreateRow(RowIndex); + RowIndex++; + foreach (var cell in item) + { + int ColIndex = item.IndexOf(cell); + dataCell = (HSSFCell)dataRow.CreateCell(ColIndex); + dataCell.SetCellValue(cell.CellText); + dataCell.CellStyle.Alignment = HorizontalAlignment.Center; + //边框 + dataCell.CellStyle.BorderBottom = BorderStyle.Thin; + dataCell.CellStyle.BorderLeft = BorderStyle.Thin; + dataCell.CellStyle.BorderRight = BorderStyle.Thin; + dataCell.CellStyle.BorderTop = BorderStyle.Thin; + //边框颜色 + dataCell.CellStyle.BottomBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.TopBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.LeftBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.RightBorderColor = HSSFColor.Black.Index; + } + } + } + for (int i = 0; i < tb.ColumnNumber; i++) + { + sheet.AutoSizeColumn(i); + } + + string filename = Guid.NewGuid().ToString() + ".xls"; + string DirectoryName = AppDomain.CurrentDomain.BaseDirectory + "ServerCookies"; + if (System.IO.Directory.Exists(DirectoryName) == false) System.IO.Directory.CreateDirectory(DirectoryName); + string ServerFileName = DirectoryName + "/" + filename; + //保存 + using (FileStream fs = new FileStream(ServerFileName, FileMode.Create, FileAccess.Write)) + { + workbook.Write(fs); + } + workbook.Close(); + return "ServerCookies/" + filename; + } + #endregion + #region DataSet导出 + public string Export(DataSet ds,List Columns) + { + HSSFWorkbook workbook = new HSSFWorkbook(); + for (int i = 0; i < Columns.Count; i++) + { + DataTable tb = ds.Tables[i]; + var listColumns = Columns[i]; + //workbook = new HSSFWorkbook(); + PageExport(workbook, tb.TableName, "", tb, 0, listColumns); + } + string filename = Guid.NewGuid().ToString() + ".xls"; + string DirectoryName = AppDomain.CurrentDomain.BaseDirectory + "ServerCookies"; + if (System.IO.Directory.Exists(DirectoryName) == false) System.IO.Directory.CreateDirectory(DirectoryName); + string ServerFileName = DirectoryName + "/" + filename; + //保存 + using (FileStream fs = new FileStream(ServerFileName, FileMode.Create, FileAccess.Write)) + { + workbook.Write(fs); + } + workbook.Close(); + return "ServerCookies/" + filename; + } + #endregion + + #region DataTable导出分页 + public void PageExport(HSSFWorkbook workbook, string SheetName, string HeaderName, DataTable tb, int start, ReportPrint.TableColumnCollection Columns) + { + HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet(SheetName); + sheet.PrintSetup.FitHeight = 0; + sheet.PrintSetup.FitWidth = 0; + sheet.PrintSetup.Scale = 100; + HSSFRow dataRow = null; + HSSFCell dataCell = null; + int RowIndex = 0; + if (HeaderName != "") + { + dataRow = (HSSFRow)sheet.CreateRow(0); + dataCell = (HSSFCell)dataRow.CreateCell(0); + dataCell.SetCellValue(HeaderName); + dataCell.CellStyle.Alignment = HorizontalAlignment.Center; + //边框 + dataCell.CellStyle.BorderBottom = BorderStyle.Thin; + dataCell.CellStyle.BorderLeft = BorderStyle.Thin; + dataCell.CellStyle.BorderRight = BorderStyle.Thin; + dataCell.CellStyle.BorderTop = BorderStyle.Thin; + //边框颜色 + dataCell.CellStyle.BottomBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.TopBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.LeftBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.RightBorderColor = HSSFColor.Black.Index; + sheet.AddMergedRegion(new Region(0, 0, 0, Columns.Count - 1)); + RowIndex++; + } + //填充表头 + dataRow = (HSSFRow)sheet.CreateRow(RowIndex); + foreach (ReportPrint.TableColumn item in Columns) + { + int index = Columns.IndexOf(item); + dataCell = (HSSFCell)dataRow.CreateCell(index); + dataCell.SetCellValue(item.Caption); + dataCell.CellStyle.Alignment = HorizontalAlignment.Center; + //边框 + dataCell.CellStyle.BorderBottom = BorderStyle.Thin; + dataCell.CellStyle.BorderLeft = BorderStyle.Thin; + dataCell.CellStyle.BorderRight = BorderStyle.Thin; + dataCell.CellStyle.BorderTop = BorderStyle.Thin; + //边框颜色 + dataCell.CellStyle.BottomBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.TopBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.LeftBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.RightBorderColor = HSSFColor.Black.Index; + } + int count = start + 60000; + if (tb.Rows.Count < count) count = tb.Rows.Count; + //填充内容 + for (int i = start; i < count; i++) + { + RowIndex++; + dataRow = (HSSFRow)sheet.CreateRow(RowIndex); + foreach (ReportPrint.TableColumn item in Columns) + { + int j = Columns.IndexOf(item); + dataCell = (HSSFCell)dataRow.CreateCell(j); + if (item.DataType == DbType.Boolean) + { + string value = Convert.ToString(tb.Rows[i][item.Name]); + bool bitValue = false; + if (string.IsNullOrEmpty(value) == false) bitValue = Convert.ToBoolean(value); + if (bitValue == true) { value = "是"; } + else { value = "否"; } + dataCell.SetCellValue(value); + } + else if (item.Format != "") + { + dataCell.SetCellValue(DataConvert.Format(tb.Rows[i][item.Name].ToString(), item.Format)); + } + else + { + dataCell.SetCellValue(tb.Rows[i][item.Name].ToString()); + } + dataCell.CellStyle.Alignment = HorizontalAlignment.Center; + //边框 + dataCell.CellStyle.BorderBottom = BorderStyle.Thin; + dataCell.CellStyle.BorderLeft = BorderStyle.Thin; + dataCell.CellStyle.BorderRight = BorderStyle.Thin; + dataCell.CellStyle.BorderTop = BorderStyle.Thin; + //边框颜色 + dataCell.CellStyle.BottomBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.TopBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.LeftBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.RightBorderColor = HSSFColor.Black.Index; + } + } + foreach (ReportPrint.TableColumn item in Columns) + { + int index = Columns.IndexOf(item); + if (item.Width > 0) { sheet.SetColumnWidth(index, (int)item.Width); } + else { sheet.AutoSizeColumn(index); } + } + + } + #endregion + #region List导出分页 + public void PageExport(HSSFWorkbook workbook, string SheetName, string HeaderName, List ListModel, int start, ReportPrint.TableColumnCollection Columns) where T : class + { + Type t = typeof(T); + HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet(SheetName); + sheet.PrintSetup.FitHeight = 0; + sheet.PrintSetup.FitWidth = 0; + sheet.PrintSetup.Scale = 100; + HSSFRow dataRow = null; + HSSFCell dataCell = null; + int RowIndex = 0; + if (HeaderName != "") + { + dataRow = (HSSFRow)sheet.CreateRow(0); + dataCell = (HSSFCell)dataRow.CreateCell(0); + dataCell.SetCellValue(HeaderName); + dataCell.CellStyle.Alignment = HorizontalAlignment.Center; + //边框 + dataCell.CellStyle.BorderBottom = BorderStyle.Thin; + dataCell.CellStyle.BorderLeft = BorderStyle.Thin; + dataCell.CellStyle.BorderRight = BorderStyle.Thin; + dataCell.CellStyle.BorderTop = BorderStyle.Thin; + //边框颜色 + dataCell.CellStyle.BottomBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.TopBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.LeftBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.RightBorderColor = HSSFColor.Black.Index; + sheet.AddMergedRegion(new Region(0, 0, 0, Columns.Count - 1)); + RowIndex++; + } + //填充表头 + dataRow = (HSSFRow)sheet.CreateRow(RowIndex); + foreach (ReportPrint.TableColumn item in Columns) + { + int index = Columns.IndexOf(item); + dataCell = (HSSFCell)dataRow.CreateCell(index); + dataCell.SetCellValue(item.Caption); + dataCell.CellStyle.Alignment = HorizontalAlignment.Center; + //边框 + dataCell.CellStyle.BorderBottom = BorderStyle.Thin; + dataCell.CellStyle.BorderLeft = BorderStyle.Thin; + dataCell.CellStyle.BorderRight = BorderStyle.Thin; + dataCell.CellStyle.BorderTop = BorderStyle.Thin; + //边框颜色 + dataCell.CellStyle.BottomBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.TopBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.LeftBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.RightBorderColor = HSSFColor.Black.Index; + } + int count = start + 60000; + if (ListModel.Count < count) count = ListModel.Count; + //填充内容 + for (int i = start; i < count; i++) + { + RowIndex++; + dataRow = (HSSFRow)sheet.CreateRow(RowIndex); + foreach (ReportPrint.TableColumn item in Columns) + { + int j = Columns.IndexOf(item); + dataCell = (HSSFCell)dataRow.CreateCell(j); + if (item.DataType == DbType.Boolean) + { + string value = Convert.ToString(t.GetProperty(item.Name).GetValue(ListModel[i], null)); + bool bitValue = false; + if (string.IsNullOrEmpty(value) == false) bitValue = Convert.ToBoolean(value); + if (bitValue == true) { value = "是"; } + else { value = "否"; } + dataCell.SetCellValue(value); + } + else if (item.KeyValueFormat.Count > 0) + { + string v = Convert.ToString(t.GetProperty(item.Name).GetValue(ListModel[i], null)); + foreach (var Keyitem in item.KeyValueFormat) + { + if (Keyitem.Key == v) dataCell.SetCellValue(Keyitem.Value); + } + } + else if (item.CellFormatter != null) + { + var value = Convert.ToString(item.CellFormatter(ListModel[i])); + dataCell.SetCellValue(value); + } + else if (item.Format != "") + { + dataCell.SetCellValue( + DataConvert.Format(Convert.ToString(t.GetProperty(item.Name).GetValue(ListModel[i], null)), item.Format)); + } + else + { + dataCell.SetCellValue(Convert.ToString(t.GetProperty(item.Name).GetValue(ListModel[i], null))); + } + dataCell.CellStyle.Alignment = HorizontalAlignment.Center; + //边框 + dataCell.CellStyle.BorderBottom = BorderStyle.Thin; + dataCell.CellStyle.BorderLeft = BorderStyle.Thin; + dataCell.CellStyle.BorderRight = BorderStyle.Thin; + dataCell.CellStyle.BorderTop = BorderStyle.Thin; + //边框颜色 + dataCell.CellStyle.BottomBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.TopBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.LeftBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.RightBorderColor = HSSFColor.Black.Index; + } + } + foreach (ReportPrint.TableColumn item in Columns) + { + int index = Columns.IndexOf(item); + if (item.Width > 0) { sheet.SetColumnWidth(index, (int)item.Width); } + else { sheet.AutoSizeColumn(index); } + } + + } + #endregion + #region List导出分页 + public void PageExport(HSSFWorkbook workbook, string SheetName, string HeaderName, List> ListModel, int start) + { + if (ListModel.Count == 0) return; + HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet(SheetName); + sheet.PrintSetup.FitHeight = 0; + sheet.PrintSetup.FitWidth = 0; + sheet.PrintSetup.Scale = 100; + HSSFRow dataRow = null; + HSSFCell dataCell = null; + int RowIndex = 0; + if (HeaderName != "") + { + dataRow = (HSSFRow)sheet.CreateRow(0); + dataCell = (HSSFCell)dataRow.CreateCell(0); + dataCell.SetCellValue(HeaderName); + dataCell.CellStyle.Alignment = HorizontalAlignment.Center; + //边框 + dataCell.CellStyle.BorderBottom = BorderStyle.Thin; + dataCell.CellStyle.BorderLeft = BorderStyle.Thin; + dataCell.CellStyle.BorderRight = BorderStyle.Thin; + dataCell.CellStyle.BorderTop = BorderStyle.Thin; + //边框颜色 + dataCell.CellStyle.BottomBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.TopBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.LeftBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.RightBorderColor = HSSFColor.Black.Index; + sheet.AddMergedRegion(new Region(0,0, 0, ListModel[0].Count - 1)); + RowIndex++; + } + //填充表头 + dataRow = (HSSFRow)sheet.CreateRow(RowIndex); + int index = 0; + foreach (string Caption in ListModel[0].Keys) + { + dataCell = (HSSFCell)dataRow.CreateCell(index); + dataCell.SetCellValue(Caption); + dataCell.CellStyle.Alignment = HorizontalAlignment.Center; + //边框 + dataCell.CellStyle.BorderBottom = BorderStyle.Thin; + dataCell.CellStyle.BorderLeft = BorderStyle.Thin; + dataCell.CellStyle.BorderRight = BorderStyle.Thin; + dataCell.CellStyle.BorderTop = BorderStyle.Thin; + //边框颜色 + dataCell.CellStyle.BottomBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.TopBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.LeftBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.RightBorderColor = HSSFColor.Black.Index; + + index++; + } + int count = start + 60000; + if (ListModel.Count < count) count = ListModel.Count; + //填充内容 + for (int i = start; i < count; i++) + { + RowIndex++; + dataRow = (HSSFRow)sheet.CreateRow(RowIndex); + index = 0; + foreach (string value in ListModel[i].Values) + { + dataCell = (HSSFCell)dataRow.CreateCell(index); + index++; + dataCell.SetCellValue(Convert.ToString(value)); + dataCell.CellStyle.Alignment = HorizontalAlignment.Center; + //边框 + dataCell.CellStyle.BorderBottom = BorderStyle.Thin; + dataCell.CellStyle.BorderLeft = BorderStyle.Thin; + dataCell.CellStyle.BorderRight = BorderStyle.Thin; + dataCell.CellStyle.BorderTop = BorderStyle.Thin; + //边框颜色 + dataCell.CellStyle.BottomBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.TopBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.LeftBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.RightBorderColor = HSSFColor.Black.Index; + } + } + for (int i = 0; i < ListModel[0].Count; i++) + { + sheet.AutoSizeColumn(i); + } + } + #endregion + #region 导出_自定义格式 + public string Export(HuizhongLibrary.ReportPrint.Table tb) + { + if (tb == null || tb.Rows.Count == 0) return ""; + HSSFWorkbook workbook = new HSSFWorkbook(); + HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet("Sheet1"); + sheet.PrintSetup.FitHeight = 0; + sheet.PrintSetup.FitWidth = 0; + sheet.PrintSetup.Scale = 100; + HSSFRow dataRow = null; + HSSFCell dataCell = null; + //填充内容 + for (int i = 0; i < tb.Rows.Count; i++) + { + dataRow = (HSSFRow)sheet.CreateRow(i); + for (int j = 0; j < tb.Rows[0].Cells.Count; j++) + { + HuizhongLibrary.ReportPrint.TableCell cell = tb.Rows[i].Cells[j]; + if (cell.Text == null) cell.Text = ""; + dataCell = (HSSFCell)dataRow.CreateCell(j); + dataCell.SetCellValue(cell.Text); + dataCell.CellStyle.Alignment = HorizontalAlignment.Center; + dataCell.CellStyle.VerticalAlignment = VerticalAlignment.Center; + //边框 + dataCell.CellStyle.BorderBottom = BorderStyle.Thin; + dataCell.CellStyle.BorderLeft = BorderStyle.Thin; + dataCell.CellStyle.BorderRight = BorderStyle.Thin; + dataCell.CellStyle.BorderTop = BorderStyle.Thin; + //边框颜色 + dataCell.CellStyle.BottomBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.TopBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.LeftBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.RightBorderColor = HSSFColor.Black.Index; + if (cell.RowSpan > 1 || cell.ColumnSpan > 1) sheet.AddMergedRegion(new CellRangeAddress(i, i + cell.RowSpan - 1, j, j + cell.ColumnSpan - 1)); + } + } + for (int i = 0; i < tb.Rows[0].Cells.Count; i++) + { + sheet.AutoSizeColumn(i); + } + string filename = Guid.NewGuid().ToString() + ".xls"; + string DirectoryName = AppDomain.CurrentDomain.BaseDirectory + "ServerCookies"; + if (System.IO.Directory.Exists(DirectoryName) == false) System.IO.Directory.CreateDirectory(DirectoryName); + string ServerFileName = DirectoryName + "/" + filename; + //保存 + using (FileStream fs = new FileStream(ServerFileName, FileMode.Create, FileAccess.Write)) + { + workbook.Write(fs); + } + workbook.Close(); + return "ServerCookies/" + filename; + } + #endregion + #region 测试自定义数据导入(测试合并数据用) + public void TestExport() + { + ReportPrint.Table tb = new ReportPrint.Table(); + ReportPrint.TableRow row = null; + + row = new ReportPrint.TableRow(); + row.AddCell("姓名", 1, 2); + row.AddCell("科目", 3, 1); + row.AddCell("科目", 1, 1); + row.AddCell("科目", 1, 1); + tb.Rows.Add(row); + + //第2行 + row = new ReportPrint.TableRow(); + row.AddCell("姓名", 1, 1); + row.AddCell("语文", 1, 1); + row.AddCell("数学", 1, 1); + row.AddCell("英语", 1, 1); + tb.Rows.Add(row); + + row = new ReportPrint.TableRow(); + row.AddCell("姓名", 1, 2); + row.AddCell("科目", 3, 1); + row.AddCell("科目", 1, 1); + row.AddCell("科目", 1, 1); + tb.Rows.Add(row); + + //第2行 + row = new ReportPrint.TableRow(); + row.AddCell("姓名", 1, 1); + row.AddCell("语文", 1, 1); + row.AddCell("数学", 1, 1); + row.AddCell("英语", 1, 1); + tb.Rows.Add(row); + + Export(tb); + } + #endregion + #region 导出模板 + public string ExportTemplate(List ListModel) + { + HSSFWorkbook workbook = new HSSFWorkbook(); + HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet("Sheet1"); + sheet.PrintSetup.FitHeight = 0; + sheet.PrintSetup.FitWidth = 0; + sheet.PrintSetup.Scale = 100; + HSSFRow dataRow = (HSSFRow)sheet.CreateRow(0); + HSSFCell dataCell = null; + //填充表头 + int ColIndex = 0; + foreach (string CellText in ListModel) + { + dataCell = (HSSFCell)dataRow.CreateCell(ColIndex); + dataCell.SetCellValue(CellText); + dataCell.CellStyle.Alignment = HorizontalAlignment.Center; + //边框 + dataCell.CellStyle.BorderBottom = BorderStyle.Thin; + dataCell.CellStyle.BorderLeft = BorderStyle.Thin; + dataCell.CellStyle.BorderRight = BorderStyle.Thin; + dataCell.CellStyle.BorderTop = BorderStyle.Thin; + //边框颜色 + dataCell.CellStyle.BottomBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.TopBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.LeftBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.RightBorderColor = HSSFColor.Black.Index; + ColIndex++; + } + for (int i = 0; i < ListModel.Count; i++) + { + sheet.AutoSizeColumn(i); + } + + string filename = Guid.NewGuid().ToString() + ".xls"; + string DirectoryName = AppDomain.CurrentDomain.BaseDirectory + "ServerCookies"; + if (System.IO.Directory.Exists(DirectoryName) == false) System.IO.Directory.CreateDirectory(DirectoryName); + string ServerFileName = DirectoryName + "/" + filename; + //保存 + using (FileStream fs = new FileStream(ServerFileName, FileMode.Create, FileAccess.Write)) + { + workbook.Write(fs); + } + workbook.Close(); + return "ServerCookies/" + filename; + } + #endregion + #region 导出模板 + public string ExportTemplate(Dictionary ListModel) + { + HSSFWorkbook workbook = new HSSFWorkbook(); + HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet("Sheet1"); + sheet.PrintSetup.FitHeight = 0; + sheet.PrintSetup.FitWidth = 0; + sheet.PrintSetup.Scale = 100; + HSSFRow dataRow = (HSSFRow)sheet.CreateRow(0); + HSSFCell dataCell = null; + //创建绘图对象,用于创建批注 + HSSFPatriarch patr = (HSSFPatriarch)sheet.CreateDrawingPatriarch(); + NPOI.SS.UserModel.ICreationHelper facktory = workbook.GetCreationHelper(); + NPOI.SS.UserModel.IClientAnchor anchor; + anchor = facktory.CreateClientAnchor(); + anchor.Col1 = 0; anchor.Col2 = 3; + anchor.Row1 = 0; anchor.Row2 = 8; + HSSFComment comment1; + //填充表头 + int ColIndex = 0; + foreach (KeyValuePair item in ListModel) + { + dataCell = (HSSFCell)dataRow.CreateCell(ColIndex); + dataCell.SetCellValue(item.Key); + if (item.Value != "") + { + comment1 = patr.CreateCellComment(anchor) as HSSFComment; + comment1.String = new HSSFRichTextString(item.Value); + dataCell.CellComment = comment1; + } + dataCell.CellStyle.Alignment = HorizontalAlignment.Center; + //边框 + dataCell.CellStyle.BorderBottom = BorderStyle.Thin; + dataCell.CellStyle.BorderLeft = BorderStyle.Thin; + dataCell.CellStyle.BorderRight = BorderStyle.Thin; + dataCell.CellStyle.BorderTop = BorderStyle.Thin; + //边框颜色 + dataCell.CellStyle.BottomBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.TopBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.LeftBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.RightBorderColor = HSSFColor.Black.Index; + ColIndex++; + } + for (int i = 0; i < ListModel.Count; i++) + { + sheet.AutoSizeColumn(i); + } + + string filename = Guid.NewGuid().ToString() + ".xls"; + string DirectoryName = AppDomain.CurrentDomain.BaseDirectory + "ServerCookies"; + if (System.IO.Directory.Exists(DirectoryName) == false) System.IO.Directory.CreateDirectory(DirectoryName); + string ServerFileName = DirectoryName + "/" + filename; + //保存 + using (FileStream fs = new FileStream(ServerFileName, FileMode.Create, FileAccess.Write)) + { + workbook.Write(fs); + } + workbook.Close(); + return "ServerCookies/" + filename; + } + #endregion + #region 导出模板_Winform + public void ExportTemplate(string filePath, Dictionary ListModel) + { + HSSFWorkbook workbook = new HSSFWorkbook(); + HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet("Sheet1"); + sheet.PrintSetup.FitHeight = 0; + sheet.PrintSetup.FitWidth = 0; + sheet.PrintSetup.Scale = 100; + HSSFRow dataRow = (HSSFRow)sheet.CreateRow(0); + HSSFCell dataCell = null; + //创建绘图对象,用于创建批注 + HSSFPatriarch patr = (HSSFPatriarch)sheet.CreateDrawingPatriarch(); + NPOI.SS.UserModel.ICreationHelper facktory = workbook.GetCreationHelper(); + NPOI.SS.UserModel.IClientAnchor anchor; + anchor = facktory.CreateClientAnchor(); + anchor.Col1 = 0; anchor.Col2 = 3; + anchor.Row1 = 0; anchor.Row2 = 8; + HSSFComment comment1; + //填充表头 + int ColIndex = 0; + foreach (KeyValuePair item in ListModel) + { + dataCell = (HSSFCell)dataRow.CreateCell(ColIndex); + dataCell.SetCellValue(item.Key); + if (item.Value != "") + { + comment1 = patr.CreateCellComment(anchor) as HSSFComment; + comment1.String = new HSSFRichTextString(item.Value); + dataCell.CellComment = comment1; + } + dataCell.CellStyle.Alignment = HorizontalAlignment.Center; + //边框 + dataCell.CellStyle.BorderBottom = BorderStyle.Thin; + dataCell.CellStyle.BorderLeft = BorderStyle.Thin; + dataCell.CellStyle.BorderRight = BorderStyle.Thin; + dataCell.CellStyle.BorderTop = BorderStyle.Thin; + //边框颜色 + dataCell.CellStyle.BottomBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.TopBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.LeftBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.RightBorderColor = HSSFColor.Black.Index; + ColIndex++; + } + for (int i = 0; i < ListModel.Count; i++) + { + sheet.AutoSizeColumn(i); + } + + //string filename = Guid.NewGuid().ToString() + ".xls"; + //string DirectoryName = AppDomain.CurrentDomain.BaseDirectory + "ServerCookies"; + //if (System.IO.Directory.Exists(DirectoryName) == false) System.IO.Directory.CreateDirectory(DirectoryName); + //string ServerFileName = DirectoryName + "/" + filename; + //保存 + using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write)) + { + workbook.Write(fs); + } + workbook.Close(); + } + #endregion + + #region 导出到指定文件 + public void ExportFile(string FilePath, DataTable tb, ReportPrint.TableColumnCollection Columns) + { + HSSFWorkbook workbook = new HSSFWorkbook(); + HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet("Sheet1"); + sheet.PrintSetup.FitHeight = 0; + sheet.PrintSetup.FitWidth = 0; + sheet.PrintSetup.Scale = 100; + //填充表头 + HSSFRow dataRow = (HSSFRow)sheet.CreateRow(0); + foreach (ReportPrint.TableColumn item in Columns) + { + int index = Columns.IndexOf(item); + HSSFCell dataCell = (HSSFCell)dataRow.CreateCell(index); + dataCell.SetCellValue(item.Caption); + dataCell.CellStyle.Alignment = HorizontalAlignment.Center; + //边框 + dataCell.CellStyle.BorderBottom = BorderStyle.Thin; + dataCell.CellStyle.BorderLeft = BorderStyle.Thin; + dataCell.CellStyle.BorderRight = BorderStyle.Thin; + dataCell.CellStyle.BorderTop = BorderStyle.Thin; + //边框颜色 + dataCell.CellStyle.BottomBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.TopBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.LeftBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.RightBorderColor = HSSFColor.Black.Index; + } + + //填充内容 + for (int i = 0; i < tb.Rows.Count; i++) + { + dataRow = (HSSFRow)sheet.CreateRow(i + 1); + HSSFCell dataCell = null; + foreach (ReportPrint.TableColumn item in Columns) + { + int j = Columns.IndexOf(item); + dataCell = (HSSFCell)dataRow.CreateCell(j); + if (item.Format != "") + { + dataCell.SetCellValue(DataConvert.Format(tb.Rows[i][item.Name].ToString(), item.Format)); + } + else + { + dataCell.SetCellValue(tb.Rows[i][item.Name].ToString()); + } + dataCell.CellStyle.Alignment = HorizontalAlignment.Center; + //边框 + dataCell.CellStyle.BorderBottom = BorderStyle.Thin; + dataCell.CellStyle.BorderLeft = BorderStyle.Thin; + dataCell.CellStyle.BorderRight = BorderStyle.Thin; + dataCell.CellStyle.BorderTop = BorderStyle.Thin; + //边框颜色 + dataCell.CellStyle.BottomBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.TopBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.LeftBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.RightBorderColor = HSSFColor.Black.Index; + } + } + foreach (ReportPrint.TableColumn item in Columns) + { + int index = Columns.IndexOf(item); + if (item.Width > 0) { sheet.SetColumnWidth(index, (int)item.Width); } + else { sheet.AutoSizeColumn(index); } + } + //保存 + using (FileStream fs = new FileStream(FilePath, FileMode.Create, FileAccess.Write)) + { + workbook.Write(fs); + } + workbook.Close(); + } + #endregion + #region 导出到指定文件 + public void ExportFile(string FilePath, List ListModel, ReportPrint.TableColumnCollection Columns) where T : class + { + Type t = typeof(T); + HSSFWorkbook workbook = new HSSFWorkbook(); + int sheerIndex = 1; + int start = 0; + while (true) + { + PageExport(workbook, "Sheet" + sheerIndex, "", ListModel, start, Columns); + start = start + 60000; + sheerIndex++; + if (ListModel.Count < start) break; + } + //保存 + using (FileStream fs = new FileStream(FilePath, FileMode.Create, FileAccess.Write)) + { + workbook.Write(fs); + } + workbook.Close(); + } + #endregion + #region DataSet导出到指定文件 + public void ExportFile(string FilePath, DataSet ds, List Columns) + { + HSSFWorkbook workbook = null; + for (int i = 0; i < Columns.Count; i++) + { + DataTable tb = ds.Tables[i]; + var listColumns = Columns[i]; + workbook = new HSSFWorkbook(); + PageExport(workbook, tb.TableName, "", tb, 0, listColumns); + } + //保存 + using (FileStream fs = new FileStream(FilePath, FileMode.Create, FileAccess.Write)) + { + workbook.Write(fs); + } + workbook.Close(); + } + #endregion + + #region ConvertHSSFWorkbook + public HSSFWorkbook ConvertHSSFWorkbook(DataTable tb, ReportPrint.TableColumnCollection Columns, int StartRowIndex = 0) + { + HSSFWorkbook workbook = new HSSFWorkbook(); + HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet("Sheet1"); + sheet.PrintSetup.FitHeight = 0; + sheet.PrintSetup.FitWidth = 0; + sheet.PrintSetup.Scale = 100; + HSSFRow dataRow = null; + HSSFCell dataCell = null; + if (StartRowIndex > 0) + { + for (int i = 0; i < StartRowIndex; i++) + { + dataRow = (HSSFRow)sheet.CreateRow(i); + for (int j = 0; j < Columns.Count; j++) + { + dataRow.CreateCell(j).SetCellValue(""); + } + } + } + //填充表头 + dataRow = (HSSFRow)sheet.CreateRow(StartRowIndex); + foreach (ReportPrint.TableColumn item in Columns) + { + int index = Columns.IndexOf(item); + dataCell = (HSSFCell)dataRow.CreateCell(index); + dataCell.SetCellValue(item.Caption); + dataCell.CellStyle.Alignment = HorizontalAlignment.Center; + //边框 + dataCell.CellStyle.BorderBottom = BorderStyle.Thin; + dataCell.CellStyle.BorderLeft = BorderStyle.Thin; + dataCell.CellStyle.BorderRight = BorderStyle.Thin; + dataCell.CellStyle.BorderTop = BorderStyle.Thin; + //边框颜色 + dataCell.CellStyle.BottomBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.TopBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.LeftBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.RightBorderColor = HSSFColor.Black.Index; + } + + //填充内容 + for (int i = 0; i < tb.Rows.Count; i++) + { + dataRow = (HSSFRow)sheet.CreateRow(i + StartRowIndex + 1); + dataCell = null; + foreach (ReportPrint.TableColumn item in Columns) + { + int j = Columns.IndexOf(item); + dataCell = (HSSFCell)dataRow.CreateCell(j); + if (item.Format != "") + { + dataCell.SetCellValue(DataConvert.Format(tb.Rows[i][item.Name].ToString(), item.Format)); + } + else + { + dataCell.SetCellValue(tb.Rows[i][item.Name].ToString()); + } + dataCell.CellStyle.Alignment = HorizontalAlignment.Center; + //边框 + dataCell.CellStyle.BorderBottom = BorderStyle.Thin; + dataCell.CellStyle.BorderLeft = BorderStyle.Thin; + dataCell.CellStyle.BorderRight = BorderStyle.Thin; + dataCell.CellStyle.BorderTop = BorderStyle.Thin; + //边框颜色 + dataCell.CellStyle.BottomBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.TopBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.LeftBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.RightBorderColor = HSSFColor.Black.Index; + } + } + foreach (ReportPrint.TableColumn item in Columns) + { + int index = Columns.IndexOf(item); + if (item.Width > 0) { sheet.SetColumnWidth(index, (int)item.Width); } + else { sheet.AutoSizeColumn(index); } + } + return workbook; + } + #endregion + + #region 导入 + public DataTable ImportExcel3(string fileName) + { + IWorkbook hssfworkbook; + string fileExt = Path.GetExtension(fileName); + + using (FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) + { + if (fileExt == ".xls") + { + hssfworkbook = new HSSFWorkbook(file); + } + else + { + hssfworkbook = new XSSFWorkbook(file); + } + } + + ISheet sheet = hssfworkbook.GetSheetAt(0); + IEnumerator rows = sheet.GetRowEnumerator(); + + DataTable dt = new DataTable(); + IRow row; + + rows.MoveNext(); + row = (IRow)rows.Current; + int len = row.LastCellNum; + for (int i = 0; i < len; i++) + { + ICell cell = row.GetCell(i); + if (cell != null) + { + dt.Columns.Add(cell.ToString()); + } + } + + while (rows.MoveNext()) + { + row = (IRow)rows.Current; + DataRow dr = dt.NewRow(); + + for (int i = 0; i < len; i++) + { + ICell cell = row.GetCell(i); + if (cell == null) + { + dr[i] = null; + } + else + { + if (cell.CellType == CellType.Formula || cell.CellType == CellType.Numeric) + { + dr[i] = cell.NumericCellValue; + } + else + { + dr[i] = cell.ToString(); + } + } + } + dt.Rows.Add(dr); + } + + return dt; + } + #endregion + + #region 导入(过滤空行) + public DataTable ImportExcel(string fileName) + { + int rowIndex = 1; + DataTable dt = new DataTable(); + IWorkbook hssfworkbook; + using (FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read)) + { + hssfworkbook = WorkbookFactory.Create(file); + } + ISheet sheet = hssfworkbook.GetSheetAt(0); + + IRow headRow = sheet.GetRow(0); + if (headRow != null) + { + int len = headRow.LastCellNum; + for (int i = 0; i < len; i++) + { + ICell cell = headRow.GetCell(i); + if (cell == null) continue; + string cellvalue = ""; + switch (cell.CellType) + { + case CellType.Numeric: + if (HSSFDateUtil.IsCellDateFormatted(cell))//日期类型 + { + cellvalue = cell.DateCellValue.ToString("yyyy-MM-dd HH:mm:ss"); + } + else//其他数字类型 + { + cellvalue = Convert.ToString(cell.NumericCellValue); + } + break; + case CellType.Blank: + break; + case CellType.Formula: + if (Path.GetExtension(fileName).ToLower().Trim() == ".xlsx") + { + XSSFFormulaEvaluator eva = new XSSFFormulaEvaluator(hssfworkbook); + if (eva.Evaluate(cell).CellType == CellType.Numeric) + { + cellvalue = Convert.ToString(eva.Evaluate(cell).NumberValue); + } + else + { + cellvalue = eva.Evaluate(cell).StringValue; + } + } + else + { + HSSFFormulaEvaluator eva = new HSSFFormulaEvaluator(hssfworkbook); + if (eva.Evaluate(cell).CellType == CellType.Numeric) + { + cellvalue = Convert.ToString(eva.Evaluate(cell).NumberValue); + } + else + { + cellvalue = eva.Evaluate(cell).StringValue; + } + } + break; + default: + cellvalue = cell.StringCellValue; + break; + } + if (cellvalue != "") dt.Columns.Add(cellvalue); + } + } + + for (int i = (sheet.FirstRowNum + rowIndex); i <= sheet.LastRowNum; i++) + { + IRow row = sheet.GetRow(i); + bool emptyRow = true; + object[] itemArray = null; + + if (row != null) + { + itemArray = new object[dt.Columns.Count]; + + for (int j = row.FirstCellNum; j < itemArray.Length; j++) + { + + if (row.GetCell(j) != null) + { + + switch (row.GetCell(j).CellType) + { + case CellType.Numeric: + if (HSSFDateUtil.IsCellDateFormatted(row.GetCell(j)))//日期类型 + { + itemArray[j] = row.GetCell(j).DateCellValue.ToString("yyyy-MM-dd HH:mm:ss"); + } + else//其他数字类型 + { + itemArray[j] = row.GetCell(j).NumericCellValue; + } + break; + case CellType.Blank: + itemArray[j] = string.Empty; + break; + case CellType.Formula: + if (Path.GetExtension(fileName).ToLower().Trim() == ".xlsx") + { + XSSFFormulaEvaluator eva = new XSSFFormulaEvaluator(hssfworkbook); + if (eva.Evaluate(row.GetCell(j)).CellType == CellType.Numeric) + { + itemArray[j] = eva.Evaluate(row.GetCell(j)).NumberValue; + } + else + { + itemArray[j] = eva.Evaluate(row.GetCell(j)).StringValue; + } + } + else + { + HSSFFormulaEvaluator eva = new HSSFFormulaEvaluator(hssfworkbook); + if (eva.Evaluate(row.GetCell(j)).CellType == CellType.Numeric) + { + itemArray[j] = eva.Evaluate(row.GetCell(j)).NumberValue; + } + else + { + itemArray[j] = eva.Evaluate(row.GetCell(j)).StringValue; + } + } + break; + default: + itemArray[j] = row.GetCell(j).StringCellValue; + break; + + } + + if (itemArray[j] != null && !string.IsNullOrEmpty(itemArray[j].ToString().Trim())) + { + emptyRow = false; + } + } + } + } + + //非空数据行数据添加到DataTable + if (!emptyRow) + { + dt.Rows.Add(itemArray); + } + } + return dt; + } + #endregion + #region 导入多表(过滤空行) + public DataTable ImportExcel2(string fileName) + { + DataTable dt = new DataTable(); + IWorkbook hssfworkbook; + using (FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read)) + { + hssfworkbook = WorkbookFactory.Create(file); + } + for (int sindex = 0; sindex < hssfworkbook.NumberOfSheets; sindex++) + { + ISheet sheet = hssfworkbook.GetSheetAt(sindex); + if (sindex == 0) + { + IRow headRow = sheet.GetRow(0); + if (headRow != null) + { + int len = headRow.LastCellNum; + for (int i = 0; i < len; i++) + { + ICell cell = headRow.GetCell(i); + if (cell == null) continue; + string cellvalue = ""; + switch (cell.CellType) + { + case CellType.Numeric: + if (HSSFDateUtil.IsCellDateFormatted(cell))//日期类型 + { + cellvalue = cell.DateCellValue.ToString("yyyy-MM-dd HH:mm:ss"); + } + else//其他数字类型 + { + cellvalue = Convert.ToString(cell.NumericCellValue); + } + break; + case CellType.Blank: + break; + case CellType.Formula: + if (Path.GetExtension(fileName).ToLower().Trim() == ".xlsx") + { + XSSFFormulaEvaluator eva = new XSSFFormulaEvaluator(hssfworkbook); + if (eva.Evaluate(cell).CellType == CellType.Numeric) + { + cellvalue = Convert.ToString(eva.Evaluate(cell).NumberValue); + } + else + { + cellvalue = eva.Evaluate(cell).StringValue; + } + } + else + { + HSSFFormulaEvaluator eva = new HSSFFormulaEvaluator(hssfworkbook); + if (eva.Evaluate(cell).CellType == CellType.Numeric) + { + cellvalue = Convert.ToString(eva.Evaluate(cell).NumberValue); + } + else + { + cellvalue = eva.Evaluate(cell).StringValue; + } + } + break; + default: + cellvalue = cell.StringCellValue; + break; + } + if (cellvalue != "") dt.Columns.Add(cellvalue); + } + } + } + int rowIndex = 1; + for (int i = (sheet.FirstRowNum + rowIndex); i <= sheet.LastRowNum; i++) + { + IRow row = sheet.GetRow(i); + bool emptyRow = true; + object[] itemArray = null; + + if (row != null) + { + itemArray = new object[dt.Columns.Count]; + + for (int j = row.FirstCellNum; j < itemArray.Length; j++) + { + + if (row.GetCell(j) != null) + { + + switch (row.GetCell(j).CellType) + { + case CellType.Numeric: + if (HSSFDateUtil.IsCellDateFormatted(row.GetCell(j)))//日期类型 + { + itemArray[j] = row.GetCell(j).DateCellValue.ToString("yyyy-MM-dd HH:mm:ss"); + } + else//其他数字类型 + { + itemArray[j] = row.GetCell(j).NumericCellValue; + } + break; + case CellType.Blank: + itemArray[j] = string.Empty; + break; + case CellType.Formula: + if (Path.GetExtension(fileName).ToLower().Trim() == ".xlsx") + { + XSSFFormulaEvaluator eva = new XSSFFormulaEvaluator(hssfworkbook); + if (eva.Evaluate(row.GetCell(j)).CellType == CellType.Numeric) + { + itemArray[j] = eva.Evaluate(row.GetCell(j)).NumberValue; + } + else + { + itemArray[j] = eva.Evaluate(row.GetCell(j)).StringValue; + } + } + else + { + HSSFFormulaEvaluator eva = new HSSFFormulaEvaluator(hssfworkbook); + if (eva.Evaluate(row.GetCell(j)).CellType == CellType.Numeric) + { + itemArray[j] = eva.Evaluate(row.GetCell(j)).NumberValue; + } + else + { + itemArray[j] = eva.Evaluate(row.GetCell(j)).StringValue; + } + } + break; + default: + itemArray[j] = row.GetCell(j).StringCellValue; + break; + + } + + if (itemArray[j] != null && !string.IsNullOrEmpty(itemArray[j].ToString().Trim())) + { + emptyRow = false; + } + } + } + } + + //非空数据行数据添加到DataTable + if (!emptyRow) + { + dt.Rows.Add(itemArray); + } + + } + } + return dt; + } + #endregion + + #region 导入(过滤空行)(排除从第一行开始的前几行) + public DataTable ImportExcel(string fileName, int RemoveCount) + { + int rowIndex = 1 + RemoveCount; + DataTable dt = new DataTable(); + IWorkbook hssfworkbook; + using (FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read)) + { + hssfworkbook = WorkbookFactory.Create(file); + } + ISheet sheet = hssfworkbook.GetSheetAt(0); + + IRow headRow = sheet.GetRow(RemoveCount); + if (headRow != null) + { + int len = headRow.LastCellNum; + for (int i = 0; i < len; i++) + { + ICell cell = headRow.GetCell(i); + if (cell == null) continue; + string cellvalue = ""; + switch (cell.CellType) + { + case CellType.Numeric: + if (HSSFDateUtil.IsCellDateFormatted(cell))//日期类型 + { + cellvalue = cell.DateCellValue.ToString("yyyy-MM-dd HH:mm:ss"); + } + else//其他数字类型 + { + cellvalue = Convert.ToString(cell.NumericCellValue); + } + break; + case CellType.Blank: + break; + case CellType.Formula: + if (Path.GetExtension(fileName).ToLower().Trim() == ".xlsx") + { + XSSFFormulaEvaluator eva = new XSSFFormulaEvaluator(hssfworkbook); + if (eva.Evaluate(cell).CellType == CellType.Numeric) + { + cellvalue = Convert.ToString(eva.Evaluate(cell).NumberValue); + } + else + { + cellvalue = eva.Evaluate(cell).StringValue; + } + } + else + { + HSSFFormulaEvaluator eva = new HSSFFormulaEvaluator(hssfworkbook); + if (eva.Evaluate(cell).CellType == CellType.Numeric) + { + cellvalue = Convert.ToString(eva.Evaluate(cell).NumberValue); + } + else + { + cellvalue = eva.Evaluate(cell).StringValue; + } + } + break; + default: + cellvalue = cell.StringCellValue; + break; + } + if (cellvalue != "") dt.Columns.Add(cellvalue); + } + } + + for (int i = (sheet.FirstRowNum + rowIndex); i <= sheet.LastRowNum; i++) + { + IRow row = sheet.GetRow(i); + bool emptyRow = true; + object[] itemArray = null; + + if (row != null) + { + itemArray = new object[dt.Columns.Count]; + + for (int j = row.FirstCellNum; j < itemArray.Length; j++) + { + + if (row.GetCell(j) != null) + { + + switch (row.GetCell(j).CellType) + { + case CellType.Numeric: + if (HSSFDateUtil.IsCellDateFormatted(row.GetCell(j)))//日期类型 + { + itemArray[j] = row.GetCell(j).DateCellValue.ToString("yyyy-MM-dd HH:mm:ss"); + } + else//其他数字类型 + { + itemArray[j] = row.GetCell(j).NumericCellValue; + } + break; + case CellType.Blank: + itemArray[j] = string.Empty; + break; + case CellType.Formula: + if (Path.GetExtension(fileName).ToLower().Trim() == ".xlsx") + { + XSSFFormulaEvaluator eva = new XSSFFormulaEvaluator(hssfworkbook); + if (eva.Evaluate(row.GetCell(j)).CellType == CellType.Numeric) + { + itemArray[j] = eva.Evaluate(row.GetCell(j)).NumberValue; + } + else + { + itemArray[j] = eva.Evaluate(row.GetCell(j)).StringValue; + } + } + else + { + HSSFFormulaEvaluator eva = new HSSFFormulaEvaluator(hssfworkbook); + if (eva.Evaluate(row.GetCell(j)).CellType == CellType.Numeric) + { + itemArray[j] = eva.Evaluate(row.GetCell(j)).NumberValue; + } + else + { + itemArray[j] = eva.Evaluate(row.GetCell(j)).StringValue; + } + } + break; + default: + itemArray[j] = row.GetCell(j).StringCellValue; + break; + + } + + if (itemArray[j] != null && !string.IsNullOrEmpty(itemArray[j].ToString().Trim())) + { + emptyRow = false; + } + } + } + } + + //非空数据行数据添加到DataTable + if (!emptyRow) + { + dt.Rows.Add(itemArray); + } + } + return dt; + } + #endregion + + #region List导出分页 + public string ExportXlsx(string HeaderName, List lst, ReportPrint.TableColumnCollection Columns) where T : class + { + Type t = typeof(T); + IWorkbook workbook = new XSSFWorkbook(); + ISheet sheet = (ISheet)workbook.CreateSheet("Sheet1"); + sheet.PrintSetup.FitHeight = 0; + sheet.PrintSetup.FitWidth = 0; + sheet.PrintSetup.Scale = 100; + IRow dataRow = null; + ICell dataCell = null; + int RowIndex = 0; + if (HeaderName != "") + { + dataRow = (IRow)sheet.CreateRow(0); + dataCell = (ICell)dataRow.CreateCell(0); + dataCell.SetCellValue(HeaderName); + dataCell.CellStyle.Alignment = HorizontalAlignment.Center; + //边框 + dataCell.CellStyle.BorderBottom = BorderStyle.Thin; + dataCell.CellStyle.BorderLeft = BorderStyle.Thin; + dataCell.CellStyle.BorderRight = BorderStyle.Thin; + dataCell.CellStyle.BorderTop = BorderStyle.Thin; + //边框颜色 + dataCell.CellStyle.BottomBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.TopBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.LeftBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.RightBorderColor = HSSFColor.Black.Index; + sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, Columns.Count - 1)); + RowIndex++; + } + //填充表头 + dataRow = (IRow)sheet.CreateRow(RowIndex); + foreach (ReportPrint.TableColumn item in Columns) + { + int index = Columns.IndexOf(item); + dataCell = (ICell)dataRow.CreateCell(index); + dataCell.SetCellValue(item.Caption); + dataCell.CellStyle.Alignment = HorizontalAlignment.Center; + //边框 + dataCell.CellStyle.BorderBottom = BorderStyle.Thin; + dataCell.CellStyle.BorderLeft = BorderStyle.Thin; + dataCell.CellStyle.BorderRight = BorderStyle.Thin; + dataCell.CellStyle.BorderTop = BorderStyle.Thin; + //边框颜色 + dataCell.CellStyle.BottomBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.TopBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.LeftBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.RightBorderColor = HSSFColor.Black.Index; + } + //填充内容 + for (int i = 0; i < lst.Count; i++) + { + RowIndex++; + dataRow = (IRow)sheet.CreateRow(RowIndex); + foreach (ReportPrint.TableColumn item in Columns) + { + int j = Columns.IndexOf(item); + dataCell = (ICell)dataRow.CreateCell(j); + if (item.DataType == DbType.Boolean) + { + string value = Convert.ToString(t.GetProperty(item.Name).GetValue(lst[i], null)); + bool bitValue = false; + if (string.IsNullOrEmpty(value) == false) bitValue = Convert.ToBoolean(value); + if (bitValue == true) { value = "是"; } + else { value = "否"; } + dataCell.SetCellValue(value); + } + else if (item.KeyValueFormat.Count > 0) + { + string v = Convert.ToString(t.GetProperty(item.Name).GetValue(lst[i], null)); + foreach (var Keyitem in item.KeyValueFormat) + { + if (Keyitem.Key == v) dataCell.SetCellValue(Keyitem.Value); + } + } + else if (item.Format != "") + { + dataCell.SetCellValue( + DataConvert.Format(Convert.ToString(t.GetProperty(item.Name).GetValue(lst[i], null)), item.Format)); + } + else + { + dataCell.SetCellValue(Convert.ToString(t.GetProperty(item.Name).GetValue(lst[i], null))); + } + dataCell.CellStyle.Alignment = HorizontalAlignment.Center; + //边框 + dataCell.CellStyle.BorderBottom = BorderStyle.Thin; + dataCell.CellStyle.BorderLeft = BorderStyle.Thin; + dataCell.CellStyle.BorderRight = BorderStyle.Thin; + dataCell.CellStyle.BorderTop = BorderStyle.Thin; + //边框颜色 + dataCell.CellStyle.BottomBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.TopBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.LeftBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.RightBorderColor = HSSFColor.Black.Index; + } + } + foreach (ReportPrint.TableColumn item in Columns) + { + int index = Columns.IndexOf(item); + if (item.Width > 0) { sheet.SetColumnWidth(index, (int)item.Width); } + else { sheet.AutoSizeColumn(index); } + } + string filename = Guid.NewGuid().ToString() + ".xls"; + string DirectoryName = AppDomain.CurrentDomain.BaseDirectory + "ServerCookies"; + if (System.IO.Directory.Exists(DirectoryName) == false) System.IO.Directory.CreateDirectory(DirectoryName); + string ServerFileName = DirectoryName + "/" + filename; + //保存 + using (FileStream fs = new FileStream(ServerFileName, FileMode.Create, FileAccess.Write)) + { + workbook.Write(fs); + } + workbook.Close(); + return "ServerCookies/" + filename; + + } + #endregion + #region List导出分页 + public string ExportXlsx(string HeaderName, DataTable tb, ReportPrint.TableColumnCollection Columns) + { + IWorkbook workbook = new XSSFWorkbook(); + ISheet sheet = (ISheet)workbook.CreateSheet("Sheet1"); + sheet.PrintSetup.FitHeight = 0; + sheet.PrintSetup.FitWidth = 0; + sheet.PrintSetup.Scale = 100; + IRow dataRow = null; + ICell dataCell = null; + int RowIndex = 0; + if (HeaderName != "") + { + dataRow = (IRow)sheet.CreateRow(0); + dataCell = (ICell)dataRow.CreateCell(0); + dataCell.SetCellValue(HeaderName); + dataCell.CellStyle.Alignment = HorizontalAlignment.Center; + //边框 + dataCell.CellStyle.BorderBottom = BorderStyle.Thin; + dataCell.CellStyle.BorderLeft = BorderStyle.Thin; + dataCell.CellStyle.BorderRight = BorderStyle.Thin; + dataCell.CellStyle.BorderTop = BorderStyle.Thin; + //边框颜色 + dataCell.CellStyle.BottomBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.TopBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.LeftBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.RightBorderColor = HSSFColor.Black.Index; + sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, Columns.Count - 1)); + RowIndex++; + } + //填充表头 + dataRow = (IRow)sheet.CreateRow(RowIndex); + foreach (ReportPrint.TableColumn item in Columns) + { + int index = Columns.IndexOf(item); + dataCell = (ICell)dataRow.CreateCell(index); + dataCell.SetCellValue(item.Caption); + dataCell.CellStyle.Alignment = HorizontalAlignment.Center; + //边框 + dataCell.CellStyle.BorderBottom = BorderStyle.Thin; + dataCell.CellStyle.BorderLeft = BorderStyle.Thin; + dataCell.CellStyle.BorderRight = BorderStyle.Thin; + dataCell.CellStyle.BorderTop = BorderStyle.Thin; + //边框颜色 + dataCell.CellStyle.BottomBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.TopBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.LeftBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.RightBorderColor = HSSFColor.Black.Index; + } + //填充内容 + for (int i = 0; i < tb.Rows.Count; i++) + { + RowIndex++; + DataRow row = tb.Rows[i]; + dataRow = (IRow)sheet.CreateRow(RowIndex); + foreach (ReportPrint.TableColumn item in Columns) + { + int j = Columns.IndexOf(item); + dataCell = (ICell)dataRow.CreateCell(j); + if (item.DataType == DbType.Boolean) + { + string value = Convert.ToString(row[item.Name]); + bool bitValue = false; + if (string.IsNullOrEmpty(value) == false) bitValue = Convert.ToBoolean(value); + if (bitValue == true) { value = "是"; } + else { value = "否"; } + dataCell.SetCellValue(value); + } + else if (item.KeyValueFormat.Count > 0) + { + string v = Convert.ToString(row[item.Name]); + foreach (var Keyitem in item.KeyValueFormat) + { + if (Keyitem.Key == v) dataCell.SetCellValue(Keyitem.Value); + } + } + else if (item.Format != "") + { + dataCell.SetCellValue( + DataConvert.Format(Convert.ToString(row[item.Name]), item.Format)); + } + else + { + dataCell.SetCellValue(Convert.ToString(row[item.Name])); + } + dataCell.CellStyle.Alignment = HorizontalAlignment.Center; + //边框 + dataCell.CellStyle.BorderBottom = BorderStyle.Thin; + dataCell.CellStyle.BorderLeft = BorderStyle.Thin; + dataCell.CellStyle.BorderRight = BorderStyle.Thin; + dataCell.CellStyle.BorderTop = BorderStyle.Thin; + //边框颜色 + dataCell.CellStyle.BottomBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.TopBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.LeftBorderColor = HSSFColor.Black.Index; + dataCell.CellStyle.RightBorderColor = HSSFColor.Black.Index; + } + } + foreach (ReportPrint.TableColumn item in Columns) + { + int index = Columns.IndexOf(item); + if (item.Width > 0) { sheet.SetColumnWidth(index, (int)item.Width); } + else { sheet.AutoSizeColumn(index); } + } + string filename = Guid.NewGuid().ToString() + ".xls"; + string DirectoryName = AppDomain.CurrentDomain.BaseDirectory + "ServerCookies"; + if (System.IO.Directory.Exists(DirectoryName) == false) System.IO.Directory.CreateDirectory(DirectoryName); + string ServerFileName = DirectoryName + "/" + filename; + //保存 + using (FileStream fs = new FileStream(ServerFileName, FileMode.Create, FileAccess.Write)) + { + workbook.Write(fs); + } + workbook.Close(); + return "ServerCookies/" + filename; + + } + #endregion + } +} diff --git a/基础类库/HuizhongLibrary/MicrosoftWord.cs b/基础类库/HuizhongLibrary/MicrosoftWord.cs new file mode 100644 index 0000000..b000b95 --- /dev/null +++ b/基础类库/HuizhongLibrary/MicrosoftWord.cs @@ -0,0 +1,2665 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Drawing; +using Aspose.Words; +using System.Data; +using HuizhongLibrary.ReportPrint; +using HuizhongLibrary.Log; +using System.IO; +using System.Drawing.Printing; +using Aspose.Words.Drawing; +using System.Drawing.Imaging; +using Aspose.Words.Saving; +using System.Collections; +using Aspose.Words.Fields; + +namespace HuizhongLibrary +{ + public class MicrosoftWord + { + #region 导出Work测试蛟川 + public string Exportjc() + { + WordReport report = new WordReport(); + WordTable tb = new WordTable(); + report.ListTables.Add(tb); + tb.ListTexts.Add(new WordText("用户个人信息", 20, "Center")); + tb.ListTexts.Add(new WordText("", 20, "Center")); + tb.ListTexts.Add(new WordText("个人标识码:" + Space(8) + "所在学校:宁波市镇海蛟川书院", 10, "Center")); + + List ListColumnWidth = new List(); + ListColumnWidth.Add(80); + ListColumnWidth.Add(120); + ListColumnWidth.Add(80); + ListColumnWidth.Add(150); + + WordCell cell = null; + //第1行 + var Row = new List(); + tb.Rows.Add(Row); + + cell = new WordCell(); + cell.Width = ListColumnWidth[0]; + cell.Text = "姓名"; + cell.Background = Color.AliceBlue; + cell.TextAlign = "Right"; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[1]; + cell.Text = "符水波"; + cell.TextAlign = "Left"; + cell.ColumnSpan = 2; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[2]; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[3]; + cell.ImageWidth = 100; + cell.ImageHeight = 150; + cell.Text = AppDomain.CurrentDomain.BaseDirectory + "Photo/刘学左.jpg"; + cell.ContentType = WordCellType.ImagePath; + //cell.Text = "测试合并"; + cell.RowSpan = 7; + Row.Add(cell); + + //第2行 + Row = new List(); + tb.Rows.Add(Row); + + cell = new WordCell(); + cell.Width = ListColumnWidth[0]; + cell.Text = "曾用名"; + cell.Background = Color.AliceBlue; + cell.TextAlign = "Right"; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[1]; + cell.Text = "符水波"; + cell.TextAlign = "Left"; + cell.ColumnSpan = 2; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[2]; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[3]; + cell.Text = ""; + Row.Add(cell); + + //第3行 + Row = new List(); + tb.Rows.Add(Row); + + cell = new WordCell(); + cell.Width = ListColumnWidth[0]; + cell.Text = "性别"; + cell.Background = Color.AliceBlue; + cell.TextAlign = "Right"; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[1]; + cell.Text = "符水波"; + cell.TextAlign = "Left"; + cell.ColumnSpan = 2; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[2]; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[3]; + cell.Text = ""; + Row.Add(cell); + + //第4行 + Row = new List(); + tb.Rows.Add(Row); + + cell = new WordCell(); + cell.Width = ListColumnWidth[0]; + cell.Text = "教职工号"; + cell.Background = Color.AliceBlue; + cell.TextAlign = "Right"; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[1]; + cell.Text = "符水波"; + cell.TextAlign = "Left"; + cell.ColumnSpan = 2; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[2]; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[3]; + cell.Text = ""; + Row.Add(cell); + + //第5行 + Row = new List(); + tb.Rows.Add(Row); + + cell = new WordCell(); + cell.Width = ListColumnWidth[0]; + cell.Text = "国籍/地区"; + cell.Background = Color.AliceBlue; + cell.TextAlign = "Right"; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[1]; + cell.Text = "符水波"; + cell.TextAlign = "Left"; + cell.ColumnSpan = 2; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[2]; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[3]; + cell.Text = ""; + Row.Add(cell); + + //第6行 + Row = new List(); + tb.Rows.Add(Row); + + cell = new WordCell(); + cell.Width = ListColumnWidth[0]; + cell.Text = "身份证件类型"; + cell.Background = Color.AliceBlue; + cell.TextAlign = "Right"; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[1]; + cell.Text = "符水波"; + cell.TextAlign = "Left"; + cell.ColumnSpan = 2; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[2]; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[3]; + cell.Text = ""; + Row.Add(cell); + + //第7行 + Row = new List(); + tb.Rows.Add(Row); + + cell = new WordCell(); + cell.Width = ListColumnWidth[0]; + cell.Text = "身份证件号"; + cell.Background = Color.AliceBlue; + cell.TextAlign = "Right"; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[1]; + cell.Text = "符水波"; + cell.TextAlign = "Left"; + cell.ColumnSpan = 2; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[2]; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[3]; + cell.Text = ""; + Row.Add(cell); + + //第8行 + Row = new List(); + tb.Rows.Add(Row); + + cell = new WordCell(); + cell.Width = ListColumnWidth[0]; + cell.Text = "身份证件号"; + cell.Background = Color.AliceBlue; + cell.TextAlign = "Right"; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[1]; + cell.Text = "符水波"; + cell.TextAlign = "Left"; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[2]; + cell.Text = "符水波"; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[3]; + cell.Text = "符水波"; + Row.Add(cell); + + + tb = new WordTable(); + report.ListTables.Add(tb); + tb.ListTexts.Add(new WordText("", 20, "Center")); + tb.ListTexts.Add(new WordText("用户个人信息2", 10, "Center")); + tb.ListTexts.Add(new WordText("", 20, "Center")); + + + //第1行 + Row = new List(); + tb.Rows.Add(Row); + + cell = new WordCell(); + cell.Width = ListColumnWidth[0]; + cell.Text = "姓名"; + cell.Background = Color.AliceBlue; + cell.TextAlign = "Right"; + Row.Add(cell); + + + return Export(report); + } + #endregion + #region 导出Work测试 + public string ExportTest() + { + List listReport = new List(); + int PageCount = 2; + for (int k = 0; k < PageCount; k++) + { + WordReport report = new WordReport(); + listReport.Add(report); + WordTable tb = new WordTable(); + report.ListTables.Add(tb); + tb.ListTexts.Add(new WordText("新生报名登记表", 20, "Center")); + tb.ListTexts.Add(new WordText("", 20, "Center")); + + //宽595*高848 + List ListColumnWidth = new List(); + ListColumnWidth.Add(75); + ListColumnWidth.Add(75); + ListColumnWidth.Add(75); + ListColumnWidth.Add(75); + ListColumnWidth.Add(75); + ListColumnWidth.Add(75); + ListColumnWidth.Add(120); + + double RowHeight = 30; + + WordCell cell = null; + //第1行 + var Row = new List(); + tb.Rows.Add(Row); + + cell = new WordCell(); + cell.Width = ListColumnWidth[0]; + cell.Height = RowHeight; + cell.Text = "姓名"; + cell.Background = Color.AliceBlue; + cell.TextAlign = "Right"; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[1]; + cell.Height = RowHeight; + cell.Text = "符水波"; + cell.TextAlign = "Left"; + cell.ColumnSpan = 3; + Row.Add(cell); + + for (int i = 2; i < 4; i++) + { + cell = new WordCell(); + cell.Width = ListColumnWidth[i]; + cell.Height = RowHeight; + Row.Add(cell); + } + + cell = new WordCell(); + cell.Width = ListColumnWidth[4]; + cell.Height = RowHeight; + cell.Text = "性别"; + cell.Background = Color.AliceBlue; + cell.TextAlign = "Right"; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[5]; + cell.Height = RowHeight; + cell.Text = "男"; + cell.TextAlign = "Left"; + cell.ColumnSpan = 2; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[6]; + cell.Height = RowHeight; + Row.Add(cell); + + //第2行 + Row = new List(); + tb.Rows.Add(Row); + + cell = new WordCell(); + cell.Width = ListColumnWidth[0]; + cell.Height = RowHeight; + cell.Text = "出生日期"; + cell.Background = Color.AliceBlue; + cell.TextAlign = "Right"; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[1]; + cell.Height = RowHeight; + cell.Text = "1996-01-01"; + cell.TextAlign = "Left"; + cell.ColumnSpan = 3; + Row.Add(cell); + + for (int i = 2; i < 4; i++) + { + cell = new WordCell(); + cell.Width = ListColumnWidth[i]; + cell.Height = RowHeight; + Row.Add(cell); + } + + cell = new WordCell(); + cell.Width = ListColumnWidth[4]; + cell.Height = RowHeight; + cell.Text = "身份证号码"; + cell.Background = Color.AliceBlue; + cell.TextAlign = "Right"; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[5]; + cell.Height = RowHeight; + cell.Text = "3302241978561415"; + cell.TextAlign = "Left"; + cell.ColumnSpan = 2; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[6]; + cell.Height = RowHeight; + Row.Add(cell); + + //第3行 + Row = new List(); + tb.Rows.Add(Row); + + cell = new WordCell(); + cell.Width = ListColumnWidth[0]; + cell.Height = RowHeight; + cell.Text = "户籍类别"; + cell.Background = Color.AliceBlue; + cell.TextAlign = "Right"; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[1]; + cell.Height = RowHeight; + cell.Text = "居民"; + cell.TextAlign = "Left"; + cell.ColumnSpan = 3; + Row.Add(cell); + + for (int i = 2; i < 4; i++) + { + cell = new WordCell(); + cell.Width = ListColumnWidth[i]; + cell.Height = RowHeight; + Row.Add(cell); + } + + cell = new WordCell(); + cell.Width = ListColumnWidth[4]; + cell.Height = RowHeight; + cell.Text = "就读幼儿园"; + cell.Background = Color.AliceBlue; + cell.TextAlign = "Right"; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[5]; + cell.Height = RowHeight; + cell.Text = "江东"; + cell.TextAlign = "Left"; + cell.ColumnSpan = 2; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[6]; + cell.Height = RowHeight; + Row.Add(cell); + + + //第4行 + Row = new List(); + tb.Rows.Add(Row); + + cell = new WordCell(); + cell.Width = ListColumnWidth[0]; + cell.Height = RowHeight; + cell.Text = "户籍所在地"; + cell.Background = Color.AliceBlue; + cell.TextAlign = "Right"; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[1]; + cell.Height = RowHeight; + cell.Text = "浙江省宁波市江东区XXX街道1号106室"; + cell.TextAlign = "Left"; + cell.ColumnSpan = 6; + Row.Add(cell); + + for (int i = 2; i < 7; i++) + { + cell = new WordCell(); + cell.Width = ListColumnWidth[i]; + cell.Height = RowHeight; + Row.Add(cell); + } + + //第5行 + Row = new List(); + tb.Rows.Add(Row); + + cell = new WordCell(); + cell.Width = ListColumnWidth[0]; + cell.Height = RowHeight; + cell.Text = "常住地址"; + cell.Background = Color.AliceBlue; + cell.TextAlign = "Right"; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[1]; + cell.Height = RowHeight; + cell.Text = "浙江省宁波市江东区XXX街道1号106室"; + cell.TextAlign = "Left"; + cell.ColumnSpan = 6; + Row.Add(cell); + + for (int i = 2; i < 7; i++) + { + cell = new WordCell(); + cell.Width = ListColumnWidth[i]; + cell.Height = RowHeight; + Row.Add(cell); + } + + //第6行 + Row = new List(); + tb.Rows.Add(Row); + + cell = new WordCell(); + cell.Width = ListColumnWidth[0]; + cell.Height = RowHeight; + cell.Text = "电话"; + cell.Background = Color.AliceBlue; + cell.TextAlign = "Right"; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[1]; + cell.Height = RowHeight; + cell.Text = "6589952535"; + cell.TextAlign = "Left"; + cell.ColumnSpan = 6; + Row.Add(cell); + + for (int i = 2; i < 7; i++) + { + cell = new WordCell(); + cell.Width = ListColumnWidth[i]; + cell.Height = RowHeight; + Row.Add(cell); + } + + //第7行 + Row = new List(); + tb.Rows.Add(Row); + RowHeight = 200; + + cell = new WordCell(); + cell.Width = ListColumnWidth[0]; + cell.Height = RowHeight; + cell.Text = "特长及荣誉"; + cell.Background = Color.AliceBlue; + cell.TextAlign = "Right"; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[1]; + cell.Height = RowHeight; + cell.Text = ""; + cell.TextAlign = "Left"; + cell.ColumnSpan = 6; + Row.Add(cell); + + for (int i = 2; i < 7; i++) + { + cell = new WordCell(); + cell.Width = ListColumnWidth[i]; + cell.Height = RowHeight; + Row.Add(cell); + } + + //第8行 + Row = new List(); + tb.Rows.Add(Row); + + cell = new WordCell(); + cell.Width = ListColumnWidth[0]; + cell.Height = RowHeight; + cell.Text = "选择学校的原因"; + cell.Background = Color.AliceBlue; + cell.TextAlign = "Right"; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[1]; + cell.Height = RowHeight; + cell.Text = ""; + cell.TextAlign = "Left"; + cell.ColumnSpan = 6; + Row.Add(cell); + + for (int i = 2; i < 7; i++) + { + cell = new WordCell(); + cell.Width = ListColumnWidth[i]; + cell.Height = RowHeight; + Row.Add(cell); + } + + //第9行 + Row = new List(); + tb.Rows.Add(Row); + RowHeight = 30; + + cell = new WordCell(); + cell.Width = ListColumnWidth[0]; + cell.Height = RowHeight; + cell.Text = "称谓"; + cell.Background = Color.AliceBlue; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[1]; + cell.Height = RowHeight; + cell.Text = "姓名"; + cell.Background = Color.AliceBlue; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[2]; + cell.Height = RowHeight; + cell.Text = "工作单位"; + cell.Background = Color.AliceBlue; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[3]; + cell.Height = RowHeight; + cell.Text = "职务"; + cell.Background = Color.AliceBlue; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[4]; + cell.Height = RowHeight; + cell.Text = "学历"; + cell.Background = Color.AliceBlue; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[5]; + cell.Height = RowHeight; + cell.Text = "联系电话"; + cell.Background = Color.AliceBlue; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[6]; + cell.Height = RowHeight; + cell.Text = "身份证号码"; + cell.Background = Color.AliceBlue; + Row.Add(cell); + + //第10行 + Row = new List(); + tb.Rows.Add(Row); + + cell = new WordCell(); + cell.Width = ListColumnWidth[0]; + cell.Height = RowHeight; + cell.Text = ""; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[1]; + cell.Height = RowHeight; + cell.Text = ""; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[2]; + cell.Height = RowHeight; + cell.Text = ""; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[3]; + cell.Height = RowHeight; + cell.Text = ""; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[4]; + cell.Height = RowHeight; + cell.Text = ""; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[5]; + cell.Height = RowHeight; + cell.Text = ""; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[6]; + cell.Height = RowHeight; + cell.Text = ""; + Row.Add(cell); + + //第11行 + Row = new List(); + tb.Rows.Add(Row); + + cell = new WordCell(); + cell.Width = ListColumnWidth[0]; + cell.Height = RowHeight; + cell.Text = ""; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[1]; + cell.Height = RowHeight; + cell.Text = ""; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[2]; + cell.Height = RowHeight; + cell.Text = ""; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[3]; + cell.Height = RowHeight; + cell.Text = ""; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[4]; + cell.Height = RowHeight; + cell.Text = ""; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[5]; + cell.Height = RowHeight; + cell.Text = ""; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[6]; + cell.Height = RowHeight; + cell.Text = ""; + Row.Add(cell); + + + //第12行 + Row = new List(); + tb.Rows.Add(Row); + + cell = new WordCell(); + cell.Width = ListColumnWidth[0]; + cell.Height = RowHeight; + cell.Text = "是否住宿"; + cell.Background = Color.AliceBlue; + Row.Add(cell); + + cell = new WordCell(); + cell.Width = ListColumnWidth[1]; + cell.Height = RowHeight; + cell.Text = "是"; + cell.ColumnSpan = 6; + Row.Add(cell); + + for (int i = 2; i < 7; i++) + { + cell = new WordCell(); + cell.Width = ListColumnWidth[i]; + cell.Height = RowHeight; + Row.Add(cell); + } + } + return Export_ListWordReport(listReport, ".pdf"); + } + #endregion + #region 复制表格测试 + public void CopyTableTest() + { + string filePath = AppDomain.CurrentDomain.BaseDirectory + "首页.docx"; + string filePath2 = AppDomain.CurrentDomain.BaseDirectory + "表格页.docx"; + var doc = new Aspose.Words.Document(filePath); + var doc2 = new Aspose.Words.Document(filePath2); + var tb = (Aspose.Words.Tables.Table)doc2.GetChild(NodeType.Table, 0, true); + var builder = new Aspose.Words.DocumentBuilder(); + builder.Document = doc; + //创建段落 + Paragraph lastParagraph = new Paragraph(doc); + //第一个表格末尾加段落 + //table.ParentNode.InsertAfter(lastParagraph, table); + //复制第一个表格 + var cloneTable = tb.Clone(true); + //在文档末尾段落后面加入复制的表格 + for (int i = 0; i < 10; i++) + { + var node = doc.ImportNode(cloneTable, true); + doc.FirstSection.Body.AppendChild(node); + } + string filePath3 = AppDomain.CurrentDomain.BaseDirectory + "新合并后的页面.docx"; + doc.Save(filePath3, SaveFormat.Docx); + + } + #endregion + + #region 导出Word + public string Export(WordReport report) + { + return Export_WordReport(report, ".doc"); + } + public string Export_WordReport(WordReport report, string SaveFileExtName) + { + Aspose.Words.Document doc = new Aspose.Words.Document(); + foreach (Section section in doc) + { + PageSetup ps = section.PageSetup; + ps.LeftMargin = report.Left;//设置或修改边距 + ps.TopMargin = report.Top;//设置或修改边距 + ps.RightMargin = report.Right;//设置或修改边距 + ps.BottomMargin = report.Bottom;//设置或修改边距 + if (report.PageType == WordPage.A3) ps.PaperSize = Aspose.Words.PaperSize.A3; + ps.Orientation = (Orientation)report.OrientationType; //纸张方向 + } + Aspose.Words.DocumentBuilder builder = new Aspose.Words.DocumentBuilder(); + //PageSetup ps = builder.PageSetup; + builder.Document = doc; + foreach (var item in report.ListTables) + { + foreach (var item2 in item.ListTexts) + { + if (item2.TextAlign == "Center") builder.ParagraphFormat.Alignment = Aspose.Words.ParagraphAlignment.Center;//水平居中对齐 + if (item2.TextAlign == "Right") builder.ParagraphFormat.Alignment = Aspose.Words.ParagraphAlignment.Right;//水平居右对齐 + if (item2.TextAlign == "Left") builder.ParagraphFormat.Alignment = Aspose.Words.ParagraphAlignment.Left;//水平居右对齐 + if (string.IsNullOrEmpty(item2.ImagePhoto) == false) + { + if (File.Exists(item2.ImagePhoto) == true) + { + builder.InsertImage(item2.ImagePhoto, item2.ImageWidth, item2.ImageHeight); + } + else + { + builder.Writeln("图片不存在:" + item2.ImagePhoto); + } + continue; + } + builder.Font.Name = item2.FontName; + builder.Font.Size = item2.FontSize; + builder.Font.Bold = item2.FontBold; + builder.Font.Color = item2.FontColor; + //builder.ParagraphFormat.Shading.BackgroundPatternColor= item2.Background; + + builder.Writeln(item2.Text); + } + item.MathMerge(); //计算合并单元格 + Aspose.Words.Tables.Table table = builder.StartTable(); + + foreach (var row in item.Rows) + { + foreach (var cell in row) + { + builder.InsertCell(); + + builder.CellFormat.Borders.LineStyle = Aspose.Words.LineStyle.Single; + builder.CellFormat.Borders.Color = System.Drawing.Color.Black; + builder.CellFormat.HorizontalMerge = (Aspose.Words.Tables.CellMerge)cell.HorizontalCellMerge; + builder.CellFormat.VerticalMerge = (Aspose.Words.Tables.CellMerge)cell.VerticalCellMerge; + //单元格背景色 + builder.CellFormat.Shading.BackgroundPatternColor = cell.Background; + if (cell.VerticalAlign == "Top") builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Top;//垂直居中对齐 + if (cell.VerticalAlign == "Center") builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;//垂直居中对齐 + if (cell.VerticalAlign == "Bottom") builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Bottom;//垂直居中对齐 + + //builder.Font.Shading.BackgroundPatternColor = Color.Red; + if (cell.TextAlign == "Center") + { + builder.ParagraphFormat.Alignment = Aspose.Words.ParagraphAlignment.Center;//水平居中对齐 + //builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;//垂直居中对齐 + } + if (cell.TextAlign == "Right") builder.ParagraphFormat.Alignment = Aspose.Words.ParagraphAlignment.Right; + if (cell.TextAlign == "Left") builder.ParagraphFormat.Alignment = Aspose.Words.ParagraphAlignment.Left; + builder.CellFormat.Width = cell.Width; + if (cell.Height > 0) builder.RowFormat.Height = cell.Height; + builder.Font.Name = cell.FontName; + builder.Font.Size = cell.FontSize; + builder.Font.Color = cell.FontColor; + builder.Font.Bold = cell.FontBold; + if (cell.Text == null) cell.Text = ""; + switch (cell.ContentType) + { + case WordCellType.None: + builder.Write(cell.Text); + break; + case WordCellType.ImagePath: + if (System.IO.File.Exists(cell.Text) == true) + { + builder.InsertImage(cell.Text, cell.ImageWidth, cell.ImageHeight); + } + else { builder.Write(""); } + break; + case WordCellType.ImageByte: + builder.InsertImage(cell.ImageBuffer, cell.ImageWidth, cell.ImageHeight); + break; + case WordCellType.Image: + builder.InsertImage(cell.ImagePhoto, cell.ImageWidth, cell.ImageHeight); + break; + default: + break; + } + } + builder.EndRow(); + } + builder.EndTable(); + + foreach (var item2 in item.ListFooterTexts) + { + if (item2.TextAlign == "Center") builder.ParagraphFormat.Alignment = Aspose.Words.ParagraphAlignment.Center;//水平居中对齐 + if (item2.TextAlign == "Right") builder.ParagraphFormat.Alignment = Aspose.Words.ParagraphAlignment.Right;//水平居右对齐 + if (item2.TextAlign == "Left") builder.ParagraphFormat.Alignment = Aspose.Words.ParagraphAlignment.Left;//水平居右对齐 + if (string.IsNullOrEmpty(item2.ImagePhoto) == false) + { + if (File.Exists(item2.ImagePhoto) == true) + { + builder.InsertImage(item2.ImagePhoto, item2.ImageWidth, item2.ImageHeight); + } + else + { + builder.Writeln("图片不存在:" + item2.ImagePhoto); + } + continue; + } + builder.Font.Name = item2.FontName; + builder.Font.Size = item2.FontSize; + builder.Font.Bold = item2.FontBold; + builder.Font.Color = item2.FontColor; + //builder.ParagraphFormat.Shading.BackgroundPatternColor= item2.Background; + builder.Writeln(item2.Text); + } + //table.AutoFit(Aspose.Words.Tables.AutoFitBehavior.FixedColumnWidths); + } + string dir = AppDomain.CurrentDomain.BaseDirectory + "ServerCookies"; + if (Directory.Exists(dir) == false) Directory.CreateDirectory(dir); + string fileName = "ServerCookies/" + Guid.NewGuid().ToString() + SaveFileExtName; + string TempFilePath = AppDomain.CurrentDomain.BaseDirectory + fileName; + switch (SaveFileExtName) + { + case ".pdf": + doc.Save(TempFilePath, SaveFormat.Pdf); + break; + case ".jpg": + doc.Save(TempFilePath, SaveFormat.Jpeg); + break; + case ".doc": + doc.Save(TempFilePath, SaveFormat.Doc); + break; + case ".docx": + doc.Save(TempFilePath, SaveFormat.Docx); + break; + default: + doc.Save(TempFilePath); + break; + } + return fileName; + } + #endregion + #region 导出Word_多页 + public string Export(List ListReport) + { + return Export_ListWordReport(ListReport, ".doc"); + } + public string Export_ListWordReport(List ListReport, string SaveFileExtName) + { + Aspose.Words.Document dstdoc = new Aspose.Words.Document(); + Aspose.Words.Document doc = null; + foreach (WordReport report in ListReport) + { + int index = ListReport.IndexOf(report); + if (index == 0) + { + doc = dstdoc; + } + else + { + doc = new Document(); + doc.FirstSection.PageSetup.SectionStart = SectionStart.NewPage; + } + Aspose.Words.DocumentBuilder builder = new Aspose.Words.DocumentBuilder(); + //PageSetup ps = builder.PageSetup; + //PageSetup ps = doc.Sections[0].PageSetup; + //ps.LeftMargin = report.Left;//设置或修改边距 + //ps.TopMargin = report.Top;//设置或修改边距 + //ps.RightMargin = report.Right;//设置或修改边距 + //ps.BottomMargin = report.Bottom;//设置或修改边距 + //ps.PaperSize = (PaperSize)report.PageType; //纸张类型 + //ps.Orientation = (Orientation)report.OrientationType; //纸张方向 + builder.Document = doc; + foreach (var item in report.ListTables) + { + foreach (var item2 in item.ListTexts) + { + if (item2.TextAlign == "Center") builder.ParagraphFormat.Alignment = Aspose.Words.ParagraphAlignment.Center;//水平居中对齐 + if (item2.TextAlign == "Right") builder.ParagraphFormat.Alignment = Aspose.Words.ParagraphAlignment.Right;//水平居右对齐 + if (item2.TextAlign == "Left") builder.ParagraphFormat.Alignment = Aspose.Words.ParagraphAlignment.Left;//水平居右对齐 + if (string.IsNullOrEmpty(item2.ImagePhoto) == false) + { + if (File.Exists(item2.ImagePhoto) == true) + { + builder.InsertImage(item2.ImagePhoto, item2.ImageWidth, item2.ImageHeight); + } + else + { + builder.Writeln("图片不存在:" + item2.ImagePhoto); + } + continue; + } + builder.Font.Name = item2.FontName; + builder.Font.Size = item2.FontSize; + builder.Font.Bold = item2.FontBold; + builder.Font.Color = item2.FontColor; + //builder.ParagraphFormat.Shading.BackgroundPatternColor= item2.Background; + builder.Writeln(item2.Text); + } + item.MathMerge(); //计算合并单元格 + Aspose.Words.Tables.Table table = builder.StartTable(); + + foreach (var row in item.Rows) + { + foreach (var cell in row) + { + builder.InsertCell(); + + builder.CellFormat.Borders.LineStyle = Aspose.Words.LineStyle.Single; + builder.CellFormat.Borders.Color = System.Drawing.Color.Black; + builder.CellFormat.HorizontalMerge = (Aspose.Words.Tables.CellMerge)cell.HorizontalCellMerge; + builder.CellFormat.VerticalMerge = (Aspose.Words.Tables.CellMerge)cell.VerticalCellMerge; + //单元格背景色 + builder.CellFormat.Shading.BackgroundPatternColor = cell.Background; + if (cell.VerticalAlign == "Top") builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Top;//垂直居中对齐 + if (cell.VerticalAlign == "Center") builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;//垂直居中对齐 + if (cell.VerticalAlign == "Bottom") builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Bottom;//垂直居中对齐 + + //builder.Font.Shading.BackgroundPatternColor = Color.Red; + if (cell.TextAlign == "Center") + { + builder.ParagraphFormat.Alignment = Aspose.Words.ParagraphAlignment.Center;//水平居中对齐 + //builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;//垂直居中对齐 + } + if (cell.TextAlign == "Right") builder.ParagraphFormat.Alignment = Aspose.Words.ParagraphAlignment.Right; + if (cell.TextAlign == "Left") builder.ParagraphFormat.Alignment = Aspose.Words.ParagraphAlignment.Left; + builder.CellFormat.Width = cell.Width; + if (cell.Height > 0) builder.RowFormat.Height = cell.Height; + builder.Font.Name = cell.FontName; + builder.Font.Size = cell.FontSize; + builder.Font.Color = cell.FontColor; + builder.Font.Bold = cell.FontBold; + if (cell.Text == null) cell.Text = ""; + switch (cell.ContentType) + { + case WordCellType.None: + builder.Write(cell.Text); + break; + case WordCellType.ImagePath: + if (System.IO.File.Exists(cell.Text) == true) + { + builder.InsertImage(cell.Text, cell.ImageWidth, cell.ImageHeight); + } + else { builder.Write(""); } + break; + case WordCellType.ImageByte: + builder.InsertImage(cell.ImageBuffer, cell.ImageWidth, cell.ImageHeight); + break; + case WordCellType.Image: + builder.InsertImage(cell.ImagePhoto, cell.ImageWidth, cell.ImageHeight); + break; + default: + break; + } + } + builder.EndRow(); + } + builder.EndTable(); + + foreach (var item2 in item.ListFooterTexts) + { + if (item2.TextAlign == "Center") builder.ParagraphFormat.Alignment = Aspose.Words.ParagraphAlignment.Center;//水平居中对齐 + if (item2.TextAlign == "Right") builder.ParagraphFormat.Alignment = Aspose.Words.ParagraphAlignment.Right;//水平居右对齐 + if (item2.TextAlign == "Left") builder.ParagraphFormat.Alignment = Aspose.Words.ParagraphAlignment.Left;//水平居右对齐 + if (string.IsNullOrEmpty(item2.ImagePhoto) == false) + { + if (File.Exists(item2.ImagePhoto) == true) + { + builder.InsertImage(item2.ImagePhoto, item2.ImageWidth, item2.ImageHeight); + } + else + { + builder.Writeln("图片不存在:" + item2.ImagePhoto); + } + continue; + } + builder.Font.Name = item2.FontName; + builder.Font.Size = item2.FontSize; + builder.Font.Bold = item2.FontBold; + builder.Font.Color = item2.FontColor; + //builder.ParagraphFormat.Shading.BackgroundPatternColor= item2.Background; + builder.Writeln(item2.Text); + } + } + if (index > 0) dstdoc.AppendDocument(doc, ImportFormatMode.KeepSourceFormatting); + } + string dir = AppDomain.CurrentDomain.BaseDirectory + "ServerCookies"; + if (Directory.Exists(dir) == false) Directory.CreateDirectory(dir); + string fileName = "ServerCookies/" + Guid.NewGuid().ToString() + SaveFileExtName; + string TempFilePath = AppDomain.CurrentDomain.BaseDirectory + fileName; + switch (SaveFileExtName) + { + case ".pdf": + dstdoc.Save(TempFilePath, SaveFormat.Pdf); + break; + case ".jpg": + dstdoc.Save(TempFilePath, SaveFormat.Jpeg); + break; + case ".doc": + dstdoc.Save(TempFilePath, SaveFormat.Doc); + break; + case ".docx": + dstdoc.Save(TempFilePath, SaveFormat.Docx); + break; + default: + dstdoc.Save(TempFilePath); + break; + } + return fileName; + } + #endregion + #region 导出Word模板替换 + public string Export(string WordTemplatePath, DataTable source, TableColumnCollection listColumns) + { + return Export(WordTemplatePath, source, listColumns, ".doc"); + } + #endregion + #region 导出Word模板替换 + public string Export(string WordTemplatePath, List ListModel, TableColumnCollection listColumns) + { + return Export(WordTemplatePath, ListModel, listColumns, ".doc"); + } + #endregion + #region 导出模板替换 + public string Export(string WordTemplatePath, DataTable source, TableColumnCollection listColumns, String SaveFileExtName) + { + if (WordTemplatePath.IndexOf(":") == -1) WordTemplatePath = AppDomain.CurrentDomain.BaseDirectory + WordTemplatePath; + Aspose.Words.Document dstdoc = new Aspose.Words.Document(WordTemplatePath); + Aspose.Words.Document doc = null; + foreach (DataRow row in source.Rows) + { + int index = source.Rows.IndexOf(row); + if (index == 0) + { + doc = dstdoc; + } + else + { + doc = new Aspose.Words.Document(WordTemplatePath); + doc.FirstSection.PageSetup.SectionStart = SectionStart.NewPage; + } + Aspose.Words.DocumentBuilder builder = new Aspose.Words.DocumentBuilder(); + builder.Document = doc; + foreach (Bookmark item in doc.Range.Bookmarks) + { + var col = listColumns.GetTableColumn(item.Name); + if (col == null) continue; + if (col.KeyValueFormat.Count > 0) + { + string v = Convert.ToString(row[item.Name]); + foreach (var Keyitem in col.KeyValueFormat) + { + if (Keyitem.Key == v) item.Text = Keyitem.Value; + } + } + else if (col.DataType == DbType.Object) + { + string[] ss = col.Format.Split('*'); + double width = Convert.ToDouble(ss[0]); + double height = Convert.ToDouble(ss[1]); + string filePath = Convert.ToString(row[item.Name]); + if (filePath.IndexOf(":") == -1) filePath = AppDomain.CurrentDomain.BaseDirectory + filePath; + //ErrorFollow.TraceWrite("导出word照片", "", filePath); + if (System.IO.File.Exists(filePath) == true) + { + builder.MoveToBookmark(item.Name); + builder.InsertImage(filePath, width, height); + } + } + else if (col.DataType == DbType.Binary) + { + string[] ss = col.Format.Split('*'); + double width = Convert.ToDouble(ss[0]); + double height = Convert.ToDouble(ss[1]); + builder.MoveToBookmark(item.Name); + builder.InsertImage((byte[])row[item.Name], width, height); + } + else if (col.DataType == DbType.Boolean) + { + string value = Convert.ToString(row[item.Name]); + bool bitValue = false; + if (string.IsNullOrEmpty(value) == false) bitValue = Convert.ToBoolean(value); + if (bitValue == true) { value = "是"; } + else { value = "否"; } + item.Text = value; + } + else if (col.Format != "") + { + item.Text = DataConvert.Format(Convert.ToString(row[item.Name]), col.Format); + } + else + { + item.Text = Convert.ToString(row[item.Name]); + } + } + if (index > 0) dstdoc.AppendDocument(doc, ImportFormatMode.KeepSourceFormatting); + } + string dir = AppDomain.CurrentDomain.BaseDirectory + "ServerCookies"; + if (Directory.Exists(dir) == false) Directory.CreateDirectory(dir); + string fileName = "ServerCookies/" + Guid.NewGuid().ToString() + SaveFileExtName; + string TempFilePath = AppDomain.CurrentDomain.BaseDirectory + fileName; + switch (SaveFileExtName) + { + case ".pdf": + dstdoc.Save(TempFilePath, SaveFormat.Pdf); + break; + case ".jpg": + dstdoc.Save(TempFilePath, SaveFormat.Jpeg); + break; + case ".doc": + dstdoc.Save(TempFilePath, SaveFormat.Doc); + break; + case ".docx": + dstdoc.Save(TempFilePath, SaveFormat.Docx); + break; + default: + dstdoc.Save(TempFilePath); + break; + } + return fileName; + } + #endregion + + #region 导出模板替换 + public string ExportImg(string WordTemplatePath, DataTable source, TableColumnCollection listColumns, String SaveFileExtName) + { + if (WordTemplatePath.IndexOf(":") == -1) WordTemplatePath = AppDomain.CurrentDomain.BaseDirectory + WordTemplatePath; + Aspose.Words.Document dstdoc = new Aspose.Words.Document(WordTemplatePath); + Aspose.Words.Document doc = null; + foreach (DataRow row in source.Rows) + { + int index = source.Rows.IndexOf(row); + if (index == 0) + { + doc = dstdoc; + } + else + { + doc = new Aspose.Words.Document(WordTemplatePath); + doc.FirstSection.PageSetup.SectionStart = SectionStart.NewPage; + } + Aspose.Words.DocumentBuilder builder = new Aspose.Words.DocumentBuilder(); + builder.Document = doc; + foreach (Bookmark item in doc.Range.Bookmarks) + { + var col = listColumns.GetTableColumn(item.Name); + if (col == null) continue; + if (col.KeyValueFormat.Count > 0) + { + string v = Convert.ToString(row[item.Name]); + foreach (var Keyitem in col.KeyValueFormat) + { + if (Keyitem.Key == v) item.Text = Keyitem.Value; + } + } + else if (col.DataType == DbType.Object) + { + // string[] ss = col.Format.Split('*'); + double width = Convert.ToDouble(row["width"]); + double height = Convert.ToDouble(row["height"]); + string filePath = Convert.ToString(row[item.Name]); + if (filePath.IndexOf(":") == -1) filePath = AppDomain.CurrentDomain.BaseDirectory + filePath; + //ErrorFollow.TraceWrite("导出word照片", "", filePath); + if (System.IO.File.Exists(filePath) == true) + { + builder.MoveToBookmark(item.Name); + builder.InsertImage(filePath, width, height); + } + } + else if (col.DataType == DbType.Binary) + { + string[] ss = col.Format.Split('*'); + double width = Convert.ToDouble(ss[0]); + double height = Convert.ToDouble(ss[1]); + builder.MoveToBookmark(item.Name); + builder.InsertImage((byte[])row[item.Name], width, height); + } + else if (col.DataType == DbType.Boolean) + { + string value = Convert.ToString(row[item.Name]); + bool bitValue = false; + if (string.IsNullOrEmpty(value) == false) bitValue = Convert.ToBoolean(value); + if (bitValue == true) { value = "是"; } + else { value = "否"; } + item.Text = value; + } + else if (col.Format != "") + { + item.Text = DataConvert.Format(Convert.ToString(row[item.Name]), col.Format); + } + else + { + item.Text = Convert.ToString(row[item.Name]); + } + } + if (index > 0) dstdoc.AppendDocument(doc, ImportFormatMode.KeepSourceFormatting); + } + string dir = AppDomain.CurrentDomain.BaseDirectory + "ServerCookies"; + if (Directory.Exists(dir) == false) Directory.CreateDirectory(dir); + string fileName = "ServerCookies/" + Guid.NewGuid().ToString() + SaveFileExtName; + string TempFilePath = AppDomain.CurrentDomain.BaseDirectory + fileName; + switch (SaveFileExtName) + { + case ".pdf": + dstdoc.Save(TempFilePath, SaveFormat.Pdf); + break; + case ".jpg": + dstdoc.Save(TempFilePath, SaveFormat.Jpeg); + break; + case ".doc": + dstdoc.Save(TempFilePath, SaveFormat.Doc); + break; + case ".docx": + dstdoc.Save(TempFilePath, SaveFormat.Docx); + break; + default: + dstdoc.Save(TempFilePath); + break; + } + return fileName; + } + #endregion + + #region 导出Word模板替换 + public string Export(string WordTemplatePath, List ListModel, TableColumnCollection listColumns, String SaveFileExtName) + { + if (WordTemplatePath.IndexOf(":") == -1) WordTemplatePath = AppDomain.CurrentDomain.BaseDirectory + WordTemplatePath; + Aspose.Words.Document dstdoc = new Aspose.Words.Document(WordTemplatePath); + Aspose.Words.Document doc = null; + Type t = typeof(T); + foreach (var row in ListModel) + { + int index = ListModel.IndexOf(row); + if (index == 0) + { + doc = dstdoc; + } + else + { + doc = new Aspose.Words.Document(WordTemplatePath); + doc.FirstSection.PageSetup.SectionStart = SectionStart.NewPage; + } + Aspose.Words.DocumentBuilder builder = new Aspose.Words.DocumentBuilder(); + builder.Document = doc; + foreach (Bookmark item in doc.Range.Bookmarks) + { + var col = listColumns.GetTableColumn(item.Name); + if (col == null) continue; + if (col.KeyValueFormat.Count > 0) + { + string v = Convert.ToString(t.GetProperty(item.Name).GetValue(row, null)); + foreach (var Keyitem in col.KeyValueFormat) + { + if (Keyitem.Key == v) item.Text = Keyitem.Value; + } + } + else if (col.DataType == DbType.Object) + { + string[] ss = col.Format.Split('*'); + double width = Convert.ToDouble(ss[0]); + double height = Convert.ToDouble(ss[1]); + string filePath = Convert.ToString(t.GetProperty(item.Name).GetValue(row, null)); + if (filePath.IndexOf(":") == -1) filePath = AppDomain.CurrentDomain.BaseDirectory + filePath; + if (System.IO.File.Exists(filePath) == true) + { + builder.MoveToBookmark(item.Name); + builder.InsertImage(filePath, width, height); + } + } + else if (col.DataType == DbType.Binary) + { + string[] ss = col.Format.Split('*'); + double width = Convert.ToDouble(ss[0]); + double height = Convert.ToDouble(ss[1]); + builder.MoveToBookmark(item.Name); + builder.InsertImage((byte[])t.GetProperty(item.Name).GetValue(row, null), width, height); + } + else if (col.DataType == DbType.Boolean) + { + string value = Convert.ToString(t.GetProperty(item.Name).GetValue(row, null)); + bool bitValue = false; + if (string.IsNullOrEmpty(value) == false) bitValue = Convert.ToBoolean(value); + if (bitValue == true) { value = "是"; } + else { value = "否"; } + item.Text = value; + } + else if (col.Format != "") + { + item.Text = DataConvert.Format(Convert.ToString(t.GetProperty(item.Name).GetValue(row, null)), col.Format); + } + else + { + item.Text = Convert.ToString(t.GetProperty(item.Name).GetValue(row, null)); + } + } + if (index > 0) dstdoc.AppendDocument(doc, ImportFormatMode.KeepSourceFormatting); + } + string dir = AppDomain.CurrentDomain.BaseDirectory + "ServerCookies"; + if (Directory.Exists(dir) == false) Directory.CreateDirectory(dir); + string fileName = "ServerCookies/" + Guid.NewGuid().ToString() + SaveFileExtName; + string TempFilePath = AppDomain.CurrentDomain.BaseDirectory + fileName; + switch (SaveFileExtName) + { + case ".pdf": + dstdoc.Save(TempFilePath, SaveFormat.Pdf); + break; + case ".jpg": + dstdoc.Save(TempFilePath, SaveFormat.Jpeg); + break; + case ".doc": + dstdoc.Save(TempFilePath, SaveFormat.Doc); + break; + case ".docx": + dstdoc.Save(TempFilePath, SaveFormat.Docx); + break; + default: + dstdoc.Save(TempFilePath); + break; + } + return fileName; + } + #endregion + #region 导出Word模板替换 + public string Export(string WordTemplatePath, List> ListModel, String SaveFileExtName) + { + if (WordTemplatePath.IndexOf(":") == -1) WordTemplatePath = AppDomain.CurrentDomain.BaseDirectory + WordTemplatePath; + Aspose.Words.Document dstdoc = new Aspose.Words.Document(WordTemplatePath); + Aspose.Words.Document doc = null; + foreach (var row in ListModel) + { + int index = ListModel.IndexOf(row); + if (index == 0) + { + doc = dstdoc; + } + else + { + doc = new Aspose.Words.Document(WordTemplatePath); + doc.FirstSection.PageSetup.SectionStart = SectionStart.NewPage; + } + Aspose.Words.DocumentBuilder builder = new Aspose.Words.DocumentBuilder(); + builder.Document = doc; + foreach (Bookmark item in doc.Range.Bookmarks) + { + var col = row.ContainsKey(item.Name); + if (col == false) continue; + string str = row[item.Name]; + if (str == null) str = ""; + item.Text = str; + } + if (index > 0) dstdoc.AppendDocument(doc, ImportFormatMode.KeepSourceFormatting); + } + string dir = AppDomain.CurrentDomain.BaseDirectory + "ServerCookies"; + if (Directory.Exists(dir) == false) Directory.CreateDirectory(dir); + string fileName = "ServerCookies/" + Guid.NewGuid().ToString() + SaveFileExtName; + string TempFilePath = AppDomain.CurrentDomain.BaseDirectory + fileName; + switch (SaveFileExtName) + { + case ".pdf": + dstdoc.Save(TempFilePath, SaveFormat.Pdf); + break; + case ".jpg": + dstdoc.Save(TempFilePath, SaveFormat.Jpeg); + break; + case ".doc": + dstdoc.Save(TempFilePath, SaveFormat.Doc); + break; + case ".docx": + dstdoc.Save(TempFilePath, SaveFormat.Docx); + break; + default: + dstdoc.Save(TempFilePath); + break; + } + return fileName; + } + #endregion + #region 导出Word模板替换 + public string Export(string WordTemplatePath, Dictionary ListModel, String SaveFileExtName) + { + if (WordTemplatePath.IndexOf(":") == -1) WordTemplatePath = AppDomain.CurrentDomain.BaseDirectory + WordTemplatePath; + Aspose.Words.Document doc = new Aspose.Words.Document(WordTemplatePath); + foreach (Bookmark item in doc.Range.Bookmarks) + { + var col = ListModel.ContainsKey(item.Name); + if (col == false) continue; + string str = ListModel[item.Name]; + if (str == null) str = ""; + item.Text = str; + } + string dir = AppDomain.CurrentDomain.BaseDirectory + "ServerCookies"; + if (Directory.Exists(dir) == false) Directory.CreateDirectory(dir); + string fileName = "ServerCookies/" + Guid.NewGuid().ToString() + SaveFileExtName; + string TempFilePath = AppDomain.CurrentDomain.BaseDirectory + fileName; + switch (SaveFileExtName) + { + case ".pdf": + doc.Save(TempFilePath, SaveFormat.Pdf); + break; + case ".jpg": + doc.Save(TempFilePath, SaveFormat.Jpeg); + break; + case ".doc": + doc.Save(TempFilePath, SaveFormat.Doc); + break; + case ".docx": + doc.Save(TempFilePath, SaveFormat.Docx); + break; + default: + doc.Save(TempFilePath); + break; + } + return fileName; + } + #endregion + #region 导出Word模板替换 + public void ExportFile(string WordTemplatePath, Dictionary ListModel, String SaveFileName) + { + if (WordTemplatePath.IndexOf(":") == -1) WordTemplatePath = AppDomain.CurrentDomain.BaseDirectory + WordTemplatePath; + Aspose.Words.Document doc = new Aspose.Words.Document(WordTemplatePath); + foreach (Bookmark item in doc.Range.Bookmarks) + { + var col = ListModel.ContainsKey(item.Name); + if (col == false) continue; + string str = ListModel[item.Name]; + if (str == null) str = ""; + item.Text = str; + } + + string fileName = SaveFileName; + string SaveFileExtName = Path.GetExtension(fileName); + switch (SaveFileExtName) + { + case ".pdf": + doc.Save(fileName, SaveFormat.Pdf); + break; + case ".jpg": + doc.Save(fileName, SaveFormat.Jpeg); + break; + case ".doc": + doc.Save(fileName, SaveFormat.Doc); + break; + case ".docx": + doc.Save(fileName, SaveFormat.Docx); + break; + default: + doc.Save(fileName); + break; + } + } + #endregion + #region 导出Word模板替换 + public string ExportFile(string WordTemplatePath, int RowCount, int StartRowIndex, int EndRowIndex, int StartCellIndex, List ListColumn, Dictionary ListModel, String SaveFileExtName) + { + if (WordTemplatePath.IndexOf(":") == -1) WordTemplatePath = AppDomain.CurrentDomain.BaseDirectory + WordTemplatePath; + var doc = GetDocument(WordTemplatePath, RowCount, StartRowIndex, EndRowIndex, StartCellIndex, ListColumn); + foreach (Bookmark item in doc.Range.Bookmarks) + { + var col = ListModel.ContainsKey(item.Name); + if (col == false) continue; + string str = ListModel[item.Name]; + if (str == null) str = ""; + item.Text = str; + } + string dir = AppDomain.CurrentDomain.BaseDirectory + "ServerCookies"; + if (Directory.Exists(dir) == false) Directory.CreateDirectory(dir); + string fileName = "ServerCookies/" + Guid.NewGuid().ToString() + SaveFileExtName; + string TempFilePath = AppDomain.CurrentDomain.BaseDirectory + fileName; + switch (SaveFileExtName) + { + case ".pdf": + doc.Save(TempFilePath, SaveFormat.Pdf); + break; + case ".jpg": + doc.Save(TempFilePath, SaveFormat.Jpeg); + break; + case ".doc": + doc.Save(TempFilePath, SaveFormat.Doc); + break; + case ".docx": + doc.Save(TempFilePath, SaveFormat.Docx); + break; + default: + doc.Save(TempFilePath); + break; + } + return fileName; + } + #endregion + #region 导出Word模板替换 + public string ExportFile(string WordTemplatePath, int TableIndex, int RowCount, int StartRowIndex, int EndRowIndex, int StartCellIndex, List ListColumn, Dictionary ListModel, String SaveFileExtName) + { + if (WordTemplatePath.IndexOf(":") == -1) WordTemplatePath = AppDomain.CurrentDomain.BaseDirectory + WordTemplatePath; + var doc = GetDocument(WordTemplatePath, TableIndex, RowCount, StartRowIndex, EndRowIndex, StartCellIndex, ListColumn); + foreach (Bookmark item in doc.Range.Bookmarks) + { + var col = ListModel.ContainsKey(item.Name); + if (col == false) continue; + string str = ListModel[item.Name]; + if (str == null) str = ""; + item.Text = str; + } + string dir = AppDomain.CurrentDomain.BaseDirectory + "ServerCookies"; + if (Directory.Exists(dir) == false) Directory.CreateDirectory(dir); + string fileName = "ServerCookies/" + Guid.NewGuid().ToString() + SaveFileExtName; + string TempFilePath = AppDomain.CurrentDomain.BaseDirectory + fileName; + switch (SaveFileExtName) + { + case ".pdf": + doc.Save(TempFilePath, SaveFormat.Pdf); + break; + case ".jpg": + doc.Save(TempFilePath, SaveFormat.Jpeg); + break; + case ".doc": + doc.Save(TempFilePath, SaveFormat.Doc); + break; + case ".docx": + doc.Save(TempFilePath, SaveFormat.Docx); + break; + default: + doc.Save(TempFilePath); + break; + } + return fileName; + } + #endregion + #region 导出Word模板替换 + public void ExportFile2(string WordTemplatePath, int TableIndex, int RowCount, int StartRowIndex, int EndRowIndex, int StartCellIndex, List ListColumn, Dictionary ListModel, String SaveFileName) + { + if (WordTemplatePath.IndexOf(":") == -1) WordTemplatePath = AppDomain.CurrentDomain.BaseDirectory + WordTemplatePath; + var doc = GetDocument(WordTemplatePath, TableIndex, RowCount, StartRowIndex, EndRowIndex, StartCellIndex, ListColumn); + foreach (Bookmark item in doc.Range.Bookmarks) + { + var col = ListModel.ContainsKey(item.Name); + if (col == false) continue; + string str = ListModel[item.Name]; + if (str == null) str = ""; + item.Text = str; + } + string SaveFileExtName = System.IO.Path.GetExtension(SaveFileName).ToLower(); + switch (SaveFileExtName) + { + case ".pdf": + doc.Save(SaveFileName, SaveFormat.Pdf); + break; + case ".jpg": + doc.Save(SaveFileName, SaveFormat.Jpeg); + break; + case ".doc": + doc.Save(SaveFileName, SaveFormat.Doc); + break; + case ".docx": + doc.Save(SaveFileName, SaveFormat.Docx); + break; + default: + doc.Save(SaveFileName); + break; + } + } + #endregion + + #region 添加空格 + public string Space(int len) + { + string ss = ""; + for (int i = 0; i < len; i++) + { + ss += " "; + } + return ss; + } + #endregion + #region 计算图片大小 + public void SetWordImageSize(Shape shape) + { + double w = shape.Width; + double h = shape.Height; + //先按固定宽度计算 + double rate = w / shape.ImageData.ImageSize.WidthPixels; //缩放比例 + double imgh = shape.ImageData.ImageSize.HeightPixels * rate; + //如果缩放后的高度超出最大高度,那么按最大高度重新计算 + if (imgh > h) + { + rate = h / shape.ImageData.ImageSize.HeightPixels; //缩放比例 + shape.Width = shape.ImageData.ImageSize.WidthPixels * rate; + } + else + { + shape.Height = imgh; + } + } + #endregion + #region 删除目录 + public void DeleteDirectory(Document doc) + { + ArrayList fieldStarts = new ArrayList(); + ArrayList nodeList = new ArrayList(); + + foreach (FieldStart start in doc.GetChildNodes(NodeType.FieldStart, true)) + { + if (start.FieldType == FieldType.FieldTOC) + { + fieldStarts.Add(start); + } + } + + bool isRemoving = true; + for (int i = 0; i < fieldStarts.Count; i++) + { + Node currentNode = (Node)fieldStarts[i]; + while (isRemoving) + { + nodeList.Add(currentNode); + currentNode = currentNode.NextPreOrder(doc); + if (currentNode.NodeType == NodeType.FieldEnd) + { + FieldEnd fieldEnd = (FieldEnd)currentNode; + if (fieldEnd.FieldType == FieldType.FieldTOC) + isRemoving = false; + } + } + foreach (Node node in nodeList) + { + node.Remove(); + } + } + } + #endregion + + #region Word打印 + public void Print(WordReport report, string PrinterName) + { + Aspose.Words.Document doc = new Aspose.Words.Document(); + Aspose.Words.DocumentBuilder builder = new Aspose.Words.DocumentBuilder(); + builder.Document = doc; + foreach (var item in report.ListTables) + { + foreach (var item2 in item.ListTexts) + { + builder.Font.Name = item2.FontName; + builder.Font.Size = item2.FontSize; + builder.Font.Bold = item2.FontBold; + builder.Font.Color = item2.FontColor; + //builder.ParagraphFormat.Shading.BackgroundPatternColor= item2.Background; + if (item2.TextAlign == "Center") builder.ParagraphFormat.Alignment = Aspose.Words.ParagraphAlignment.Center;//水平居中对齐 + if (item2.TextAlign == "Right") builder.ParagraphFormat.Alignment = Aspose.Words.ParagraphAlignment.Right;//水平居右对齐 + if (item2.TextAlign == "Left") builder.ParagraphFormat.Alignment = Aspose.Words.ParagraphAlignment.Left;//水平居右对齐 + builder.Writeln(item2.Text); + } + item.MathMerge(); //计算合并单元格 + Aspose.Words.Tables.Table table = builder.StartTable(); + + foreach (var row in item.Rows) + { + foreach (var cell in row) + { + builder.InsertCell(); + + builder.CellFormat.Borders.LineStyle = Aspose.Words.LineStyle.Single; + builder.CellFormat.Borders.Color = System.Drawing.Color.Black; + builder.CellFormat.HorizontalMerge = (Aspose.Words.Tables.CellMerge)cell.HorizontalCellMerge; + builder.CellFormat.VerticalMerge = (Aspose.Words.Tables.CellMerge)cell.VerticalCellMerge; + //单元格背景色 + builder.CellFormat.Shading.BackgroundPatternColor = cell.Background; + if (cell.VerticalAlign == "Top") builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Top;//垂直居中对齐 + if (cell.VerticalAlign == "Center") builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;//垂直居中对齐 + if (cell.VerticalAlign == "Bottom") builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Bottom;//垂直居中对齐 + + //builder.Font.Shading.BackgroundPatternColor = Color.Red; + if (cell.TextAlign == "Center") + { + builder.ParagraphFormat.Alignment = Aspose.Words.ParagraphAlignment.Center;//水平居中对齐 + //builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;//垂直居中对齐 + } + if (cell.TextAlign == "Right") builder.ParagraphFormat.Alignment = Aspose.Words.ParagraphAlignment.Right; + if (cell.TextAlign == "Left") builder.ParagraphFormat.Alignment = Aspose.Words.ParagraphAlignment.Left; + builder.CellFormat.Width = cell.Width; + if (cell.Height > 0) builder.RowFormat.Height = cell.Height; + builder.Font.Name = cell.FontName; + builder.Font.Size = cell.FontSize; + builder.Font.Color = cell.FontColor; + builder.Font.Bold = cell.FontBold; + if (cell.Text == null) cell.Text = ""; + switch (cell.ContentType) + { + case WordCellType.None: + builder.Write(cell.Text); + break; + case WordCellType.ImagePath: + if (System.IO.File.Exists(cell.Text) == true) + { + builder.InsertImage(cell.Text, cell.ImageWidth, cell.ImageHeight); + } + else { builder.Write(""); } + break; + case WordCellType.ImageByte: + builder.InsertImage(cell.ImageBuffer, cell.ImageWidth, cell.ImageHeight); + break; + case WordCellType.Image: + builder.InsertImage(cell.ImagePhoto, cell.ImageWidth, cell.ImageHeight); + break; + default: + break; + } + } + builder.EndRow(); + } + builder.EndTable(); + + foreach (var item2 in item.ListFooterTexts) + { + + builder.Font.Name = item2.FontName; + builder.Font.Size = item2.FontSize; + builder.Font.Bold = item2.FontBold; + builder.Font.Color = item2.FontColor; + //builder.ParagraphFormat.Shading.BackgroundPatternColor= item2.Background; + if (item2.TextAlign == "Center") builder.ParagraphFormat.Alignment = Aspose.Words.ParagraphAlignment.Center;//水平居中对齐 + if (item2.TextAlign == "Right") builder.ParagraphFormat.Alignment = Aspose.Words.ParagraphAlignment.Right;//水平居右对齐 + if (item2.TextAlign == "Left") builder.ParagraphFormat.Alignment = Aspose.Words.ParagraphAlignment.Left;//水平居右对齐 + builder.Writeln(item2.Text); + } + //table.AutoFit(Aspose.Words.Tables.AutoFitBehavior.FixedColumnWidths); + } + //string fileName = "ServerCookies/" + Guid.NewGuid().ToString() + ".doc"; + //string TempFilePath = AppDomain.CurrentDomain.BaseDirectory + fileName; + //doc.Save(TempFilePath); + + if (string.IsNullOrEmpty(PrinterName) == true) { doc.Print(); } + else { doc.Print(PrinterName); } + } + #endregion + #region Word打印_多页 + public void Export(List ListReport, string PrinterName) + { + Aspose.Words.Document dstdoc = new Aspose.Words.Document(); + Aspose.Words.Document doc = null; + foreach (WordReport report in ListReport) + { + int index = ListReport.IndexOf(report); + if (index == 0) + { + doc = dstdoc; + } + else + { + doc = new Document(); + doc.FirstSection.PageSetup.SectionStart = SectionStart.NewPage; + } + Aspose.Words.DocumentBuilder builder = new Aspose.Words.DocumentBuilder(); + builder.Document = doc; + foreach (var item in report.ListTables) + { + foreach (var item2 in item.ListTexts) + { + builder.Font.Name = item2.FontName; + builder.Font.Size = item2.FontSize; + builder.Font.Bold = item2.FontBold; + builder.Font.Color = item2.FontColor; + //builder.ParagraphFormat.Shading.BackgroundPatternColor= item2.Background; + if (item2.TextAlign == "Center") builder.ParagraphFormat.Alignment = Aspose.Words.ParagraphAlignment.Center;//水平居中对齐 + if (item2.TextAlign == "Right") builder.ParagraphFormat.Alignment = Aspose.Words.ParagraphAlignment.Right;//水平居右对齐 + if (item2.TextAlign == "Left") builder.ParagraphFormat.Alignment = Aspose.Words.ParagraphAlignment.Left;//水平居右对齐 + builder.Writeln(item2.Text); + } + item.MathMerge(); //计算合并单元格 + Aspose.Words.Tables.Table table = builder.StartTable(); + + foreach (var row in item.Rows) + { + foreach (var cell in row) + { + builder.InsertCell(); + + builder.CellFormat.Borders.LineStyle = Aspose.Words.LineStyle.Single; + builder.CellFormat.Borders.Color = System.Drawing.Color.Black; + builder.CellFormat.HorizontalMerge = (Aspose.Words.Tables.CellMerge)cell.HorizontalCellMerge; + builder.CellFormat.VerticalMerge = (Aspose.Words.Tables.CellMerge)cell.VerticalCellMerge; + //单元格背景色 + builder.CellFormat.Shading.BackgroundPatternColor = cell.Background; + if (cell.VerticalAlign == "Top") builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Top;//垂直居中对齐 + if (cell.VerticalAlign == "Center") builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;//垂直居中对齐 + if (cell.VerticalAlign == "Bottom") builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Bottom;//垂直居中对齐 + + //builder.Font.Shading.BackgroundPatternColor = Color.Red; + if (cell.TextAlign == "Center") + { + builder.ParagraphFormat.Alignment = Aspose.Words.ParagraphAlignment.Center;//水平居中对齐 + //builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;//垂直居中对齐 + } + if (cell.TextAlign == "Right") builder.ParagraphFormat.Alignment = Aspose.Words.ParagraphAlignment.Right; + if (cell.TextAlign == "Left") builder.ParagraphFormat.Alignment = Aspose.Words.ParagraphAlignment.Left; + builder.CellFormat.Width = cell.Width; + if (cell.Height > 0) builder.RowFormat.Height = cell.Height; + builder.Font.Name = cell.FontName; + builder.Font.Size = cell.FontSize; + builder.Font.Color = cell.FontColor; + builder.Font.Bold = cell.FontBold; + if (cell.Text == null) cell.Text = ""; + switch (cell.ContentType) + { + case WordCellType.None: + builder.Write(cell.Text); + break; + case WordCellType.ImagePath: + if (System.IO.File.Exists(cell.Text) == true) + { + builder.InsertImage(cell.Text, cell.ImageWidth, cell.ImageHeight); + } + else { builder.Write(""); } + break; + case WordCellType.ImageByte: + builder.InsertImage(cell.ImageBuffer, cell.ImageWidth, cell.ImageHeight); + break; + case WordCellType.Image: + builder.InsertImage(cell.ImagePhoto, cell.ImageWidth, cell.ImageHeight); + break; + default: + break; + } + } + builder.EndRow(); + } + builder.EndTable(); + + foreach (var item2 in item.ListFooterTexts) + { + builder.Font.Name = item2.FontName; + builder.Font.Size = item2.FontSize; + builder.Font.Bold = item2.FontBold; + builder.Font.Color = item2.FontColor; + //builder.ParagraphFormat.Shading.BackgroundPatternColor= item2.Background; + if (item2.TextAlign == "Center") builder.ParagraphFormat.Alignment = Aspose.Words.ParagraphAlignment.Center;//水平居中对齐 + if (item2.TextAlign == "Right") builder.ParagraphFormat.Alignment = Aspose.Words.ParagraphAlignment.Right;//水平居右对齐 + if (item2.TextAlign == "Left") builder.ParagraphFormat.Alignment = Aspose.Words.ParagraphAlignment.Left;//水平居右对齐 + builder.Writeln(item2.Text); + } + } + if (index > 0) dstdoc.AppendDocument(doc, ImportFormatMode.KeepSourceFormatting); + } + if (string.IsNullOrEmpty(PrinterName) == true) { dstdoc.Print(); } + else { dstdoc.Print(PrinterName); } + //string fileName = "ServerCookies/" + Guid.NewGuid().ToString() + ".doc"; + //string TempFilePath = AppDomain.CurrentDomain.BaseDirectory + fileName; + //dstdoc.Save(TempFilePath); + //return fileName; + } + #endregion + #region Word打印模板替换 + public void Print(string WordTemplatePath, DataTable source, TableColumnCollection listColumns, string PrinterName) + { + if (WordTemplatePath.IndexOf(":") == -1) WordTemplatePath = AppDomain.CurrentDomain.BaseDirectory + WordTemplatePath; + Aspose.Words.Document dstdoc = new Aspose.Words.Document(WordTemplatePath); + Aspose.Words.Document doc = null; + foreach (DataRow row in source.Rows) + { + int index = source.Rows.IndexOf(row); + if (index == 0) + { + doc = dstdoc; + } + else + { + doc = new Aspose.Words.Document(WordTemplatePath); + doc.FirstSection.PageSetup.SectionStart = SectionStart.NewPage; + } + Aspose.Words.DocumentBuilder builder = new Aspose.Words.DocumentBuilder(); + builder.Document = doc; + foreach (Bookmark item in doc.Range.Bookmarks) + { + var col = listColumns.GetTableColumn(item.Name); + if (col == null) continue; + if (col.KeyValueFormat.Count > 0) + { + string v = Convert.ToString(row[item.Name]); + foreach (var Keyitem in col.KeyValueFormat) + { + if (Keyitem.Key == v) item.Text = Keyitem.Value; + } + } + else if (col.DataType == DbType.Object) + { + string[] ss = col.Format.Split('*'); + double width = Convert.ToDouble(ss[0]); + double height = Convert.ToDouble(ss[1]); + string filePath = Convert.ToString(row[item.Name]); + if (filePath.IndexOf(":") == -1) filePath = AppDomain.CurrentDomain.BaseDirectory + filePath; + //ErrorFollow.TraceWrite("导出word照片", "", filePath); + if (System.IO.File.Exists(filePath) == true) + { + builder.MoveToBookmark(item.Name); + builder.InsertImage(filePath, width, height); + } + } + else if (col.DataType == DbType.Binary) + { + string[] ss = col.Format.Split('*'); + double width = Convert.ToDouble(ss[0]); + double height = Convert.ToDouble(ss[1]); + builder.MoveToBookmark(item.Name); + builder.InsertImage((byte[])row[item.Name], width, height); + } + else if (col.DataType == DbType.Boolean) + { + string value = Convert.ToString(row[item.Name]); + bool bitValue = false; + if (string.IsNullOrEmpty(value) == false) bitValue = Convert.ToBoolean(value); + if (bitValue == true) { value = "是"; } + else { value = "否"; } + item.Text = value; + } + else if (col.Format != "") + { + item.Text = DataConvert.Format(Convert.ToString(row[item.Name]), col.Format); + } + else + { + item.Text = Convert.ToString(row[item.Name]); + } + } + if (index > 0) dstdoc.AppendDocument(doc, ImportFormatMode.KeepSourceFormatting); + } + if (string.IsNullOrEmpty(PrinterName) == true) { doc.Print(); } + else { doc.Print(PrinterName); } + //string fileName = "ServerCookies/" + Guid.NewGuid().ToString() + ".doc"; + //string TempFilePath = AppDomain.CurrentDomain.BaseDirectory + fileName; + //dstdoc.Save(TempFilePath); + //return fileName; + } + #endregion + #region Word打印模板替换 + public void Print(string WordTemplatePath, List ListModel, TableColumnCollection listColumns, string PrinterName) + { + if (WordTemplatePath.IndexOf(":") == -1) WordTemplatePath = AppDomain.CurrentDomain.BaseDirectory + WordTemplatePath; + Aspose.Words.Document dstdoc = new Aspose.Words.Document(WordTemplatePath); + //PageSetup ps = builder.PageSetup; + //PageSetup ps = doc.Sections[0].PageSetup; + //ps.LeftMargin = report.Left;//设置或修改边距 + //ps.TopMargin = report.Top;//设置或修改边距 + //ps.RightMargin = report.Right;//设置或修改边距 + //ps.BottomMargin = report.Bottom;//设置或修改边距 + //ps.PaperSize = (PaperSize)report.PageType; //纸张类型 + //ps.Orientation = (Orientation)report.OrientationType; //纸张方向 + Aspose.Words.Document doc = null; + Type t = typeof(T); + foreach (var row in ListModel) + { + int index = ListModel.IndexOf(row); + if (index == 0) + { + doc = dstdoc; + //PageSetup ps = doc.Sections[0].PageSetup; + //ps.LeftMargin = report.Left;//设置或修改边距 + //ps.TopMargin = report.Top;//设置或修改边距 + //ps.RightMargin = report.Right;//设置或修改边距 + //ps.BottomMargin = report.Bottom;//设置或修改边距 + //ps.PaperSize = PaperSize.Custom; //纸张类型 + + //ps.Orientation = (Orientation)report.OrientationType; //纸张方向 + //ps.PageWidth = 9.8; + //ps.PageHeight = 21; + } + else + { + doc = new Aspose.Words.Document(WordTemplatePath); + doc.FirstSection.PageSetup.SectionStart = SectionStart.NewPage; + } + Aspose.Words.DocumentBuilder builder = new Aspose.Words.DocumentBuilder(); + + builder.Document = doc; + foreach (Bookmark item in doc.Range.Bookmarks) + { + var col = listColumns.GetTableColumn(item.Name); + if (col == null) continue; + if (col.KeyValueFormat.Count > 0) + { + string v = Convert.ToString(t.GetProperty(item.Name).GetValue(row, null)); + foreach (var Keyitem in col.KeyValueFormat) + { + if (Keyitem.Key == v) item.Text = Keyitem.Value; + } + } + else if (col.DataType == DbType.Object) + { + string[] ss = col.Format.Split('*'); + double width = Convert.ToDouble(ss[0]); + double height = Convert.ToDouble(ss[1]); + string filePath = Convert.ToString(t.GetProperty(item.Name).GetValue(row, null)); + if (filePath.IndexOf(":") == -1) filePath = AppDomain.CurrentDomain.BaseDirectory + filePath; + if (System.IO.File.Exists(filePath) == true) + { + builder.MoveToBookmark(item.Name); + builder.InsertImage(filePath, width, height); + } + } + else if (col.DataType == DbType.Binary) + { + string[] ss = col.Format.Split('*'); + double width = Convert.ToDouble(ss[0]); + double height = Convert.ToDouble(ss[1]); + builder.MoveToBookmark(item.Name); + builder.InsertImage((byte[])t.GetProperty(item.Name).GetValue(row, null), width, height); + } + else if (col.DataType == DbType.Boolean) + { + string value = Convert.ToString(t.GetProperty(item.Name).GetValue(row, null)); + bool bitValue = false; + if (string.IsNullOrEmpty(value) == false) bitValue = Convert.ToBoolean(value); + if (bitValue == true) { value = "是"; } + else { value = "否"; } + item.Text = value; + } + else if (col.Format != "") + { + item.Text = DataConvert.Format(Convert.ToString(t.GetProperty(item.Name).GetValue(row, null)), col.Format); + } + else + { + item.Text = Convert.ToString(t.GetProperty(item.Name).GetValue(row, null)); + } + } + if (index > 0) dstdoc.AppendDocument(doc, ImportFormatMode.KeepSourceFormatting); + } + //string fileName = "ServerCookies/" + Guid.NewGuid().ToString() + ".pdf"; + //string TempFilePath = AppDomain.CurrentDomain.BaseDirectory + fileName; + //dstdoc.Save(TempFilePath, SaveFormat.Pdf); + //return fileName; + + if (string.IsNullOrEmpty(PrinterName) == true) { doc.Print(); } + else { doc.Print(PrinterName); } + } + #endregion + #region Word打印模板替换 + public void Print(string WordTemplatePath, T Model, TableColumnCollection listColumns, string PrinterName) + { + if (WordTemplatePath.IndexOf(":") == -1) WordTemplatePath = AppDomain.CurrentDomain.BaseDirectory + WordTemplatePath; + Aspose.Words.Document doc = new Aspose.Words.Document(WordTemplatePath); + Type t = typeof(T); + Aspose.Words.DocumentBuilder builder = new Aspose.Words.DocumentBuilder(); + builder.Document = doc; + foreach (Bookmark item in doc.Range.Bookmarks) + { + var col = listColumns.GetTableColumn(item.Name); + if (col == null) continue; + if (col.KeyValueFormat.Count > 0) + { + string v = Convert.ToString(t.GetProperty(item.Name).GetValue(Model, null)); + foreach (var Keyitem in col.KeyValueFormat) + { + if (Keyitem.Key == v) item.Text = Keyitem.Value; + } + } + else if (col.DataType == DbType.Object) + { + string[] ss = col.Format.Split('*'); + double width = Convert.ToDouble(ss[0]); + double height = Convert.ToDouble(ss[1]); + string filePath = Convert.ToString(t.GetProperty(item.Name).GetValue(Model, null)); + if (filePath.IndexOf(":") == -1) filePath = AppDomain.CurrentDomain.BaseDirectory + filePath; + if (System.IO.File.Exists(filePath) == true) + { + builder.MoveToBookmark(item.Name); + builder.InsertImage(filePath, width, height); + } + } + else if (col.DataType == DbType.Binary) + { + string[] ss = col.Format.Split('*'); + double width = Convert.ToDouble(ss[0]); + double height = Convert.ToDouble(ss[1]); + builder.MoveToBookmark(item.Name); + builder.InsertImage((byte[])t.GetProperty(item.Name).GetValue(Model, null), width, height); + } + else if (col.DataType == DbType.Boolean) + { + string value = Convert.ToString(t.GetProperty(item.Name).GetValue(Model, null)); + bool bitValue = false; + if (string.IsNullOrEmpty(value) == false) bitValue = Convert.ToBoolean(value); + if (bitValue == true) { value = "是"; } + else { value = "否"; } + item.Text = value; + } + else if (col.Format != "") + { + item.Text = DataConvert.Format(Convert.ToString(t.GetProperty(item.Name).GetValue(Model, null)), col.Format); + } + else + { + item.Text = Convert.ToString(t.GetProperty(item.Name).GetValue(Model, null)); + } + } + if (string.IsNullOrEmpty(PrinterName) == true) { doc.Print(); } + else { doc.Print(PrinterName); } + } + #endregion + + #region Word模板替换并且返回 + public Aspose.Words.Document GetDocument(string WordTemplatePath, Dictionary ListModel) + { + if (WordTemplatePath.IndexOf(":") == -1) WordTemplatePath = AppDomain.CurrentDomain.BaseDirectory + WordTemplatePath; + Aspose.Words.Document doc = new Aspose.Words.Document(WordTemplatePath); + //Aspose.Words.DocumentBuilder builder = new Aspose.Words.DocumentBuilder(); + //builder.Document = doc; + //builder.Font.Size = 5; + //builder.Font.SizeBi = 5; + //builder.Font.Bold = true; + foreach (Bookmark item in doc.Range.Bookmarks) + { + var col = ListModel.ContainsKey(item.Name); + if (col == false) continue; + var str = ListModel[item.Name]; + if (str == null) str = ""; + item.Text = str; + } + return doc; + } + #endregion + #region Word模板替换并且返回 + public Aspose.Words.Document GetDocument(string WordTemplatePath, Dictionary ListModel) + { + if (WordTemplatePath.IndexOf(":") == -1) WordTemplatePath = AppDomain.CurrentDomain.BaseDirectory + WordTemplatePath; + Aspose.Words.Document doc = new Aspose.Words.Document(WordTemplatePath); + Aspose.Words.DocumentBuilder builder = new Aspose.Words.DocumentBuilder(); + builder.Document = doc; + foreach (Bookmark item in doc.Range.Bookmarks) + { + var col = ListModel.ContainsKey(item.Name); + if (col == false) continue; + var model = ListModel[item.Name]; + string str = model.Text; + if (model.Text == null) str = ""; + builder.MoveToBookmark(item.Name); + if (model.FontSize > 0) builder.Font.Size = model.FontSize; + builder.Font.Bold = model.FontBold; + builder.Write(str); + } + return doc; + } + #endregion + + #region Word模板替换并且返回 + public Aspose.Words.Document GetDocument(string WordTemplatePath, int RowCount, int StartRowIndex, int EndRowIndex, int StartCellIndex, List ListColumn, Dictionary ListModel) + { + if (WordTemplatePath.IndexOf(":") == -1) WordTemplatePath = AppDomain.CurrentDomain.BaseDirectory + WordTemplatePath; + var doc = GetDocument(WordTemplatePath, RowCount, StartRowIndex, EndRowIndex, StartCellIndex, ListColumn); + foreach (Bookmark item in doc.Range.Bookmarks) + { + var col = ListModel.ContainsKey(item.Name); + if (col == false) continue; + var str = ListModel[item.Name]; + if (str == null) str = ""; + item.Text = str; + } + return doc; + } + #endregion + #region Word模板替换并且返回 + public Aspose.Words.Document GetDocument(string WordTemplatePath, int TableIndex, int RowCount, int StartRowIndex, int EndRowIndex, int StartCellIndex, List ListColumn, Dictionary ListModel) + { + if (WordTemplatePath.IndexOf(":") == -1) WordTemplatePath = AppDomain.CurrentDomain.BaseDirectory + WordTemplatePath; + var doc = GetDocument(WordTemplatePath, TableIndex, RowCount, StartRowIndex, EndRowIndex, StartCellIndex, ListColumn); + foreach (Bookmark item in doc.Range.Bookmarks) + { + var col = ListModel.ContainsKey(item.Name); + if (col == false) continue; + var str = ListModel[item.Name]; + if (str == null) str = ""; + item.Text = str; + } + return doc; + } + #endregion + #region Word模板替换并且返回 + public Aspose.Words.Document GetDocument(string WordTemplatePath, int RowCount, int StartRowIndex, int EndRowIndex, int StartCellIndex, List ListColumn, Dictionary ListModel) + { + if (WordTemplatePath.IndexOf(":") == -1) WordTemplatePath = AppDomain.CurrentDomain.BaseDirectory + WordTemplatePath; + var doc = GetDocument(WordTemplatePath, RowCount, StartRowIndex, EndRowIndex, StartCellIndex, ListColumn); + var builder = new Aspose.Words.DocumentBuilder(doc); + foreach (Bookmark item in doc.Range.Bookmarks) + { + var col = ListModel.ContainsKey(item.Name); + if (col == false) continue; + var model = ListModel[item.Name]; + string str = model.Text; + if (model.Text == null) str = ""; + builder.MoveToBookmark(item.Name); + if (model.FontSize > 0) builder.Font.Size = model.FontSize; + builder.Font.Bold = model.FontBold; + builder.Write(str); + } + return doc; + } + #endregion + + #region Word模板替换表格内容并且返回 + public Aspose.Words.Document GetDocument(string WordTemplatePath, int RowCount, int StartRowIndex, int EndRowIndex, int StartCellIndex, List ListColumn) + { + if (WordTemplatePath.IndexOf(":") == -1) WordTemplatePath = AppDomain.CurrentDomain.BaseDirectory + WordTemplatePath; + Aspose.Words.Document doc = new Aspose.Words.Document(WordTemplatePath); + NodeCollection allTables = doc.GetChildNodes(NodeType.Table, true); + Aspose.Words.Tables.Table table = allTables[0] as Aspose.Words.Tables.Table;//拿到第一个表格 + int num = RowCount - EndRowIndex + (StartRowIndex - 1); //计算出一共需要复制多少行 + if (num > 0) + { + for (int i = 0; i < num; i++) + { + var roww = table.Rows[EndRowIndex]; + var row = roww.Clone(true);//复制行 + table.Rows.Insert(EndRowIndex, row);//将复制的行插入当前行的上方 + } + } + + var builder = new Aspose.Words.DocumentBuilder(doc); + for (int i = StartCellIndex; i < ListColumn.Count + StartCellIndex; i++) + { + string ColName = ListColumn[i - StartCellIndex]; + for (int j = StartRowIndex; j < RowCount + StartRowIndex; j++) + { + builder.MoveToCell(0, j, i, 0); + string strBookMarkName = ColName + (j - StartRowIndex); + builder.StartBookmark(strBookMarkName); + builder.EndBookmark(strBookMarkName); + } + } + return doc; + } + #endregion + #region Word模板替换表格内容并且返回 + public Aspose.Words.Document GetDocument(string WordTemplatePath, int TableIndex, int RowCount, int StartRowIndex, int EndRowIndex, int StartCellIndex, List ListColumn) + { + if (WordTemplatePath.IndexOf(":") == -1) WordTemplatePath = AppDomain.CurrentDomain.BaseDirectory + WordTemplatePath; + Aspose.Words.Document doc = new Aspose.Words.Document(WordTemplatePath); + NodeCollection allTables = doc.GetChildNodes(NodeType.Table, true); + Aspose.Words.Tables.Table table = allTables[TableIndex] as Aspose.Words.Tables.Table;//拿到第一个表格 + int num = RowCount - EndRowIndex + (StartRowIndex - 1); //计算出一共需要复制多少行 + if (num > 0) + { + for (int i = 0; i < num; i++) + { + var roww = table.Rows[EndRowIndex]; + var row = roww.Clone(true);//复制行 + table.Rows.Insert(EndRowIndex, row);//将复制的行插入当前行的上方 + } + } + + var builder = new Aspose.Words.DocumentBuilder(doc); + for (int i = StartCellIndex; i < ListColumn.Count + StartCellIndex; i++) + { + string ColName = ListColumn[i - StartCellIndex]; + for (int j = StartRowIndex; j < RowCount + StartRowIndex; j++) + { + builder.MoveToCell(0, j, i, 0); + string strBookMarkName = ColName + (j - StartRowIndex); + builder.StartBookmark(strBookMarkName); + builder.EndBookmark(strBookMarkName); + } + } + return doc; + } + #endregion + + #region 导出图片 + public void ExportImage(string filePath, string ExportDir) + { + if (System.IO.Directory.Exists(ExportDir) == false) System.IO.Directory.CreateDirectory(ExportDir); + var doc = new Aspose.Words.Document(filePath); + ImageSaveOptions iso = new ImageSaveOptions(SaveFormat.Png); + iso.Resolution = 128; + iso.PrettyFormat = true; + iso.UseAntiAliasing = true; + for (var i = 0; i < doc.PageCount; i++) + { + iso.PageIndex = i; + string imgName = ExportDir + "/" + (i + 1) + ".png"; + //doc文件保存成图片至本地 + doc.Save(imgName, iso); + } + } + #endregion + + #region 保存 + public string SaveFile(Aspose.Words.Document doc, string SaveFileExtName) + { + string dir = AppDomain.CurrentDomain.BaseDirectory + "ServerCookies"; + if (Directory.Exists(dir) == false) Directory.CreateDirectory(dir); + string fileName = "ServerCookies/" + Guid.NewGuid().ToString() + SaveFileExtName; + string TempFilePath = AppDomain.CurrentDomain.BaseDirectory + fileName; + switch (SaveFileExtName) + { + case ".pdf": + doc.Save(TempFilePath, SaveFormat.Pdf); + break; + case ".jpg": + doc.Save(TempFilePath, SaveFormat.Jpeg); + break; + case ".doc": + doc.Save(TempFilePath, SaveFormat.Doc); + break; + case ".docx": + doc.Save(TempFilePath, SaveFormat.Docx); + break; + default: + doc.Save(TempFilePath); + break; + } + return fileName; + } + #endregion + } + + #region Word报表 + public class WordReport + { + public double Left { get; set; } + public double Top { get; set; } + public double Right { get; set; } + public double Bottom { get; set; } + public WordPage PageType { get; set; } + public WordPageOrientation OrientationType { get; set; } + public List ListTables { get; set; } + public WordReport() + { + ListTables = new List(); + PageType = WordPage.A4; + OrientationType = WordPageOrientation.Portrait; + Top = 10; + Left = 10; + Right = 10; + Bottom = 10; + } + } + #endregion + #region Word表格 + public class WordTable + { + public List> Rows { get; set; } + public List ListTexts { get; set; } + public List ListFooterTexts { get; set; } + public WordTable() + { + Rows = new List>(); + ListTexts = new List(); + ListFooterTexts = new List(); + } + + #region 计算单元格合并 + public void MathMerge() + { + foreach (List row in this.Rows) + { + int rowIndex = this.Rows.IndexOf(row); + for (int i = 0; i < row.Count; i++) + { + WordCell cell = row[i]; + if (cell.RowSpan > 1) + { //如果跨行数等于>1,那么添加,计算本单元格所需高度 + cell.VerticalCellMerge = 1; + for (int ii = 1; ii < cell.RowSpan; ii++) + { + this.Rows[rowIndex + ii][i].VerticalCellMerge = 2; + } + } + if (cell.ColumnSpan > 1) + { //如果跨列数大于1,那么计算本单元格所需宽度 + cell.HorizontalCellMerge = 1; + for (int ii = 1; ii < cell.ColumnSpan; ii++) + { + row[i + ii].HorizontalCellMerge = 2; + //cell.Width += row[i + ii].Width; + } + } + //如果不是第一行,并且左边与上边的单元格属性为隐藏,那么隐藏单元格 + if (rowIndex > 0 && i > 0) + { + if (row[i - 1].HorizontalCellMerge > 0 && this.Rows[rowIndex - 1][i].VerticalCellMerge > 0) + { + if (row[i - 1].VerticalCellMerge == 2) cell.HorizontalCellMerge = 2; + cell.VerticalCellMerge = 2; + } + } + } + } + } + #endregion + + #region 增加空格 + public void AddCell(List Row) + { + WordCell cell = new WordCell(); + //cell.Width = Width; , double Width + cell.Text = ""; + cell.ColumnSpan = 1; + //cell.Background = Color.AliceBlue; + Row.Add(cell); + } + #endregion + #region 增加空格 + public void AddCells(List Row, int Num) + { + for (int i = 0; i < Num; i++) + { + AddCell(Row); + } + } + #endregion + } + #endregion + #region Word单元格 + public class WordCell + { + public double Width { get; set; } + public double Height { get; set; } + public double ImageWidth { get; set; } + public double ImageHeight { get; set; } + public byte[] ImageBuffer { get; set; } + public Image ImagePhoto { get; set; } + public int ColumnSpan { get; set; } + public int RowSpan { get; set; } + public string Text { get; set; } + public WordCellType ContentType { get; set; } + public string FontName { get; set; } + public double FontSize { get; set; } + public bool FontBold { get; set; } + public string TextAlign { get; set; } + public string VerticalAlign { get; set; } + public Color FontColor { get; set; } + public Color Background { get; set; } + public int HorizontalCellMerge { get; set; } + public int VerticalCellMerge { get; set; } + + public WordCell() + { + ContentType = WordCellType.None; + FontName = "宋体"; + FontSize = 9; + FontColor = Color.Black; + TextAlign = "Center"; + VerticalAlign = "Center"; //Bottom,Top,Center + Text = ""; + + } + } + #endregion + #region Word单元格类型 + public enum WordCellType + { + None, + ImagePath, + ImageByte, + Image + } + #endregion + #region Word纸张 + public enum WordPage + { + /// + /// 宽595*高848 + /// + A4 = 1, + A3 = 0 + } + #endregion + #region Word纸张方向 + public enum WordPageOrientation + { + Portrait = 1, + Landscape = 2 + } + #endregion + #region Word行字符串 + public class WordText + { + public string Text { get; set; } + public string FontName { get; set; } + public double FontSize { get; set; } + public bool FontBold { get; set; } + public Color FontColor { get; set; } + public string TextAlign { get; set; } + public Color Background { get; set; } + public string ImagePhoto { get; set; } + public double ImageWidth { get; set; } + public double ImageHeight { get; set; } + + public WordText() + { + FontName = "宋体"; + FontSize = 0;//等于小五 + FontColor = Color.Black; + Background = Color.White; + TextAlign = "Center"; + Text = ""; + } + public WordText(string Text) + { + this.Text = Text; + } + public WordText(string ImagePhoto, double ImageWidth, double ImageHeight) + { + TextAlign = "Center"; + this.ImagePhoto = ImagePhoto; + this.ImageWidth = ImageWidth; + this.ImageHeight = ImageHeight; + } + + public WordText(string ImagePhoto, double ImageWidth, double ImageHeight, string TextAlign) + { + this.TextAlign = TextAlign; + this.ImagePhoto = ImagePhoto; + this.ImageWidth = ImageWidth; + this.ImageHeight = ImageHeight; + } + + public WordText(string Text, double FontSize, string TextAlign) + { + this.Text = Text; + this.FontSize = FontSize; + this.TextAlign = TextAlign; + FontName = "宋体"; + FontColor = Color.Black; + Background = Color.White; + } + public WordText(string Text, double FontSize, string TextAlign, bool FontBold) + { + this.Text = Text; + this.FontSize = FontSize; + this.TextAlign = TextAlign; + FontName = "宋体"; + FontColor = Color.Black; + Background = Color.White; + this.FontBold = FontBold; + } + } + #endregion + + + + +} + + + + + + + diff --git a/基础类库/HuizhongLibrary/Models/JavaDataTable.cs b/基础类库/HuizhongLibrary/Models/JavaDataTable.cs new file mode 100644 index 0000000..4f15b04 --- /dev/null +++ b/基础类库/HuizhongLibrary/Models/JavaDataTable.cs @@ -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 + { + 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 ItemArray { get; set; } + public JavaDataTableRow() + { + ItemArray = new List(); + } + } + + public class JavaDataTableRows : List + { + + } + #endregion +} diff --git a/基础类库/HuizhongLibrary/Models/JsonModel.cs b/基础类库/HuizhongLibrary/Models/JsonModel.cs new file mode 100644 index 0000000..8e1a906 --- /dev/null +++ b/基础类库/HuizhongLibrary/Models/JsonModel.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace HuizhongLibrary.Data +{ + /// + /// JSON对象 + /// + /// + public class JsonModel + { + /// + /// 数据集 + /// + public T DataSource { get; set; } + public T DataSource2 { get; set; } + /// + /// 行数量 + /// + public int RowCount { get; set; } + public int RowCount2 { get; set; } + /// + /// 错误信息 + /// + public string ErrorMsg { get; set; } + + public int allnum { get; set; } + public JsonModel() + { + RowCount = 0; + ErrorMsg = ""; + } + } +} diff --git a/基础类库/HuizhongLibrary/Models/PostDateClass.cs b/基础类库/HuizhongLibrary/Models/PostDateClass.cs new file mode 100644 index 0000000..3504485 --- /dev/null +++ b/基础类库/HuizhongLibrary/Models/PostDateClass.cs @@ -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; } + } +} diff --git a/基础类库/HuizhongLibrary/Models/TableCell.cs b/基础类库/HuizhongLibrary/Models/TableCell.cs new file mode 100644 index 0000000..a917b52 --- /dev/null +++ b/基础类库/HuizhongLibrary/Models/TableCell.cs @@ -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 Cells { get; set; } + public List> Rows { get; set; } + public JsonTable() + { + Cells = new List(); + Rows = new List>(); + } + + 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 jsonRow = new List(); + 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(); + 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 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 + { + public int ColumnNumber { get; set; } + public int RowCount { get; set; } + public List> Cells { get; set; } + public List>> Rows { get; set; } + public JsonTable() + { + Cells = new List>(); + Rows = new List>>(); + } + + #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> jsonRow = new List>(); + 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>(); + 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> 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 + } + public class JsonCell + { + 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; + } + + + } +} diff --git a/基础类库/HuizhongLibrary/MyAlphaControl/AlphaLabel.Designer.cs b/基础类库/HuizhongLibrary/MyAlphaControl/AlphaLabel.Designer.cs new file mode 100644 index 0000000..0e908d6 --- /dev/null +++ b/基础类库/HuizhongLibrary/MyAlphaControl/AlphaLabel.Designer.cs @@ -0,0 +1,56 @@ +namespace HuizhongLibrary.MyAlphaControl +{ + partial class AlphaLabel + { + /// + /// 必需的设计器变量。 + /// + private System.ComponentModel.IContainer components = null; + + /// + /// 清理所有正在使用的资源。 + /// + /// 如果应释放托管资源,为 true;否则为 false。 + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region 组件设计器生成的代码 + + /// + /// 设计器支持所需的方法 - 不要 + /// 使用代码编辑器修改此方法的内容。 + /// + 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; + + } +} diff --git a/基础类库/HuizhongLibrary/MyAlphaControl/AlphaLabel.cs b/基础类库/HuizhongLibrary/MyAlphaControl/AlphaLabel.cs new file mode 100644 index 0000000..53f5d9a --- /dev/null +++ b/基础类库/HuizhongLibrary/MyAlphaControl/AlphaLabel.cs @@ -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; + /// + /// 背景图片 + /// + public new Bitmap BackgroundImage + { + get { return m_BackgroundImage; } + set + { + m_BackgroundImage = value; + } + } + private StringPool m_ScrollText = new StringPool(); + /// + /// 滚动文字列表 + /// + 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"; + /// + /// 移动方向(None,Left,Right,Top,Boottom) + /// + public string MoveDirection + { + get { return m_MoveDirection; } + set { m_MoveDirection = value; } + } + private int m_DurationStep = 5; + /// + /// 每次移动多少个像素(默认一个像素,最慢的移动速度) + /// + public int DurationStep + { + get { return m_DurationStep; } + set { m_DurationStep = value; } + } + private StringFormat m_TextAlign = new StringFormat(); + /// + /// 文本对齐 + /// + 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; + /// + /// 是否启用倒计时 + /// + public bool TickEnable + { + get { return m_TickEnable; } + set + { + m_TickEnable = value; + if (value == true) { StartTimeer(); } + else { StopTimeer(); } + } + } + + private Color m_BorderColor = Color.Black; + /// + /// 边框粗细 + /// + 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 = ""; + /// + /// 空时显示的文本 + /// + 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; + + /// + /// 当倒计时正常终止时触发 + /// + public event Action 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); + } + } +} diff --git a/基础类库/HuizhongLibrary/MyAlphaControl/AlphaLabel.resx b/基础类库/HuizhongLibrary/MyAlphaControl/AlphaLabel.resx new file mode 100644 index 0000000..3e7a6d2 --- /dev/null +++ b/基础类库/HuizhongLibrary/MyAlphaControl/AlphaLabel.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + WEBPAD + + \ No newline at end of file diff --git a/基础类库/HuizhongLibrary/MyAlphaControl/ControlInfoExtend.cs b/基础类库/HuizhongLibrary/MyAlphaControl/ControlInfoExtend.cs new file mode 100644 index 0000000..b8b2e07 --- /dev/null +++ b/基础类库/HuizhongLibrary/MyAlphaControl/ControlInfoExtend.cs @@ -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; + } +} diff --git a/基础类库/HuizhongLibrary/MyAlphaControl/MyImageList.cs b/基础类库/HuizhongLibrary/MyAlphaControl/MyImageList.cs new file mode 100644 index 0000000..01ba663 --- /dev/null +++ b/基础类库/HuizhongLibrary/MyAlphaControl/MyImageList.cs @@ -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; + } +} diff --git a/基础类库/HuizhongLibrary/MyAlphaControl/MyPanel.Designer.cs b/基础类库/HuizhongLibrary/MyAlphaControl/MyPanel.Designer.cs new file mode 100644 index 0000000..c35d932 --- /dev/null +++ b/基础类库/HuizhongLibrary/MyAlphaControl/MyPanel.Designer.cs @@ -0,0 +1,57 @@ +namespace HuizhongLibrary.MyAlphaControl +{ + partial class MyPanel + { + /// + /// 必需的设计器变量。 + /// + private System.ComponentModel.IContainer components = null; + + /// + /// 清理所有正在使用的资源。 + /// + /// 如果应释放托管资源,为 true;否则为 false。 + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region 组件设计器生成的代码 + + /// + /// 设计器支持所需的方法 - 不要 + /// 使用代码编辑器修改此方法的内容。 + /// + 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; + + } +} diff --git a/基础类库/HuizhongLibrary/MyAlphaControl/MyPanel.cs b/基础类库/HuizhongLibrary/MyAlphaControl/MyPanel.cs new file mode 100644 index 0000000..70c8ede --- /dev/null +++ b/基础类库/HuizhongLibrary/MyAlphaControl/MyPanel.cs @@ -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; + /// + /// 背景图片 + /// + 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 m_ImageArray = new List(); + + public List 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 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 + + + } +} diff --git a/基础类库/HuizhongLibrary/MyAlphaControl/MyPanel.resx b/基础类库/HuizhongLibrary/MyAlphaControl/MyPanel.resx new file mode 100644 index 0000000..7080a7d --- /dev/null +++ b/基础类库/HuizhongLibrary/MyAlphaControl/MyPanel.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/基础类库/HuizhongLibrary/MyAlphaControl/StringPool.cs b/基础类库/HuizhongLibrary/MyAlphaControl/StringPool.cs new file mode 100644 index 0000000..536819c --- /dev/null +++ b/基础类库/HuizhongLibrary/MyAlphaControl/StringPool.cs @@ -0,0 +1,143 @@ +using HuizhongLibrary.Log; +using System; +using System.Collections.Generic; +using System.Text; + +namespace HuizhongLibrary +{ + + #region 消息缓存池 + public class StringPool + { + Queue argsPool; + + public StringPool() + { + argsPool = new Queue(); + } + + #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 +} diff --git a/基础类库/HuizhongLibrary/MyImage.cs b/基础类库/HuizhongLibrary/MyImage.cs new file mode 100644 index 0000000..10dbd56 --- /dev/null +++ b/基础类库/HuizhongLibrary/MyImage.cs @@ -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 Rows { get; set; } + public List Columns { get; set; } + + public MyTable() + { + Rows = new List(); + Columns = new List(); + BorderWidth = 1; + ShowLine = true; + FontName = "宋体"; + FontColor = "Black"; + FontSize = 12; + } + } + #endregion + #region 表格中的行 + public class MyRow + { + public List Cells { get; set; } + public int Height { get; set; } + public string BackColor { get; set; } + public MyRow() + { + Cells = new List(); + 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; } + /// + /// true为列隐藏,false为行隐藏 + /// + 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 + +} diff --git a/基础类库/HuizhongLibrary/MyKeyDemon.cs b/基础类库/HuizhongLibrary/MyKeyDemon.cs new file mode 100644 index 0000000..6b40a7e --- /dev/null +++ b/基础类库/HuizhongLibrary/MyKeyDemon.cs @@ -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; + + + + } +} diff --git a/基础类库/HuizhongLibrary/Network/DataEventArgs.cs b/基础类库/HuizhongLibrary/Network/DataEventArgs.cs new file mode 100644 index 0000000..6a2dbfa --- /dev/null +++ b/基础类库/HuizhongLibrary/Network/DataEventArgs.cs @@ -0,0 +1,16 @@ +using System; +using System.Net; + +namespace HuizhongLibrary.Network +{ + /// + /// EventArgs class holding a Byte[]. + /// + public class DataEventArgs : EventArgs + { + public IPEndPoint RemoteEndPoint { get; set; } + public Byte[] Data { get; set; } + public Int32 Offset { get; set; } + public Int32 Length { get; set; } + } +} diff --git a/基础类库/HuizhongLibrary/Network/ExtensionMethods/ExtensionMethods.cs b/基础类库/HuizhongLibrary/Network/ExtensionMethods/ExtensionMethods.cs new file mode 100644 index 0000000..97b0fab --- /dev/null +++ b/基础类库/HuizhongLibrary/Network/ExtensionMethods/ExtensionMethods.cs @@ -0,0 +1,35 @@ +using System; +using System.Net.Sockets; + +namespace HuizhongLibrary.Network +{ + /// + /// Represents one of the new Socket xxxAsync methods in .NET 3.5. + /// + /// The SocketAsyncEventArgs for use with the method. + /// Returns true if the operation completed asynchronously, false otherwise. + public delegate Boolean SocketAsyncMethod(SocketAsyncEventArgs args); + + /// + /// Holds helper methods for working with the new Socket xxxAsync methods in .NET 3.5. + /// + public static class ExtensionMethods + { + /// + /// 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 + /// + /// The socket this method acts on. + /// The xxxAsync method to be invoked. + /// The callback for the method. Note: The Completed event must already have been attached to the same. + /// The SocketAsyncEventArgs to be used with this call. + public static void InvokeAsyncMethod(this Socket socket, SocketAsyncMethod method, EventHandler callback, SocketAsyncEventArgs args) + { + if (!method(args)) + { + callback(socket, args); + } + + } + } +} \ No newline at end of file diff --git a/基础类库/HuizhongLibrary/Network/SendSocket.cs b/基础类库/HuizhongLibrary/Network/SendSocket.cs new file mode 100644 index 0000000..2a91051 --- /dev/null +++ b/基础类库/HuizhongLibrary/Network/SendSocket.cs @@ -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 ActionProgress) + { + Action> act = new Action>(BeginSendFile); + act.BeginInvoke(IpAddress, Port, FilePath, ActionProgress, null, null); + } + public static void BeginSendFile(string IpAddress, int Port, string FilePath, Action 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 + + } + + +} diff --git a/基础类库/HuizhongLibrary/Network/SocketEventArgs.cs b/基础类库/HuizhongLibrary/Network/SocketEventArgs.cs new file mode 100644 index 0000000..9c6139e --- /dev/null +++ b/基础类库/HuizhongLibrary/Network/SocketEventArgs.cs @@ -0,0 +1,13 @@ +using System; +using System.Net.Sockets; + +namespace HuizhongLibrary.Network +{ + /// + /// EventArgs class holding a Socket. + /// + public class SocketEventArgs : EventArgs + { + public Socket Socket { get; set; } + } +} \ No newline at end of file diff --git a/基础类库/HuizhongLibrary/Network/SocketMessage.cs b/基础类库/HuizhongLibrary/Network/SocketMessage.cs new file mode 100644 index 0000000..ba6f22c --- /dev/null +++ b/基础类库/HuizhongLibrary/Network/SocketMessage.cs @@ -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; + /// + /// 是否要求回复 + /// + 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 ListModel = new List(); + 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 argsPool; + + public bool IsRead = false; + + public SocketMessagePool() + { + argsPool = new Queue(); + 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 argsPool=new Dictionary(); + + #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(); + 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 +} diff --git a/基础类库/HuizhongLibrary/Network/SocketServer/BufferPool.cs b/基础类库/HuizhongLibrary/Network/SocketServer/BufferPool.cs new file mode 100644 index 0000000..416b0fa --- /dev/null +++ b/基础类库/HuizhongLibrary/Network/SocketServer/BufferPool.cs @@ -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 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(); + } + + 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 +} diff --git a/基础类库/HuizhongLibrary/Network/SocketServer/ServerConnection.cs b/基础类库/HuizhongLibrary/Network/SocketServer/ServerConnection.cs new file mode 100644 index 0000000..4cba659 --- /dev/null +++ b/基础类库/HuizhongLibrary/Network/SocketServer/ServerConnection.cs @@ -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 +{ + /// + /// Represents a callback used to inform a listener that a ServerConnection has received data. + /// + /// The sender of the callback. + /// The DataEventArgs object containging the received data. + public delegate void DataReceivedCallback(ServerConnection sender, DataEventArgs e); + /// + /// Represents a callback used to inform a listener that a ServerConnection has disconnected. + /// + /// The sender of the callback. + /// The SocketAsyncEventArgs object used by the ServerConnection. + public delegate void DisconnectedCallback(ServerConnection sender, SocketAsyncEventArgs e); + + /// + /// A connection to our server. + /// + 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 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 SendCompleted; + public event Action DataReceived; + public event Action CloseSocketed; + + + #region 初始化 + public ServerConnection() + { + CheckConnectNumber = 3; + FileLength = 0; + IsLogin = false; + PrevTime = DateTime.Now; + WaitMsgNumber = 0; + SocketBuffer = new List(); + 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(); + 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(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 打包服务器数据 + /// + /// 打包服务器数据 + /// + /// 数据 + /// 数据包 + 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 + /// + /// Disconnects the client. + /// + public void Disconnect() + { + lock (this) + { + CloseConnection(eventArgs); + } + } + + /// + /// Sends data to the client. + /// + /// The data to send. + /// The offset into the data. + /// The ammount of data to send. + 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 + /// + /// Starts and asynchronous recieve. + /// + /// The SocketAsyncEventArgs to use. + private void ListenForData(SocketAsyncEventArgs args) + { + lock (this) + { + if (socket == null) return; + if (socket.Connected) + { + socket.InvokeAsyncMethod(socket.ReceiveAsync, + ReceivedCompleted, args); + } + } + } + + /// + /// Called when an asynchronous receive has completed. + /// + /// The sender. + /// The SocketAsyncEventArgs for the operation. + 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 + + /// + /// Closes the connection. + /// + /// The SocketAsyncEventArgs for the connection. + 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 + /// + /// Fires the DataReceivedCallback. + /// + /// The data which was received. + /// The address the data came from. + /// The callback. + private void OnDataReceived(DataReceivedCallback callback) + { + callback(this, new DataEventArgs() { Data = this.Data, Length = this.ReceiveLen }); + } + + /// + /// Fires the DisconnectedCallback. + /// + /// The SocketAsyncEventArgs for this connection. + /// The callback. + private void OnDisconnected(SocketAsyncEventArgs args, DisconnectedCallback callback) + { + callback(this, args); + } + #endregion + + } +} \ No newline at end of file diff --git a/基础类库/HuizhongLibrary/Network/SocketServer/ServerConnectionPool.cs b/基础类库/HuizhongLibrary/Network/SocketServer/ServerConnectionPool.cs new file mode 100644 index 0000000..2caca5a --- /dev/null +++ b/基础类库/HuizhongLibrary/Network/SocketServer/ServerConnectionPool.cs @@ -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 argsPool; + + public ServerConnectionPool() + { + argsPool = new Queue(); + } + + #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 + + } +} diff --git a/基础类库/HuizhongLibrary/Network/SocketServer/SocketArgsPool.cs b/基础类库/HuizhongLibrary/Network/SocketServer/SocketArgsPool.cs new file mode 100644 index 0000000..c11be61 --- /dev/null +++ b/基础类库/HuizhongLibrary/Network/SocketServer/SocketArgsPool.cs @@ -0,0 +1,121 @@ +using HuizhongLibrary.Log; +using System; +using System.Collections.Generic; +using System.Net.Sockets; + +namespace HuizhongLibrary.Network +{ + /// + /// Pools SocketAsyncEventArgs objects to avoid repeated allocations. + /// + public class SocketArgsPool : IDisposable + { + Queue argsPool; + + + public SocketArgsPool(Int32 capacity) + { + argsPool = new Queue(capacity); + } + + public SocketArgsPool() + { + argsPool = new Queue(); + } + + #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 + + } +} diff --git a/基础类库/HuizhongLibrary/Network/SocketServer/TcpSocketListener.cs b/基础类库/HuizhongLibrary/Network/SocketServer/TcpSocketListener.cs new file mode 100644 index 0000000..8350fef --- /dev/null +++ b/基础类库/HuizhongLibrary/Network/SocketServer/TcpSocketListener.cs @@ -0,0 +1,227 @@ +using System; +using System.Net; +using System.Net.Sockets; +using HuizhongLibrary.Log; + +namespace HuizhongLibrary.Network +{ + /// + /// Listens for socket connection on a given address and port. + /// + public class TcpSocketListener : IDisposable + { + #region Fields + private Int32 connectionBacklog; + private IPEndPoint endPoint; + private AddressFamily family; + + private Socket listenerSocket; + private SocketAsyncEventArgs args; + #endregion + + #region Properties + /// + /// Length of the connection backlog. + /// + public Int32 ConnectionBacklog + { + get { return connectionBacklog; } + set + { + lock (this) + { + if (IsRunning) + throw new InvalidOperationException("Property cannot be changed while server running."); + else + connectionBacklog = value; + } + } + } + /// + /// The IPEndPoint to bind the listening socket to. + /// + public IPEndPoint EndPoint + { + get { return endPoint; } + set + { + lock (this) + { + if (IsRunning) + throw new InvalidOperationException("Property cannot be changed while server running."); + else + endPoint = value; + } + } + } + /// + /// Is the class currently listening. + /// + public Boolean IsRunning + { + get { return listenerSocket != null; } + } + #endregion + + #region Constructors + /// + /// Listens for socket connection on a given address and port. + /// + /// The address to listen on. + /// The port to listen on. + /// The connection backlog. + public TcpSocketListener(AddressFamily family, String address, Int32 port, Int32 connectionBacklog) + : this(family,IPAddress.Parse(address), port, connectionBacklog) + { } + /// + /// Listens for socket connection on a given address and port. + /// + /// The address to listen on. + /// The port to listen on. + /// The connection backlog. + public TcpSocketListener(AddressFamily family, IPAddress address, Int32 port, Int32 connectionBacklog) + : this(family,new IPEndPoint(address, port), connectionBacklog) + { } + /// + /// Listens for socket connection on a given address and port. + /// + /// The endpoint to listen on. + /// The connection backlog. + 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 + /// + /// Start listening for socket connections. + /// + 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."); + } + + } + + /// + /// Stop listening for socket connections. + /// + public void Stop() + { + lock (this) + { + if (listenerSocket == null) + return; + listenerSocket.Close(); + listenerSocket = null; + } + } + #endregion + + #region Private Methods + /// + /// Asynchronously listens for new connections. + /// + /// + 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); + } + + } + /// + /// Invoked when an asynchrounous accept completes. + /// + /// The sender. + /// The SocketAsyncEventArgs for the operation. + 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 + /// + /// Fired when a new connection is received. + /// + public event EventHandler SocketConnected; + /// + /// Fires the SocketConnected event. + /// + /// The new client socket. + 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 + } +} \ No newline at end of file diff --git a/基础类库/HuizhongLibrary/Network/TcpSocket.cs b/基础类库/HuizhongLibrary/Network/TcpSocket.cs new file mode 100644 index 0000000..0367d77 --- /dev/null +++ b/基础类库/HuizhongLibrary/Network/TcpSocket.cs @@ -0,0 +1,2891 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using HuizhongLibrary.Network; +using System.Collections; +using System.Net.Sockets; +using System.Threading; +using System.Net; +using HuizhongLibrary.Log; +using System.IO; +using System.Text.RegularExpressions; +using System.Security.Cryptography; +using HuizhongLibrary.RegularExpressions; +using WebSocketSharp; +using WebSocketSharp.Server; + +namespace HuizhongLibrary.Network +{ + #region 服务器Socket + public class SocketService + { + /// + /// 要监控的端口号 + /// + public int Port { get; set; } + /// + /// 空闲超时自动断开或引发心跳包事件 + /// + public int OutTime { get; set; } + /// + /// 重发等待默认30秒后重发 + /// + public int RefshSecond { get; set; } + /// + /// 最大消息等待回包数量(滑动窗口) + /// + public int MaxWaitMsgNumber { get; set; } + public AddressFamily Family { get; set; } + public int MaxSendNumber { get; set; } + public int BufferSize { get; set; } + public bool OutMaxSendNumberCloseConnect { get; set; } + /// + /// 是否长连接(默认长连接) + /// + public bool IsLongConnect { get; set; } + /// + /// 是否启用发送线程 + /// + public bool IsSendThread { get; set; } + /// + /// 数据读取到时发生 + /// + public event Action ReceiveData; + /// + /// 连接完成时发生 + /// + public event Action ConnectSocketComplete; + /// + /// 关闭时发生 + /// + public event Action CloseSocketComplete; + /// + /// 心跳请求事件 + /// + public event Action OutTimeHappen; + /// + /// 发送失败事件 + /// + public event Action SendError; + public event Action ReadDataMessage; + + + + TcpSocketListener socketListener = null; + public ServerConnectionPool ListUserSocket = new ServerConnectionPool(); + private AutoResetEvent AutoReset = new AutoResetEvent(false); + public SocketArgsPool socketArgsPool = null; + //BufferPool bufferManager = null; + public bool IsRun = false; + + + public SocketService() + { + Family = AddressFamily.InterNetwork; + IsSendThread = false; + IsLongConnect = false; + OutTime = 180; + Port = 10000; + RefshSecond = 30; + MaxWaitMsgNumber = 10; + BufferSize = 1024; + OutMaxSendNumberCloseConnect = false; + } + #region 初始化缓存 + public void Init() + { + //初始化数据接收缓存 + //bufferManager = new BufferPool(MaxConnect * BuffSize, BuffSize); + //bufferManager.InitBuffer(); + + // 声明异步Socket + //SocketAsyncEventArgs readWriteEventArg; + + //for (int i = 0; i < MaxConnect; i++) + //{ + // //初始化异步Socket + // readWriteEventArg = new SocketAsyncEventArgs(); + // // 设备接收数据缓存 + // bufferManager.SetBuffer(readWriteEventArg); + // // 把异步Socket放入集合顶部 + // socketArgsPool.CheckIn(readWriteEventArg); + //} + } + #endregion + #region 开始监控 + public void Start() + { + socketArgsPool = new SocketArgsPool(); + socketListener = new TcpSocketListener(Family, IPAddress.Any, Port, 9999); + socketListener.SocketConnected += socketListener_SocketConnected; + socketListener.Start(); + RunWhileListUserSocket(); + } + #endregion + #region 结束监控 + public void Stop() + { + IsRun = false; + AutoReset.Set(); + if (socketListener!=null) socketListener.Stop(); + while (true) + { + var model = ListUserSocket.CheckOut(); + if (model == null) break; + model.Disconnect(); + } + ListUserSocket.Clear(); + System.GC.Collect(); + } + #endregion + #region 结束监控并且发送断开连接消息 + public void Stop(byte[] bytes) + { + IsRun = false; + AutoReset.Set(); + if (socketListener != null) socketListener.Stop(); + while (true) + { + var model = ListUserSocket.CheckOut(); + if (model == null) break; + if (bytes != null && bytes.Length > 0) model.SendData(bytes, 0, bytes.Length); + model.Disconnect(); + } + ListUserSocket.Clear(); + System.GC.Collect(); + } + #endregion + #region 启动发送线程 + void RunWhileListUserSocket() + { + if (this.IsSendThread == true) + { + Thread t1 = new Thread(new ThreadStart(this.WhileListUserSocket)); + t1.Start(); + } + else + { + Thread t1 = new Thread(new ThreadStart(this.WhileListUserSocket2)); + t1.Start(); + } + } + #endregion + #region 关闭设备连接 + public bool CloseDevice(string IpAddress) + { + bool bk = false; + int index = ListUserSocket.Available; + for (int i = 0; i < index; i++) + { + var model = ListUserSocket.CheckOut(); + if (model == null) break; + if (model.IpAddress == IpAddress) + { + model.Disconnect(); + bk = true; + break; + } + ListUserSocket.CheckIn(model); + } + return bk; + } + #endregion + #region 关闭设备连接 + public bool CloseDevice2(string DeviceNo) + { + bool bk = false; + int index = ListUserSocket.Available; + for (int i = 0; i < index; i++) + { + var model = ListUserSocket.CheckOut(); + if (model == null) break; + if (model.DeviceNo == DeviceNo) + { + model.Disconnect(); + bk = true; + break; + } + ListUserSocket.CheckIn(model); + } + return bk; + } + #endregion + #region 关闭设备连接 + public bool CloseDevice3(string DeviceNo, int Port) + { + bool bk = false; + int index = ListUserSocket.Available; + for (int i = 0; i < index; i++) + { + var model = ListUserSocket.CheckOut(); + if (model == null) break; + if (model.DeviceNo == DeviceNo && model.Port == Port) + { + model.Disconnect(); + bk = true; + break; + } + ListUserSocket.CheckIn(model); + } + return bk; + } + #endregion + #region 接受连接请求 + void socketListener_SocketConnected(object sender, SocketEventArgs e) + { + try + { + e.Socket.SendBufferSize = 32 * 1024; + e.Socket.ReceiveBufferSize = 32 * 1024; + e.Socket.LingerState = new LingerOption(true, 0); + e.Socket.SendTimeout = 60000; + //SocketAsyncEventArgs args = socketArgsPool.CheckOut(); + SocketAsyncEventArgs args = null; + if (args == null) + { + args = new SocketAsyncEventArgs(); + byte[] buffer = new byte[BufferSize]; + args.SetBuffer(buffer, 0, buffer.Length); + } + ServerConnection connection = null; + try + { + connection = new ServerConnection(e.Socket, args); + connection.DataReceived += DataReceived; + connection.CloseSocketed += Disconnected; + } + catch (Exception ex) + { + ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message); + e.Socket.Close(); + //if (connection!=null) connection.Disconnect(); + return; + } + ListUserSocket.CheckIn(connection); + if (this.ConnectSocketComplete != null) this.ConnectSocketComplete(connection); + } + catch (Exception exx) + { + ErrorFollow.TraceWrite(exx.TargetSite.Name, exx.StackTrace, exx.Message); + } + + } + #endregion + #region 读取消息 + void DataReceived(ServerConnection sender, DataEventArgs e) + { + if (e.Data.Length == 0) return; + sender.PrevTime = DateTime.Now; + if (this.ReceiveData != null) this.ReceiveData(sender, e); + } + #endregion + #region 对方关闭连接 + void Disconnected(ServerConnection model, SocketAsyncEventArgs e) + { + if (model == null || model.Enabled == false) + { + if (model != null) + { + model.DataReceived -= DataReceived; + model.CloseSocketed -= Disconnected; + model.Dispose(); + } + if (this.CloseSocketComplete != null) this.CloseSocketComplete(model); + e.Dispose(); + e = null; + model = null; + } + else + { + model.DataReceived -= DataReceived; + model.CloseSocketed -= Disconnected; + model.Disconnect(); + } + } + #endregion + #region 发送完成时 + void connection_SendCompleted(ServerConnection model) + { + if (this.IsRun == true) ListUserSocket.CheckIn(model); + } + #endregion + #region 轮循连接列表 + void WhileListUserSocket() + { + //bool IsRemoveMessage = false; + IsRun = true; + while (IsRun) + { + try + { + ServerConnection model = ListUserSocket.CheckOut(); + if (model == null) + { + AutoReset.WaitOne(5000, false); + continue; + } + if (model.Enabled == false) continue; + if (model.PrevTime.AddSeconds(this.OutTime) < DateTime.Now) + { + if (this.IsLongConnect == false) + { + ErrorFollow.TraceWrite("服务器检测到" + model.DeviceNo + "无应答", "", "断开对方连接"); + model.Disconnect(); + continue; + } + else + { + //如果是长连接引发,心跳事件 + if (this.OutTimeHappen != null) + { + this.OutTimeHappen(model); + model.PrevTime = DateTime.Now; + ListUserSocket.CheckIn(model); + continue; + } + } + } + //如果服务器是断开连接的,那么不读取主动发送的数据 + if (string.IsNullOrEmpty(model.DeviceNo) == false && model.ListMessage.Count == 0) + { + if (this.ReadDataMessage != null) this.ReadDataMessage(model); + } + if (model.ListMessage.Count > 0) + { + while (model.WaitMsgNumber < this.MaxWaitMsgNumber) + { + SocketMessage Msg = model.GetNextSocketMessage(this.RefshSecond); + if (Msg == null) break; + if (this.MaxSendNumber > 0 && Msg.SendNumber > this.MaxSendNumber) + { + if (OutMaxSendNumberCloseConnect == false) + { + model.EndWaitMsg(Msg.SequenceID); + continue; + } + else + { + model.Disconnect(); + break; + } + } + if (this.Send(model, Msg) == false) + { + if (this.SendError != null) this.SendError(Msg); + break; + } + } + } + if (model.Enabled == false) continue; + if (model.ListMessage.IsEmployMessages == true) model.ListMessage.RemoveEmploy(); + ListUserSocket.CheckIn(model); + AutoReset.WaitOne(10, false); + } + catch (Exception ex) + { + ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message); + } + } + } + #endregion + #region 轮循连接列表 + void WhileListUserSocket2() + { + IsRun = true; + while (IsRun) + { + try + { + ServerConnection model = ListUserSocket.CheckOut(); + if (model == null) + { + AutoReset.WaitOne(30000, false); + continue; + } + if (model.Enabled == false) continue; + if (model.PrevTime.AddSeconds(this.OutTime) < DateTime.Now) + { + if (this.IsLongConnect == false) + { + ErrorFollow.TraceWrite("服务器检测到" + model.DeviceNo + "无应答", "", "断开对方连接"); + model.Disconnect(); + continue; + } + else + { + //如果是长连接引发,心跳事件 + if (this.OutTimeHappen != null) + { + this.OutTimeHappen(model); + model.PrevTime = DateTime.Now; + ListUserSocket.CheckIn(model); + continue; + } + } + } + if (model.Enabled == false) continue; + ListUserSocket.CheckIn(model); + AutoReset.WaitOne(100, false); + } + catch (Exception ex) + { + ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message); + } + } + } + #endregion + #region 发送数据 + public bool Send(ServerConnection model, SocketMessage msg) + { + model.PrevTime = DateTime.Now; + try + { + msg.SendNumber++; + msg.SendTime = DateTime.Now; + bool bk = model.SendData(msg.Bytes, 0, msg.SendLength); + if (bk == false) + { + ErrorFollow.TraceWrite("Send", "", "发送失败断开连接"); + model.Disconnect(); + return false; + } + if (msg.IsRevert == false) + { + EndWaitMsg(model, msg.SequenceID); + } + else + { + if (msg.SendNumber > 1) model.IncrementWaitMsgNumber(); + } + } + catch (Exception ex) + { + ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message); + model.Disconnect(); + return false; + } + return true; + } + #endregion + #region 返回UserSocket + public ServerConnection GetUserSocket(string IpAddress) + { + int index = ListUserSocket.Available; + for (int i = 0; i < index; i++) + { + var model = ListUserSocket.CheckOut(); + if (model == null) break; + if (model.Enabled == false) continue; + if (model.IpAddress == IpAddress) return model; + ListUserSocket.CheckIn(model); + } + return null; + } + #endregion + #region 返回UserSocket + public ServerConnection GetUserSocket2(string DeviceNo) + { + int index = ListUserSocket.Available; + for (int i = 0; i < index; i++) + { + var model = ListUserSocket.CheckOut(); + if (model == null) break; + if (model.Enabled == false) continue; + if (model.DeviceNo == DeviceNo) return model; + ListUserSocket.CheckIn(model); + } + return null; + } + #endregion + #region 返回UserSocket + public ServerConnection GetUserSocket3(string DeviceNo, int Port) + { + int index = ListUserSocket.Available; + for (int i = 0; i < index; i++) + { + var model = ListUserSocket.CheckOut(); + if (model == null) break; + if (model.Enabled == false) continue; + if (model.DeviceNo == DeviceNo && model.Port != Port) return model; + ListUserSocket.CheckIn(model); + } + return null; + } + #endregion + #region 消除已回复消息 + public int EndWaitMsg(ServerConnection model, string SequenceID) + { + SocketMessage msg = model.EndWaitMsg(SequenceID); + if (msg == null) return 0; + return msg.MessageID; + } + #endregion + } + #endregion + #region 客户端Socket + public class ClientSocket + { + public string IpAddress { get; set; } + public int Port { get; set; } + public ServerConnection UseSocket { get; set; } + public int RefshSecond { get; set; } + /// + /// 最大消息等待回复数量 + /// + public int MaxWaitMsgNumber { get; set; } + /// + /// 超出多少秒没有数据通讯后连接自动断开 + /// + public int OutTime { get; set; } + public int BuffSize { get; set; } + public int MaxSendNumber { get; set; } + public bool IsLongConnect { get; set; } + public bool IsLogin { get; set; } + + + public event Action ReceiveData; + public event Action ConnectSocketComplete; + public event Action CloseSocketComplete; + public event Action ConnectSocketError; + public event Action OutTimeHappen; + public event Action SendError; + public event Action LocalIpAddressComplete; + + private AutoResetEvent AutoReset = new AutoResetEvent(false); + private bool IsRun = false; + private DateTime PrevTime = DateTime.Now; + private int CloseReConnectTime = 0; + + + public ClientSocket() + { + IsLongConnect = true; + IsLogin = false; + RefshSecond = 10; + MaxWaitMsgNumber = 16; + MaxSendNumber = 0; + OutTime = 30; + BuffSize = 32 * 1024; + UseSocket = new ServerConnection(); + UseSocket.DataReceived += DataReceived; + UseSocket.CloseSocketed += Disconnected; + } + + #region 开始监控 + public void Start() + { + IsRun = true; + Thread t1 = new Thread(new ThreadStart(this.WhileListUserSocket)); + t1.Name = "ClientSocket"; + t1.Start(); + } + #endregion + #region 停止 + public void Stop() + { + IsRun = false; + AutoReset.Set(); + CloseSocket(UseSocket); + } + #endregion + #region 连接 + bool SocketAccept() + { + IPAddress broadcast; + if (DataRegex.IsIP(IpAddress) == false) + { + broadcast = Dns.GetHostAddresses(IpAddress)[0]; + } + else + { + broadcast = IPAddress.Parse(IpAddress); + } + IPEndPoint ep = new IPEndPoint(broadcast, Port); + Socket e = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + e.LingerState = new LingerOption(true, 0); + e.SendTimeout = 60000; + try + { + e.Connect(ep); + if (this.LocalIpAddressComplete != null) + { + string[] RemoteEndPoint = e.LocalEndPoint.ToString().Split(':'); + this.LocalIpAddressComplete(RemoteEndPoint[0]); + } + System.Threading.Thread.Sleep(1000); + UseSocket.PrevTime = DateTime.Now; + } + catch (Exception ex) + { + //CloseReConnectTime = 60; + ErrorFollow.TraceWrite("连接失败", this.IpAddress + ":" + Port, ex.Message); + if (this.ConnectSocketError != null) this.ConnectSocketError(this.IpAddress); + return false; + } + SocketAsyncEventArgs args = new SocketAsyncEventArgs(); + byte[] bytes = new byte[this.BuffSize]; + args.SetBuffer(bytes, 0, this.BuffSize); + + UseSocket.Start(e, args); + if (this.ConnectSocketComplete != null) this.ConnectSocketComplete(this.UseSocket); + return true; + } + #endregion + #region 读取消息 + void DataReceived(ServerConnection sender, DataEventArgs e) + { + if (e.Data.Length == 0) return; + UseSocket.PrevTime = DateTime.Now; + if (this.ReceiveData != null) this.ReceiveData(sender, e); + } + #endregion + #region 对方关闭连接 + void Disconnected(ServerConnection sender, SocketAsyncEventArgs e) + { + CloseReConnectTime = 60; + if (this.CloseSocketComplete != null) this.CloseSocketComplete(sender); + e.Dispose(); + e = null; + //ErrorFollow.TraceWrite("TcpSocker.Disconnected", "", "对方关闭连接"); + //CloseSocket(sender); + } + #endregion + + #region 轮循消息列表 + void WhileListUserSocket() + { + bool bk = false; + //SocketAccept(); + while (IsRun) + { + try + { + if (UseSocket.Enabled == false) + { + if (this.IsLongConnect == true || UseSocket.ListMessage.Count > 0) + { + if (CloseReConnectTime > 0) + { + CloseReConnectTime = 0; + AutoReset.WaitOne(2000); + if (IsRun == false) return; + } + bk = SocketAccept(); + if (bk == true) continue; + if (IsRun == true) AutoReset.WaitOne(2000); + } + else + { + if (IsRun == true) AutoReset.WaitOne(2000, false); + } + continue; + } + if (UseSocket.PrevTime.AddSeconds(this.OutTime) < DateTime.Now) + { + if (this.IsLongConnect == false) + { + CloseSocket(UseSocket); + bk = true; + continue; + } + else + { + //如果是长连接引发,心跳事件 + if (this.OutTimeHappen != null) + { + this.OutTimeHappen(UseSocket); + UseSocket.PrevTime = DateTime.Now; + continue; + } + } + } + if (UseSocket.ListMessage.Count > 0) + { + //ErrorFollow.TraceWrite("发送数据", "", "数量:" + UseSocket.ListMessage.Count + ",等待数:" + UseSocket.WaitMsgNumber); + while (true) + { + SocketMessage Msg = UseSocket.GetNextSocketMessage(this.RefshSecond); + if (Msg == null) break; + if (UseSocket.WaitMsgNumber >= this.MaxWaitMsgNumber) break; + if (this.MaxSendNumber > 0 && Msg.SendNumber > this.MaxSendNumber) + { + UseSocket.EndWaitMsg(Msg.SequenceID); + continue; + } + if (this.Send(UseSocket, Msg) == false) + { + if (this.SendError != null) this.SendError(Msg); + break; + } + UseSocket.IncrementWaitMsgNumber(); + AutoReset.WaitOne(10, false); + } + } + if (IsRun == true) AutoReset.WaitOne(1000, false); + } + catch (Exception ex) + { + ErrorFollow.TraceWrite("线程循环错误", "", "关闭连接"); + CloseSocket(UseSocket); + ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message); + } + } + + } + #endregion + #region 发送数据 + public bool Send(ServerConnection model, SocketMessage msg) + { + model.PrevTime = DateTime.Now; + try + { + msg.SendNumber++; + msg.SendTime = DateTime.Now; + if (msg.SendNumber > 1) + { + string m = "第" + msg.SendNumber + "次"; + m += ",上次发送时间:" + msg.SendTime; + m += ",id:" + msg.MessageID; + m += ",流水号:" + msg.SequenceID; + m += ",FunNo:" + msg.FunNo; + m += ",DeviceNo:" + msg.DeviceNo; + ErrorFollow.TraceWrite("重发数据", "", m); + } + bool bk = model.SendData(msg.Bytes, 0, msg.Bytes.Length); + if (bk == false) + { + ErrorFollow.TraceWrite("发送数据失败", "", "断开连接"); + CloseSocket(model); + } + return bk; + } + catch + { + ErrorFollow.TraceWrite("发送数据失败", "", "断开连接"); + CloseSocket(model); + return false; + } + } + #endregion + #region 关闭连接 + public void CloseSocket() + { + CloseSocket(this.UseSocket); + } + #endregion + #region 关闭连接 + public void CloseSocket(ServerConnection model) + { + if (model.Enabled == false) return; + try + { + this.OutTime = 5; + model.Enabled = false; + model.Disconnect(); + } + catch + { } + } + #endregion + #region 消除已回复消息 + public int EndWaitMsg(string SequenceID) + { + try + { + SocketMessage msg = UseSocket.EndWaitMsg(SequenceID); + if (UseSocket.WaitMsgNumber == this.MaxSendNumber - 1) UseSocket.WaitMsgNumber = 0; + if (msg == null) return 0; + return msg.MessageID; + } + catch (Exception ex) + { + ErrorFollow.TraceWrite("ClientSocket.EndWaitMsg", "", ex.Message); + } + return 0; + } + #endregion + } + #endregion + #region 文件下载服务器 + public class FileService + { + private int Port = 11111; + public AutoResetEvent AutoReset = new AutoResetEvent(false); + + public char SpaceChar = '^'; + public static string WebPath = ""; + + SocketService ser = new SocketService(); + + public event Action> ReceiveData; + public event Action ConnectSocketComplete; + public event Action CloseSocketComplete; + + public System.Security.Cryptography.MD5CryptoServiceProvider oMD5Hasher = new System.Security.Cryptography.MD5CryptoServiceProvider(); + + public FileService() + { + //ser. + ser.IsLongConnect = false; + ser.OutMaxSendNumberCloseConnect = true; + ser.MaxWaitMsgNumber = 16; + ser.MaxSendNumber = 2; + ser.OutTime = 60 * 3; + ser.RefshSecond = 10; + ser.ReceiveData += ser_ReceiveData; + ser.ConnectSocketComplete += ser_ConnectSocketComplete; + ser.CloseSocketComplete += ser_CloseSocketComplete; + } + + #region 连接 + void ser_ConnectSocketComplete(ServerConnection model) + { + if (this.ConnectSocketComplete != null) this.ConnectSocketComplete(model); + } + #endregion + #region 关闭连接 + void ser_CloseSocketComplete(ServerConnection model) + { + if (model.fs != null) + { + model.fs.Close(); + model.fs = null; + } + if (this.CloseSocketComplete != null) this.CloseSocketComplete(model); + } + #endregion + + #region 启动监控 + public void Start(int Port) + { + this.Port = Port; + if (this.Port == 0) return; + ser.BufferSize = 2 * 1024; + ser.Port = Port; + ser.Start(); + } + #endregion + #region 停止监控 + public void Stop() + { + if (this.Port == 0) return; + ser.Stop(null); + } + #endregion + + #region 服务器读取到数据时发生 + private void ser_ReceiveData(ServerConnection model, DataEventArgs arg2) + { + try + { + string Data = System.Text.Encoding.GetEncoding("GB2312").GetString(model.Data).Trim('\0'); + ErrorFollow.TraceWrite("读取到数据", model.IpAddress, Data); + Dictionary ReceiveModel = this.ParseData(Data); + string FunNo = ReceiveModel["TRANS_NO"]; + switch (FunNo) + { + case "9999": //文件下载请求 + DownFile(model, ReceiveModel); + break; + default: + if (this.ReceiveData != null) this.ReceiveData(model, ReceiveModel); + break; + } + } + catch (Exception ex) + { + ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message); + } + } + #endregion + #region 解析返回数据 + Dictionary ParseData(string Data) + { + if (string.IsNullOrEmpty(Data) == true) return null; + //if (ErrorFollow.IsDebug == true) ErrorFollow.TraceWrite("解析返回数据", "", Data); + Dictionary list = new Dictionary(); + string[] ss = Data.Split(this.SpaceChar); + foreach (string item in ss) + { + if (string.IsNullOrEmpty(item) == true) continue; + string[] sss = item.Split('='); + if (sss.Length == 1) + { + list.Add(sss[0].ToUpper(), ""); + } + if (sss.Length == 2) + { + list.Add(sss[0].ToUpper(), sss[1]); + } + } + return list; + } + #endregion + #region 下载文件 + public void DownFile(ServerConnection model, Dictionary ReceiveModel) + { + + NetworkStream ns = null; + Socket socker = null; + + try + { + string FilePath = CustomIO.GetKeyValues(ReceiveModel, "FilePath"); + if (FilePath.Contains(":") == false) FilePath = FileService.WebPath + FilePath; + bool IsExistsFile = File.Exists(FilePath); + socker = model.GetSocket(); + ns = new NetworkStream(socker); + if (IsExistsFile == false) + { + ErrorFollow.TraceWrite("下载文件失败,文件不存在", model.IpAddress, FilePath); + byte[] fileBuffer = new byte[24]; + for (int i = 8; i < 24; i++) + { + fileBuffer[i] = 255; + } + ns.Write(fileBuffer, 0, 24); + } + else + { + //传送头信息:文件长度,MD5校验码 + model.fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read); + byte[] HeaderLen = BitConverter.GetBytes(model.fs.Length); + byte[] HeaderHash = oMD5Hasher.ComputeHash(model.fs); + ns.Write(HeaderLen, 0, HeaderLen.Length); + ns.Write(HeaderHash, 0, HeaderHash.Length); + byte[] fileBuffer = new byte[1024 * 4]; // 每次传1KB + int bytesRead; + int totalBytes = 0; + // 将文件流转写入网络流 + int index = 0; + model.fs.Position = 0; + do + { + bytesRead = model.fs.Read(fileBuffer, 0, fileBuffer.Length); + if (bytesRead == 0) break; + ns.Write(fileBuffer, 0, bytesRead); + totalBytes += bytesRead; // 发送了的字节数 + index++; + if (index == 10) + { + AutoReset.WaitOne(10, false); + index = 0; + model.PrevTime = DateTime.Now; + } + } while (bytesRead > 0); + model.fs.Close(); + model.fs = null; + } + } + catch (Exception ex) + { + if (model.fs != null) + { + model.fs.Close(); + model.fs = null; + } + ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message); + } + + } + #endregion + } + #endregion + #region 文件下载客户端 + public class FileClient + { + public static string IpAddress = ""; + public static int Port = 11111; + public static string SpaceChar = "^"; + + public int CilentID = 0; + public int DownFileID = 0; + public List FileManage = null; + public int ModelType = 0; + public bool IsSaveList = true; + public bool IsErrorStopDown = false; + public float Version = 0; + public object CustomModel = null; + private AutoResetEvent AutoReset = new AutoResetEvent(false); + public bool IsRun = true; + public string tempFilePath = ""; + public string RunTime = ""; + + public event Action DownFileComplete; //下载文件完成 + public event Action DownFileErrorComplete; //下载文件错误时发生 + public event Action DownNoFileComplete; //服务器不存在这个文件 + + #region 启动监控 + public void Start() + { + IsRun = true; + Thread t = new Thread(this.OnStart); + t.Start(); + } + #endregion + #region 启动监控 + public void Start(int ModelType, List ListModel) + { + this.ModelType = ModelType; + this.FileManage = ListModel; + IsRun = true; + string dir = SystemInfo.AppPath() + "TempFileDown"; + if (Directory.Exists(dir) == false) Directory.CreateDirectory(dir); + tempFilePath = dir + "/" + DateTime.Now.ToString("MMddHHmmssfff") + ".txt"; + Thread t = new Thread(this.OnStart); + t.Start(); + } + #endregion + #region 启动监控 + public void Start(int ModelType, string filePath, List ListModel) + { + this.ModelType = ModelType; + this.FileManage = ListModel; + IsRun = true; + string dir = SystemInfo.AppPath() + "TempFileDown"; + if (Directory.Exists(dir) == false) Directory.CreateDirectory(dir); + tempFilePath = filePath; + Thread t = new Thread(this.OnStart); + t.Start(); + } + #endregion + #region 停止监控 + public void Stop() + { + FileManage.Clear(); + IsRun = false; + AutoReset.Set(); + } + #endregion + #region 保存下载文件列表 + public void SaveFileList() + { + try + { + if (this.IsSaveList == false) return; + if (string.IsNullOrEmpty(tempFilePath) == true) + { + string dir = SystemInfo.AppPath() + "TempFileDown"; + if (Directory.Exists(dir) == false) Directory.CreateDirectory(dir); + tempFilePath = dir + "/" + DateTime.Now.ToString("MMddHHmmssfff") + ".txt"; + } + StringBuilder sb = new StringBuilder(); + sb.Append("DownFileID=" + this.DownFileID + FileClient.SpaceChar); + sb.Append("ModelType=" + this.ModelType + FileClient.SpaceChar); + sb.Append("RowCount=" + FileManage.Count + FileClient.SpaceChar); + sb.Append("IsErrorStopDown=" + IsErrorStopDown.ToString() + FileClient.SpaceChar); + int index = 1; + foreach (NetDownFile item in FileManage) + { + sb.Append("DownFileName[" + index + "]=" + item.DownFileName + FileClient.SpaceChar); + sb.Append("DownID[" + index + "]=" + item.DownID + FileClient.SpaceChar); + sb.Append("SaveFileName[" + index + "]=" + item.SaveFileName + FileClient.SpaceChar); + sb.Append("IsDownComplete[" + index + "]=" + item.IsDownComplete.ToString() + FileClient.SpaceChar); + sb.Append("FileType[" + index + "]=" + item.FileType + FileClient.SpaceChar); + index++; + } + using (StreamWriter sw = new StreamWriter(tempFilePath, false, System.Text.Encoding.GetEncoding("GB2312"))) + { + sw.WriteLine(sb.ToString()); + sw.Close(); + } + } + catch (Exception ex) + { + ErrorFollow.TraceWrite("保存下载文件列表", ex.StackTrace, ex.Message); + } + + + } + #endregion + + #region 文件下载 + void OnStart() + { + DateTime StartTime = DateTime.Now; + SaveFileList(); + FileStream fs = null; + NetworkStream ns = null; + TcpClient tcp = null; + try + { + System.Security.Cryptography.MD5CryptoServiceProvider oMD5Hasher = new System.Security.Cryptography.MD5CryptoServiceProvider(); + bool bk = false; + #region 循环 + foreach (NetDownFile item in FileManage) + { + if (item.IsDownComplete == true) continue; + try + { + if (File.Exists(item.SaveFileName) == true) File.Delete(item.SaveFileName); + } + catch + { + ErrorFollow.TraceWrite("下载文件", "", item.SaveFileName + "文件删除失败"); + bk = true; + break; + } + string dir = Path.GetDirectoryName(item.SaveFileName); + if (Directory.Exists(dir) == false) Directory.CreateDirectory(dir); + string path = item.SaveFileName + ".temp"; + if (File.Exists(path) == true) + { + DateTime dt = DateTime.Now; + FileInfo finfo = new FileInfo(path); + if (dt.AddMinutes(-1) < finfo.LastWriteTime) + { + finfo = null; + ErrorFollow.TraceWrite("下载文件", "", path + "文件已经在下载"); + bk = true; + break; + } + File.Delete(path); + } + IPAddress broadcast = IPAddress.Parse(IpAddress); + IPEndPoint ep = new IPEndPoint(broadcast, Port); + tcp = new TcpClient(); + tcp.Connect(ep); + ns = tcp.GetStream(); + //这里发送文件下载请求 + StringBuilder sb = new StringBuilder(); + if (item.FileType == 0) + { + sb.Append("TRANS_NO=9998" + FileClient.SpaceChar); + } + else + { + sb.Append("TRANS_NO=9999" + FileClient.SpaceChar); + } + sb.Append("FilePath=" + item.DownFileName + FileClient.SpaceChar); + byte[] bytes = System.Text.Encoding.GetEncoding("GB2312").GetBytes(sb.ToString()); + ns.Write(bytes, 0, bytes.Length); + //AutoReset.WaitOne(1000, false); + byte[] fileHeader = new byte[24]; + byte[] fileBuffer = new byte[1024 * 4]; // 每次收1KB + if (File.Exists(path)) File.Delete(path); + fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite); + + // 从缓存buffer中读入到文件流中 + int bytesRead; + int totalBytes = 0; + int index = 0; + byte[] HeaderHash = null; + string CheckOutCode = ""; + do + { + bytesRead = ns.Read(fileBuffer, 0, fileBuffer.Length); + if (totalBytes < 24) + { + int count = 24 - totalBytes; + if (bytesRead < count) count = bytesRead; + Buffer.BlockCopy(fileBuffer, 0, fileHeader, totalBytes, count); + if (totalBytes + count >= 24) + { + item.Length = BitConverter.ToInt64(fileHeader, 0); + if (item.Length == 0) break; + item.CheckOutCode = BitConverter.ToString(fileHeader, 8, 16); + if (bytesRead > 24) fs.Write(fileBuffer, count, bytesRead - count); + } + } + else + { + fs.Write(fileBuffer, 0, bytesRead); + } + totalBytes += bytesRead; + if (item.Length > 0 && totalBytes >= item.Length + 24) break; + if (index == 10) { AutoReset.WaitOne(10, false); if (IsRun == false) return; index = 0; } + } while (bytesRead > 0); + if (fs.Length > 0) + { + fs.Position = 0; + HeaderHash = oMD5Hasher.ComputeHash(fs); + CheckOutCode = BitConverter.ToString(HeaderHash, 0, 16); + } + long FileLength = fs.Length; + fs.Close(); + fs = null; + ns.Close(); + ns = null; + tcp.Close(); + tcp = null; + bool bkk = true; + if (item.Length == 0 && fileHeader.Length == 24) + { + bkk = false; + for (int i = 8; i < 24; i++) + { + if (fileHeader[i] != 255) { bkk = true; break; } + } + } + if (bkk == false) + { + ErrorFollow.TraceWrite("下载文件", "", "服务器不存在这个文件:" + item.DownFileName); + item.IsDownComplete = true; + if (this.DownNoFileComplete != null) this.DownNoFileComplete(item); + File.Delete(path); + bk = false; + break; + } + else if (item.Length == 0 || HeaderHash == null) + { + ErrorFollow.TraceWrite("下载文件出错", "文件长度不能等于0", item.DownFileName); + File.Delete(path); + bk = true; + break; + } + else if (FileLength != item.Length) + { + ErrorFollow.TraceWrite("下载文件出错", "文件长度错误", item.DownFileName); + File.Delete(path); + bk = true; + break; + } + else if (CheckOutCode != item.CheckOutCode) + { + ErrorFollow.TraceWrite("下载文件出错", "MD5校验失败", item.DownFileName); + File.Delete(path); + bk = true; + break; + } + else + { + ErrorFollow.TraceWrite("下载文件成功", "", item.DownFileName); + item.IsDownComplete = true; + File.Move(path, item.SaveFileName); + } + } + #endregion + + if (bk == false) + { + DateTime StopTime = DateTime.Now; + TimeSpan ts = StopTime - StartTime; + RunTime = ts.ToString(); + IsRun = false; + if (this.IsSaveList == true) File.Delete(tempFilePath); + if (this.DownFileComplete != null) this.DownFileComplete(this); + } + else + { + if (this.IsErrorStopDown == true) + { + ErrorFollow.TraceWrite("下载文件错误", "", "停止下载"); + if (this.DownFileErrorComplete != null) this.DownFileErrorComplete(this); + } + else + { + ErrorFollow.TraceWrite("下载文件出错", "", "60秒后重新下载"); + AutoReset.WaitOne(60000, false); + if (IsRun == false) return; + OnStart(); + return; + } + } + } + catch (Exception ex) + { + try + { + if (fs != null) + { + fs.Close(); + fs = null; + } + if (ns != null) + { + ns.Close(); + ns = null; + } + if (tcp != null) + { + tcp.Close(); + tcp = null; + } + } + catch + { } + + if (this.IsErrorStopDown == true) + { + ErrorFollow.TraceWrite("下载文件出错", ex.StackTrace, ex.Message); + if (this.DownFileErrorComplete != null) this.DownFileErrorComplete(this); + } + else + { + ErrorFollow.TraceWrite("下载文件出错,60秒后重新下载", ex.StackTrace, ex.Message); + AutoReset.WaitOne(60000, false); + if (IsRun == false) return; + OnStart(); + } + } + } + #endregion + + + + } + #endregion + + #region 文件下载信息 + public class NetDownFile + { + public int DownID = 0; + public string SaveFileName = ""; + public string DownFileName = ""; + public long Length = 0; + public string CheckOutCode = ""; + public bool IsDownComplete = false; + public int FileType = 1; //0医生照片下载1文件下载 + + + public void CreateFile() + { + if (File.Exists(SaveFileName) == true) File.Delete(SaveFileName); + } + + public NetDownFile Copy() + { + NetDownFile model = new NetDownFile(); + model.DownID = this.DownID; + model.SaveFileName = this.SaveFileName; + model.DownFileName = this.DownFileName; + model.Length = this.Length; + model.CheckOutCode = this.CheckOutCode; + model.IsDownComplete = this.IsDownComplete; + model.FileType = this.FileType; + return model; + } + } + #endregion + + #region 服务器WebSocket + public class WebSocketService + { + /// + /// 要监控的端口号 + /// + public int Port { get; set; } + /// + /// 空闲超时自动断开或引发心跳包事件 + /// + public int OutTime { get; set; } + /// + /// 重发等待默认30秒后重发 + /// + public int RefshSecond { get; set; } + /// + /// 最大消息等待回包数量(滑动窗口) + /// + public int MaxWaitMsgNumber { get; set; } + public AddressFamily Family { get; set; } + public int MaxSendNumber { get; set; } + public int BufferSize { get; set; } + public bool OutMaxSendNumberCloseConnect { get; set; } + /// + /// 是否长连接(默认长连接) + /// + public bool IsLongConnect { get; set; } + /// + /// 是否启用发送线程 + /// + public bool IsSendThread { get; set; } + /// + /// 数据读取到时发生 + /// + public event Action ReceiveData; + /// + /// 连接完成时发生 + /// + public event Action ConnectSocketComplete; + /// + /// 关闭时发生 + /// + public event Action CloseSocketComplete; + /// + /// 心跳请求事件 + /// + public event Action OutTimeHappen; + /// + /// 发送失败事件 + /// + public event Action SendError; + public event Action ReadDataMessage; + public string DebugIpAddress = ""; + + + TcpSocketListener socketListener = null; + public ServerConnectionPool ListUserSocket = new ServerConnectionPool(); + private AutoResetEvent AutoReset = new AutoResetEvent(false); + public SocketArgsPool socketArgsPool = null; + //BufferPool bufferManager = null; + public bool IsRun = false; + + + public WebSocketService() + { + Family = AddressFamily.InterNetwork; + IsSendThread = false; + IsLongConnect = false; + OutTime = 180; + Port = 10000; + RefshSecond = 10; + MaxWaitMsgNumber = 10; + BufferSize = 1024; + OutMaxSendNumberCloseConnect = false; + } + #region 初始化缓存 + public void Init() + { + //初始化数据接收缓存 + //bufferManager = new BufferPool(MaxConnect * BuffSize, BuffSize); + //bufferManager.InitBuffer(); + + // 声明异步Socket + //SocketAsyncEventArgs readWriteEventArg; + + //for (int i = 0; i < MaxConnect; i++) + //{ + // //初始化异步Socket + // readWriteEventArg = new SocketAsyncEventArgs(); + // // 设备接收数据缓存 + // bufferManager.SetBuffer(readWriteEventArg); + // // 把异步Socket放入集合顶部 + // socketArgsPool.CheckIn(readWriteEventArg); + //} + } + #endregion + #region 开始监控 + public void Start() + { + socketArgsPool = new SocketArgsPool(); + socketListener = new TcpSocketListener(Family, IPAddress.Any, Port, 9999); + socketListener.SocketConnected += socketListener_SocketConnected; + socketListener.Start(); + RunWhileListUserSocket(); + } + #endregion + #region 结束监控 + public void Stop() + { + IsRun = false; + AutoReset.Set(); + socketListener.Stop(); + while (true) + { + var model = ListUserSocket.CheckOut(); + if (model == null) break; + model.Disconnect(); + } + ListUserSocket.Clear(); + System.GC.Collect(); + } + #endregion + #region 结束监控并且发送断开连接消息 + public void Stop(string Data) + { + IsRun = false; + AutoReset.Set(); + socketListener.Stop(); + while (true) + { + var model = ListUserSocket.CheckOut(); + if (model == null) break; + if (string.IsNullOrEmpty(Data) == false) model.SendData(Data); + model.Disconnect(); + } + ListUserSocket.Clear(); + System.GC.Collect(); + } + #endregion + #region 启动发送线程 + void RunWhileListUserSocket() + { + if (this.IsSendThread == true) + { + Thread t1 = new Thread(new ThreadStart(this.WhileListUserSocket)); + t1.Start(); + } + else + { + Thread t1 = new Thread(new ThreadStart(this.WhileListUserSocket2)); + t1.Start(); + } + } + #endregion + #region 关闭设备连接 + public bool CloseDevice(string IpAddress) + { + bool bk = false; + int index = ListUserSocket.Available; + for (int i = 0; i < index; i++) + { + var model = ListUserSocket.CheckOut(); + if (model == null) break; + if (model.IpAddress == IpAddress) + { + model.Disconnect(); + bk = true; + break; + } + ListUserSocket.CheckIn(model); + } + return bk; + } + #endregion + #region 关闭设备连接 + public bool CloseDevice2(string DeviceNo) + { + bool bk = false; + int index = ListUserSocket.Available; + for (int i = 0; i < index; i++) + { + var model = ListUserSocket.CheckOut(); + if (model == null) break; + if (model.DeviceNo == DeviceNo) + { + model.Disconnect(); + bk = true; + break; + } + ListUserSocket.CheckIn(model); + } + return bk; + } + #endregion + #region 关闭设备连接 + public bool CloseDevice3(string DeviceNo, int Port) + { + bool bk = false; + int index = ListUserSocket.Available; + for (int i = 0; i < index; i++) + { + var model = ListUserSocket.CheckOut(); + if (model == null) break; + if (model.DeviceNo == DeviceNo && model.Port == Port) + { + model.Disconnect(); + bk = true; + break; + } + ListUserSocket.CheckIn(model); + } + return bk; + } + #endregion + #region 接受连接请求 + void socketListener_SocketConnected(object sender, SocketEventArgs e) + { + try + { + //CilentConnectProtocol(e); + //return; + e.Socket.SendBufferSize = 32 * 1024; + e.Socket.ReceiveBufferSize = 32 * 1024; + e.Socket.LingerState = new LingerOption(true, 0); + e.Socket.SendTimeout = 60000; + //SocketAsyncEventArgs args = socketArgsPool.CheckOut(); + SocketAsyncEventArgs args = null; + if (args == null) + { + args = new SocketAsyncEventArgs(); + byte[] buffer = new byte[BufferSize]; + args.SetBuffer(buffer, 0, buffer.Length); + } + ServerConnection connection = null; + try + { + connection = new ServerConnection(e.Socket, args); + connection.DataReceived += DataReceived; + connection.CloseSocketed += Disconnected; + } + catch (Exception ex) + { + ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message); + e.Socket.Close(); + //if (connection!=null) connection.Disconnect(); + return; + } + ListUserSocket.CheckIn(connection); + if (this.ConnectSocketComplete != null) this.ConnectSocketComplete(connection); + } + catch (Exception exx) + { + ErrorFollow.TraceWrite(exx.TargetSite.Name, exx.StackTrace, exx.Message); + } + + } + #endregion + #region 读取消息 + void DataReceived(ServerConnection sender, DataEventArgs e) + { + if (e.Data.Length == 0) return; + if (sender.IsWebSocket == false) + { + string handShakeText = Encoding.UTF8.GetString(e.Data, 0, e.Length); + ErrorFollow.TraceWrite("协议", sender.IpAddress, handShakeText); + byte[] buffer = PackHandShakeData(GetSecKeyAccetp(e.Data, e.Length)); + sender.SendData(buffer, 0, buffer.Length); + sender.IsWebSocket = true; + return; + } + sender.PrevTime = DateTime.Now; + string data = AnalyticData(e.Data, e.Length); + if (data == "") + { + if (sender.IpAddress == DebugIpAddress) + { + ErrorFollow.TraceWrite("读取数据", sender.IpAddress, "数据解析失败"); + } + return; + } + else + { + if (sender.IpAddress == DebugIpAddress) + { + ErrorFollow.TraceWrite("读取数据", sender.IpAddress, data); + } + } + if (this.ReceiveData != null) this.ReceiveData(sender, data); + } + #endregion + #region 对方关闭连接 + void Disconnected(ServerConnection model, SocketAsyncEventArgs e) + { + if (model == null || model.Enabled == false) + { + if (model != null) + { + model.DataReceived -= DataReceived; + model.CloseSocketed -= Disconnected; + model.Dispose(); + } + if (this.CloseSocketComplete != null) this.CloseSocketComplete(model); + e.Dispose(); + e = null; + model = null; + } + else + { + model.DataReceived -= DataReceived; + model.CloseSocketed -= Disconnected; + model.Disconnect(); + } + } + #endregion + #region 发送完成时 + void connection_SendCompleted(ServerConnection model) + { + if (this.IsRun == true) ListUserSocket.CheckIn(model); + } + #endregion + #region 轮循连接列表 + void WhileListUserSocket() + { + //bool IsRemoveMessage = false; + IsRun = true; + while (IsRun) + { + try + { + ServerConnection model = ListUserSocket.CheckOut(); + if (model == null) + { + AutoReset.WaitOne(5000, false); + continue; + } + if (model.Enabled == false) continue; + if (model.PrevTime.AddSeconds(this.OutTime) < DateTime.Now) + { + if (this.IsLongConnect == false) + { + ErrorFollow.TraceWrite("服务器检测到" + model.DeviceNo + "无应答", "", "断开对方连接"); + model.Disconnect(); + continue; + } + else + { + //如果是长连接引发,心跳事件 + if (this.OutTimeHappen != null) + { + this.OutTimeHappen(model); + model.PrevTime = DateTime.Now; + ListUserSocket.CheckIn(model); + continue; + } + } + } + //如果服务器是断开连接的,那么不读取主动发送的数据 + if (string.IsNullOrEmpty(model.DeviceNo) == false && model.ListMessage.Count == 0) + { + if (this.ReadDataMessage != null) this.ReadDataMessage(model); + } + if (model.ListMessage.Count > 0) + { + while (model.WaitMsgNumber < this.MaxWaitMsgNumber) + { + SocketMessage Msg = model.GetNextSocketMessage(this.RefshSecond); + if (Msg == null) break; + if (this.MaxSendNumber > 0 && Msg.SendNumber > this.MaxSendNumber) + { + if (OutMaxSendNumberCloseConnect == false) + { + model.EndWaitMsg(Msg.SequenceID); + continue; + } + else + { + model.Disconnect(); + break; + } + } + if (this.Send(model, Msg) == false) + { + if (this.SendError != null) this.SendError(Msg); + break; + } + } + } + if (model.Enabled == false) continue; + if (model.ListMessage.IsEmployMessages == true) model.ListMessage.RemoveEmploy(); + ListUserSocket.CheckIn(model); + AutoReset.WaitOne(10, false); + } + catch (Exception ex) + { + ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message); + } + } + } + #endregion + #region 轮循连接列表 + void WhileListUserSocket2() + { + IsRun = true; + while (IsRun) + { + try + { + ServerConnection model = ListUserSocket.CheckOut(); + if (model == null) + { + AutoReset.WaitOne(30000, false); + continue; + } + if (model.Enabled == false) continue; + if (model.PrevTime.AddSeconds(this.OutTime) < DateTime.Now) + { + if (this.IsLongConnect == false) + { + ErrorFollow.TraceWrite("服务器检测到" + model.DeviceNo + "无应答", "", "断开对方连接"); + model.Disconnect(); + continue; + } + else + { + //如果是长连接引发,心跳事件 + if (this.OutTimeHappen != null) + { + this.OutTimeHappen(model); + model.PrevTime = DateTime.Now; + ListUserSocket.CheckIn(model); + continue; + } + } + } + if (model.Enabled == false) continue; + ListUserSocket.CheckIn(model); + AutoReset.WaitOne(100, false); + } + catch (Exception ex) + { + ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message); + } + } + } + #endregion + #region 发送数据 + public bool Send(ServerConnection model, SocketMessage msg) + { + model.PrevTime = DateTime.Now; + try + { + msg.SendNumber++; + msg.SendTime = DateTime.Now; + bool bk = model.SendData(msg.Bytes, 0, msg.SendLength); + if (bk == false) + { + ErrorFollow.TraceWrite("Send", "", "发送失败断开连接"); + model.Disconnect(); + return false; + } + if (msg.IsRevert == false) + { + EndWaitMsg(model, msg.SequenceID); + } + else + { + if (msg.SendNumber > 1) model.IncrementWaitMsgNumber(); + } + } + catch (Exception ex) + { + ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message); + model.Disconnect(); + return false; + } + return true; + } + #endregion + #region 返回UserSocket + public ServerConnection GetUserSocket(string IpAddress) + { + int index = ListUserSocket.Available; + for (int i = 0; i < index; i++) + { + var model = ListUserSocket.CheckOut(); + if (model == null) break; + if (model.Enabled == false) continue; + if (model.IpAddress == IpAddress) return model; + ListUserSocket.CheckIn(model); + } + return null; + } + #endregion + #region 返回UserSocket + public ServerConnection GetUserSocket2(string DeviceNo) + { + int index = ListUserSocket.Available; + for (int i = 0; i < index; i++) + { + var model = ListUserSocket.CheckOut(); + if (model == null) break; + if (model.Enabled == false) continue; + if (model.DeviceNo == DeviceNo) return model; + ListUserSocket.CheckIn(model); + } + return null; + } + #endregion + #region 返回UserSocket + public ServerConnection GetUserSocket3(string DeviceNo, int Port) + { + int index = ListUserSocket.Available; + for (int i = 0; i < index; i++) + { + var model = ListUserSocket.CheckOut(); + if (model == null) break; + if (model.Enabled == false) continue; + if (model.DeviceNo == DeviceNo && model.Port != Port) return model; + ListUserSocket.CheckIn(model); + } + return null; + } + #endregion + #region 消除已回复消息 + public int EndWaitMsg(ServerConnection model, string SequenceID) + { + SocketMessage msg = model.EndWaitMsg(SequenceID); + if (msg == null) return 0; + return msg.MessageID; + } + #endregion + #region WebSocket专用 + #region 解析客户端连接协议 + public static void CilentConnectProtocol(SocketEventArgs e) + { + + //int len = e.Socket.Available; + byte[] buffer = new byte[5000]; + //if (len == 0) { + // ErrorFollow.TraceWrite("协议", "", "协议未收到"); + // e.Socket.Close(); + // return; + //} + int length = e.Socket.Receive(buffer);//接受客户端握手信息 + string handShakeText = Encoding.UTF8.GetString(buffer, 0, length); + ErrorFollow.TraceWrite("协议", "", handShakeText); + //string[] ss = Regex.Split(handShakeText, System.Environment.NewLine); + //e.Socket.Send(PackHandShakeData(GetSecKeyAccetp(buffer, length))); + } + #endregion + #region 打包握手信息 + /// + /// 打包握手信息 + /// + /// Sec-WebSocket-Accept + /// 数据包 + public static byte[] PackHandShakeData(string secKeyAccept) + { + var responseBuilder = new StringBuilder(); + responseBuilder.Append("HTTP/1.1 101 Switching Protocols" + Environment.NewLine); + responseBuilder.Append("Connection: Upgrade" + Environment.NewLine); + responseBuilder.Append("Upgrade: WebSocket" + Environment.NewLine); + responseBuilder.Append("Sec-WebSocket-Accept: " + secKeyAccept + Environment.NewLine + Environment.NewLine); + //responseBuilder.Append("Sec-WebSocket-Protocol: chat" + Environment.NewLine ); + //responseBuilder.Append("" + Environment.NewLine); + //responseBuilder.Append("" + Environment.NewLine + Environment.NewLine); + + //responseBuilder.Append("Server: beetle websocket server" + Environment.NewLine); + //responseBuilder.Append("Date: " + DateTime.Now.ToString("r") + Environment.NewLine); + + + //responseBuilder.Append("Sec-WebSocket-Accept: " + secKeyAccept + Environment.NewLine + Environment.NewLine); + ////如果把上一行换成下面两行,才是thewebsocketprotocol-17协议,但居然握手不成功,目前仍没弄明白! + ////responseBuilder.Append("Sec-WebSocket-Accept: " + secKeyAccept + Environment.NewLine); + ////responseBuilder.Append("Sec-WebSocket-Protocol: chat" + Environment.NewLine); + + + return Encoding.UTF8.GetBytes(responseBuilder.ToString()); + } + #endregion + #region 数据进行编码 + /// + /// 生成Sec-WebSocket-Accept + /// + /// 客户端握手信息 + /// Sec-WebSocket-Accept + public static string GetSecKeyAccetp(byte[] handShakeBytes, int bytesLength) + { + string handShakeText = Encoding.UTF8.GetString(handShakeBytes, 0, bytesLength); + string key = string.Empty; + Regex r = new Regex(@"Sec\-WebSocket\-Key:(.*?)\r\n"); + Match m = r.Match(handShakeText); + if (m.Groups.Count != 0) + { + key = Regex.Replace(m.Value, @"Sec\-WebSocket\-Key:(.*?)\r\n", "$1").Trim(); + } + byte[] encryptionString = SHA1.Create().ComputeHash(Encoding.ASCII.GetBytes(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11")); + return Convert.ToBase64String(encryptionString); + } + #endregion + #region 解析客户端数据包 + /// + /// 解析客户端数据包 + /// + /// 服务器接收的数据包 + /// 有效数据长度 + /// + public static string AnalyticData(byte[] recBytes, int recByteLength) + { + if (recByteLength < 2) { return string.Empty; } + + bool fin = (recBytes[0] & 0x80) == 0x80; // 1bit,1表示最后一帧 + if (!fin) + { + return string.Empty;// 超过一帧暂不处理 + } + + byte[] payload_data; + bool mask_flag = (recBytes[1] & 0x80) == 0x80; // 是否包含掩码 + int payload_len = recBytes[1] & 0x7F; // 数据长度 + if (payload_len == 0) return ""; + byte[] masks = new byte[4]; + + if (payload_len == 126) + { + Array.Copy(recBytes, 4, masks, 0, 4); + payload_len = (UInt16)(recBytes[2] << 8 | recBytes[3]); + payload_data = new byte[payload_len]; + Array.Copy(recBytes, 8, payload_data, 0, payload_len); + } + else if (payload_len == 127) + { + Array.Copy(recBytes, 10, masks, 0, 4); + byte[] uInt64Bytes = new byte[8]; + for (int i = 0; i < 8; i++) + { + uInt64Bytes[i] = recBytes[9 - i]; + } + UInt64 len = BitConverter.ToUInt64(uInt64Bytes, 0); + + payload_data = new byte[len]; + for (UInt64 i = 0; i < len; i++) + { + payload_data[i] = recBytes[i + 14]; + } + } + else + { + Array.Copy(recBytes, 2, masks, 0, 4); + payload_data = new byte[payload_len]; + Array.Copy(recBytes, 6, payload_data, 0, payload_len); + } + //解码 + if (mask_flag == true) + { + for (var i = 0; i < payload_len; i++) + { + payload_data[i] = (byte)(payload_data[i] ^ masks[i % 4]); + } + } + return Encoding.UTF8.GetString(payload_data); + } + #endregion + #region 打包服务器数据 + /// + /// 打包服务器数据 + /// + /// 数据 + /// 数据包 + 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 & 0xFF); + contentBytes[3] = (byte)(temp.Length >> 8 & 0xFF); + Array.Copy(temp, 0, contentBytes, 4, temp.Length); + } + else + { + contentBytes = new byte[temp.Length + 10]; + contentBytes[0] = 0x81; + contentBytes[1] = 127; + contentBytes[2] = 0; + contentBytes[3] = 0; + contentBytes[4] = 0; + contentBytes[5] = 0; + contentBytes[6] = (byte)(temp.Length >> 24); + contentBytes[7] = (byte)(temp.Length >> 16); + contentBytes[8] = (byte)(temp.Length >> 8); + contentBytes[9] = (byte)(temp.Length & 0xFF); + Array.Copy(temp, 0, contentBytes, 10, temp.Length); + } + return contentBytes; + } + #endregion + #endregion + + } + #endregion + #region 客户端WebSocket + public class WebSocketClient + { + private WebSocket websocket = null; + private bool IsRun = false; + public bool IsConnect = false; //连接状态 + private int SequenceID = 1; + private int CloseReConnectTime = 0; + private DateTime PrevTime = DateTime.Today; + private AutoResetEvent AutoReset = new AutoResetEvent(false); + + public string DeviceNo { get; set; } + public string IpAddress { get; set; } + public int Port { get; set; } + /// + /// 超出多少秒没有数据通讯后连接自动断开 + /// + public int OutTime { get; set; } + /// + /// 断线重连间隔 + /// + public int ReconnectInterval { get; set; } + public SocketMessages ListMessage { get; set; } + public int RefshSecond { get; set; } + + public event Action CloseSocketComplete; //连接关闭时发生 + public event Action ConnectSocketComplete; //连接完成时发生 + public event Action OutTimeHappen; + public event Action ReceiveData; + public int WaitMsgNumber = 0; + public int MaxWaitMsgNumber = 16; + public int MaxSendNumber = 0; + + public WebSocketClient() + { + ListMessage = new SocketMessages(); + RefshSecond = 10; + } + #region 启动监控 + public void Start() + { + IsRun = true; + websocket = new WebSocket("ws://" + IpAddress + ":" + Port); + websocket.OnMessage += Websocket_OnMessage; + websocket.OnOpen += Websocket_OnOpen; + websocket.OnClose += Websocket_OnClose; + websocket.OnError += Websocket_OnError; + + Thread t1 = new Thread(new ThreadStart(this.WhileListUserSocket)); + t1.Name = "ClientSocket"; + t1.Start(); + } + + private void Websocket_OnError(object sender, WebSocketSharp.ErrorEventArgs e) + { + ErrorFollow.TraceWrite("WebSocket错误", "", e.Message); + } + #endregion + #region 停止监控 + public void Stop() + { + try + { + IsRun = false; + websocket.CloseAsync(); + } + catch (Exception ex) + { + ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message); + } + + } + #endregion + #region 关闭监控 + public void Disconnect() + { + websocket.Close(); + } + #endregion + #region 连接完成时 + private void Websocket_OnOpen(object sender, EventArgs e) + { + IsConnect = true; + PrevTime = DateTime.Now; + if (this.ConnectSocketComplete != null) this.ConnectSocketComplete(); + } + #endregion + #region 连接关闭时 + private void Websocket_OnClose(object sender, CloseEventArgs e) + { + IsConnect = false; + PrevTime = DateTime.Now; + if (this.CloseSocketComplete != null) this.CloseSocketComplete(); + } + #endregion + #region 发送数据 + public bool SendData(string msg) + { + try + { + if (IsConnect == false) return false; + PrevTime = DateTime.Now; + websocket.Send(msg); + return true; + } + catch (Exception ex) + { + ErrorFollow.TraceWrite("发送数据失败", ex.StackTrace, ex.Message); + } + return false; + } + #endregion + #region 接收消息 + private void Websocket_OnMessage(object sender, MessageEventArgs e) + { + PrevTime = DateTime.Now; + if (this.ReceiveData != null) this.ReceiveData(e.Data); + } + #endregion + #region 轮循消息列表 + void WhileListUserSocket() + { + while (IsRun) + { + try + { + if (IsConnect == false) + { + if (PrevTime.AddSeconds(this.ReconnectInterval) < DateTime.Now) + { + //超时重连 + ErrorFollow.TraceWrite("连接", "", "断线重连"); + websocket.Connect(); + } + AutoReset.WaitOne(1000); + if (IsRun == false) return; + continue; + } + if (PrevTime.AddSeconds(this.OutTime) < DateTime.Now) + { + //如果是长连接引发,心跳事件 + if (this.OutTimeHappen != null) + { + this.OutTimeHappen(); + PrevTime = DateTime.Now; + continue; + } + } + if (ListMessage.Count > 0) + { + //ErrorFollow.TraceWrite("发送数据", "", "数量:" + UseSocket.ListMessage.Count + ",等待数:" + UseSocket.WaitMsgNumber); + while (true) + { + SocketMessage Msg = GetNextSocketMessage(this.RefshSecond); + if (Msg == null) break; + if (WaitMsgNumber >= this.MaxWaitMsgNumber) break; + if (this.MaxSendNumber > 0 && Msg.SendNumber > this.MaxSendNumber) + { + EndWaitMsg(Msg.SequenceID); + continue; + } + if (this.SendData(Msg.Data) == false) break; + IncrementWaitMsgNumber(); + AutoReset.WaitOne(10, false); + } + } + if (IsRun == true) AutoReset.WaitOne(1000, false); + } + catch (Exception ex) + { + ErrorFollow.TraceWrite("线程循环错误5秒后重连;"+ex.TargetSite.Name, ex.StackTrace, ex.Message); + ReConnect(); + AutoReset.WaitOne(5000, false); + } + } + + } + #endregion + #region 断线重连失败时调用 + void ReConnect() + { + try + { + websocket.OnMessage -= Websocket_OnMessage; + websocket.OnOpen -= Websocket_OnOpen; + websocket.OnClose -= Websocket_OnClose; + websocket.OnError -= Websocket_OnError; + websocket.Close(); + websocket = null; + } + catch (Exception ex) + { + ErrorFollow.TraceWrite("断线重连关闭原Socket", ex.StackTrace, ex.Message); + } + try + { + websocket = new WebSocket("ws://" + IpAddress + ":" + Port); + websocket.OnMessage += Websocket_OnMessage; + websocket.OnOpen += Websocket_OnOpen; + websocket.OnClose += Websocket_OnClose; + websocket.OnError += Websocket_OnError; + } + catch (Exception ex) + { + ErrorFollow.TraceWrite("断线重连初始化WebSocket错误", ex.StackTrace, ex.Message); + } + + } + #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(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 Dispose() + { + ListMessage.Clear(); + ListMessage = null; + } + #endregion + + } + #endregion + #region 客户端WebSocket(不使用) + public class WebSocketClient2 + { + private ClientSocket websocket = null; + + private bool IsRun = false; + public bool IsConnect = false; //连接状态 + private int SequenceID = 1; + private int CloseReConnectTime = 0; + private DateTime PrevTime = DateTime.Today; + private AutoResetEvent AutoReset = new AutoResetEvent(false); + + public string DeviceNo { get; set; } + public string IpAddress { get; set; } + public int Port { get; set; } + /// + /// 超出多少秒没有数据通讯后连接自动断开 + /// + public int OutTime { get; set; } + /// + /// 断线重连间隔 + /// + public int ReconnectInterval { get; set; } + public SocketMessages ListMessage { get; set; } + public int RefshSecond { get; set; } + public int WaitMsgNumber = 0; + public int MaxWaitMsgNumber = 16; + public int MaxSendNumber = 0; + + + public event Action LoginComplete; //登陆完成时 + public event Action CloseSocketComplete; //连接关闭时发生 + public event Action ConnectSocketComplete; //连接完成时发生 + public event Action OutTimeHappen; + public event Action ReceiveData; + + public WebSocketClient2(String ServerUrl) + { + ServerUrl = ServerUrl.Substring(5); + string[] ss = ServerUrl.Split(':'); + this.IpAddress = ss[0]; + this.Port = Convert.ToInt32(ss[1]); + websocket = new ClientSocket(); + websocket.BuffSize = 32 * 1024; + websocket.RefshSecond = 10; + websocket.MaxWaitMsgNumber = 16; + websocket.OutTime = 60; + websocket.ReceiveData += ser_ReceiveData; + websocket.ConnectSocketComplete += ser_ConnectSocketComplete; + websocket.CloseSocketComplete += ser_CloseSocketComplete; + websocket.OutTimeHappen += ser_OutTimeHappen; + } + #region 服务器Socket关闭时发生 + private void ser_CloseSocketComplete(ServerConnection model) + { + if (this.CloseSocketComplete != null) this.CloseSocketComplete(); + } + #endregion + #region 服务器Socket连接完成时发生 + private void ser_ConnectSocketComplete(ServerConnection model) + { + string msg = @" +GET / HTTP/1.1 +Host: " + IpAddress + @":" + Port + @" +Upgrade: WebSocket +Connection: Upgrade +Sec-WebSocket-Key: irNFMwBYbxtuzrT0GWajwg== +Sec-WebSocket-Version: 13 +"; + model.SendData(msg); + if (this.ConnectSocketComplete != null) this.ConnectSocketComplete(); + } + #endregion + #region 服务器读取到数据时发生 + private void ser_ReceiveData(ServerConnection sender, DataEventArgs e) + { + if (e.Data.Length == 0) return; + if (sender.IsWebSocket == false) + { + sender.IsWebSocket = true; + return; + } + sender.PrevTime = DateTime.Now; + string data = AnalyticData(e.Data, e.Length); + if (data == "") return; + if (this.ReceiveData != null) this.ReceiveData(sender, data); + } + #endregion + #region 发送心跳 + void ser_OutTimeHappen(ServerConnection e) + { + if (this.OutTimeHappen != null) this.OutTimeHappen(e); + } + #endregion + #region 解析客户端数据包 + /// + /// 解析客户端数据包 + /// + /// 服务器接收的数据包 + /// 有效数据长度 + /// + public static string AnalyticData(byte[] recBytes, int recByteLength) + { + if (recByteLength < 2) { return string.Empty; } + + bool fin = (recBytes[0] & 0x80) == 0x80; // 1bit,1表示最后一帧 + if (!fin) + { + return string.Empty;// 超过一帧暂不处理 + } + + byte[] payload_data; + bool mask_flag = (recBytes[1] & 0x80) == 0x80; // 是否包含掩码 + int payload_len = recBytes[1] & 0x7F; // 数据长度 + if (payload_len == 0) return ""; + byte[] masks = new byte[4]; + + if (payload_len == 126) + { + Array.Copy(recBytes, 4, masks, 0, 4); + payload_len = (UInt16)(recBytes[2] << 8 | recBytes[3]); + payload_data = new byte[payload_len]; + Array.Copy(recBytes, 8, payload_data, 0, payload_len); + + } + else if (payload_len == 127) + { + Array.Copy(recBytes, 10, masks, 0, 4); + byte[] uInt64Bytes = new byte[8]; + for (int i = 0; i < 8; i++) + { + uInt64Bytes[i] = recBytes[9 - i]; + } + UInt64 len = BitConverter.ToUInt64(uInt64Bytes, 0); + + payload_data = new byte[len]; + for (UInt64 i = 0; i < len; i++) + { + payload_data[i] = recBytes[i + 14]; + } + } + else + { + Array.Copy(recBytes, 2, masks, 0, 4); + payload_data = new byte[payload_len]; + Array.Copy(recBytes, 6, payload_data, 0, payload_len); + } + //解码 + if (mask_flag == true) + { + for (var i = 0; i < payload_len; i++) + { + payload_data[i] = (byte)(payload_data[i] ^ masks[i % 4]); + } + } + return Encoding.UTF8.GetString(payload_data); + } + #endregion + #region 打包服务器数据 + /// + /// 打包服务器数据 + /// + /// 数据 + /// 数据包 + 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 & 0xFF); + contentBytes[3] = (byte)(temp.Length >> 8 & 0xFF); + Array.Copy(temp, 0, contentBytes, 4, temp.Length); + } + else + { + contentBytes = new byte[temp.Length + 10]; + contentBytes[0] = 0x81; + contentBytes[1] = 127; + contentBytes[2] = 0; + contentBytes[3] = 0; + contentBytes[4] = 0; + contentBytes[5] = 0; + contentBytes[6] = (byte)(temp.Length >> 24); + contentBytes[7] = (byte)(temp.Length >> 16); + contentBytes[8] = (byte)(temp.Length >> 8); + contentBytes[9] = (byte)(temp.Length & 0xFF); + Array.Copy(temp, 0, contentBytes, 10, temp.Length); + } + return contentBytes; + } + #endregion + #region 启动监控 + public void Start() + { + websocket.IpAddress = IpAddress; + websocket.Port = Port; + websocket.Start(); + + Thread t1 = new Thread(new ThreadStart(this.WhileListUserSocket)); + t1.Name = "WebSocketClient2"; + t1.Start(); + } + #endregion + #region 停止监控 + public void Stop() + { + websocket.Stop(); + } + #endregion + #region 发送数据 + public void SendData(string msg) + { + byte[] bytes = PackData(msg); + websocket.UseSocket.SendData(bytes, 0, bytes.Length); + } + #endregion + #region 轮循消息列表 + void WhileListUserSocket() + { + //while (IsRun) + //{ + // try + // { + // if (IsConnect == false) + // { + // if (PrevTime.AddSeconds(this.ReconnectInterval) < DateTime.Now) + // { + // //超时重连 + // websocket.ConnectAsync(); + // } + // else + // { + // AutoReset.WaitOne(1000); + // } + // if (IsRun == false) return; + // continue; + // } + // if (PrevTime.AddSeconds(this.OutTime) < DateTime.Now) + // { + // //如果是长连接引发,心跳事件 + // if (this.OutTimeHappen != null) + // { + // this.OutTimeHappen(); + // PrevTime = DateTime.Now; + // continue; + // } + // } + // if (ListMessage.Count > 0) + // { + // //ErrorFollow.TraceWrite("发送数据", "", "数量:" + UseSocket.ListMessage.Count + ",等待数:" + UseSocket.WaitMsgNumber); + // while (true) + // { + // SocketMessage Msg = GetNextSocketMessage(this.RefshSecond); + // if (Msg == null) break; + // if (WaitMsgNumber >= this.MaxWaitMsgNumber) break; + // if (this.MaxSendNumber > 0 && Msg.SendNumber > this.MaxSendNumber) + // { + // EndWaitMsg(Msg.SequenceID); + // continue; + // } + // if (this.SendData(Msg.Data) == false) break; + // IncrementWaitMsgNumber(); + // AutoReset.WaitOne(10, false); + // } + // } + // if (IsRun == true) AutoReset.WaitOne(1000, false); + // } + // catch (Exception ex) + // { + // ErrorFollow.TraceWrite("线程循环错误", "", "关闭连接"); + // Stop(); + // ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message); + // } + //} + + } + #endregion + } + #endregion + + #region 服务器HttpSocket + public class HttpSocketService + { + /// + /// 要监控的端口号 + /// + public int Port { get; set; } + /// + /// 空闲超时自动断开或引发心跳包事件 + /// + public int OutTime { get; set; } + /// + /// 重发等待默认30秒后重发 + /// + public int RefshSecond { get; set; } + /// + /// 最大消息等待回包数量(滑动窗口) + /// + public int MaxWaitMsgNumber { get; set; } + public AddressFamily Family { get; set; } + public int MaxSendNumber { get; set; } + public int BufferSize { get; set; } + public bool OutMaxSendNumberCloseConnect { get; set; } + /// + /// 是否长连接(默认长连接) + /// + public bool IsLongConnect { get; set; } + /// + /// 是否启用发送线程 + /// + public bool IsSendThread { get; set; } + /// + /// 数据读取到时发生 + /// + public event Action ReceiveData; + /// + /// 连接完成时发生 + /// + public event Action ConnectSocketComplete; + /// + /// 关闭时发生 + /// + public event Action CloseSocketComplete; + /// + /// 心跳请求事件 + /// + public event Action OutTimeHappen; + /// + /// 发送失败事件 + /// + public event Action SendError; + public event Action ReadDataMessage; + public string DebugIpAddress = ""; + + + TcpSocketListener socketListener = null; + private AutoResetEvent AutoReset = new AutoResetEvent(false); + //BufferPool bufferManager = null; + public bool IsRun = false; + + + public HttpSocketService() + { + Family = AddressFamily.InterNetwork; + IsSendThread = false; + IsLongConnect = false; + OutTime = 180; + Port = 10000; + RefshSecond = 10; + MaxWaitMsgNumber = 10; + BufferSize = 1024; + OutMaxSendNumberCloseConnect = false; + } + #region 初始化缓存 + public void Init() + { + //初始化数据接收缓存 + //bufferManager = new BufferPool(MaxConnect * BuffSize, BuffSize); + //bufferManager.InitBuffer(); + + // 声明异步Socket + //SocketAsyncEventArgs readWriteEventArg; + + //for (int i = 0; i < MaxConnect; i++) + //{ + // //初始化异步Socket + // readWriteEventArg = new SocketAsyncEventArgs(); + // // 设备接收数据缓存 + // bufferManager.SetBuffer(readWriteEventArg); + // // 把异步Socket放入集合顶部 + // socketArgsPool.CheckIn(readWriteEventArg); + //} + } + #endregion + #region 开始监控 + public void Start() + { + socketListener = new TcpSocketListener(Family, IPAddress.Any, Port, 9999); + socketListener.SocketConnected += socketListener_SocketConnected; + socketListener.Start(); + } + #endregion + #region 结束监控 + public void Stop() + { + IsRun = false; + AutoReset.Set(); + socketListener.Stop(); + System.GC.Collect(); + } + #endregion + #region 接受连接请求 + void socketListener_SocketConnected(object sender, SocketEventArgs e) + { + try + { + //CilentConnectProtocol(e); + //return; + e.Socket.SendBufferSize = 32 * 1024; + e.Socket.ReceiveBufferSize = 32 * 1024; + e.Socket.LingerState = new LingerOption(true, 0); + e.Socket.SendTimeout = 60000; + //SocketAsyncEventArgs args = socketArgsPool.CheckOut(); + SocketAsyncEventArgs args = null; + if (args == null) + { + args = new SocketAsyncEventArgs(); + byte[] buffer = new byte[BufferSize]; + args.SetBuffer(buffer, 0, buffer.Length); + } + ServerConnection connection = null; + try + { + connection = new ServerConnection(e.Socket, args); + connection.DataReceived += DataReceived; + connection.CloseSocketed += Disconnected; + } + catch (Exception ex) + { + ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message); + e.Socket.Close(); + //if (connection!=null) connection.Disconnect(); + return; + } + if (this.ConnectSocketComplete != null) this.ConnectSocketComplete(connection); + } + catch (Exception exx) + { + ErrorFollow.TraceWrite(exx.TargetSite.Name, exx.StackTrace, exx.Message); + } + + } + #endregion + #region 读取消息 + void DataReceived(ServerConnection sender, DataEventArgs e) + { + if (e.Data.Length == 0) return; + string handShakeText = Encoding.UTF8.GetString(e.Data, 0, e.Length); + ErrorFollow.TraceWrite("协议", sender.IpAddress, handShakeText); + //if (this.ReceiveData != null) this.ReceiveData(sender, data); + } + #endregion + #region 对方关闭连接 + void Disconnected(ServerConnection model, SocketAsyncEventArgs e) + { + if (model == null || model.Enabled == false) + { + if (model != null) + { + model.DataReceived -= DataReceived; + model.CloseSocketed -= Disconnected; + } + if (this.CloseSocketComplete != null) this.CloseSocketComplete(model); + e.Dispose(); + e = null; + model = null; + } + else + { + model.Disconnect(); + } + } + #endregion + #region 发送完成时 + void connection_SendCompleted(ServerConnection model) + { + + } + #endregion + #region 发送数据 + public bool Send(ServerConnection model, SocketMessage msg) + { + model.PrevTime = DateTime.Now; + try + { + msg.SendNumber++; + msg.SendTime = DateTime.Now; + bool bk = model.SendData(msg.Bytes, 0, msg.SendLength); + if (bk == false) + { + ErrorFollow.TraceWrite("Send", "", "发送失败断开连接"); + model.Disconnect(); + return false; + } + if (msg.IsRevert == false) + { + EndWaitMsg(model, msg.SequenceID); + } + else + { + if (msg.SendNumber > 1) model.IncrementWaitMsgNumber(); + } + } + catch (Exception ex) + { + ErrorFollow.TraceWrite(ex.TargetSite.Name, ex.StackTrace, ex.Message); + model.Disconnect(); + return false; + } + return true; + } + #endregion + #region 消除已回复消息 + public int EndWaitMsg(ServerConnection model, string SequenceID) + { + SocketMessage msg = model.EndWaitMsg(SequenceID); + if (msg == null) return 0; + return msg.MessageID; + } + #endregion + + + } + #endregion + +} diff --git a/基础类库/HuizhongLibrary/Network/UdpSocket.cs b/基础类库/HuizhongLibrary/Network/UdpSocket.cs new file mode 100644 index 0000000..09ee7e7 --- /dev/null +++ b/基础类库/HuizhongLibrary/Network/UdpSocket.cs @@ -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 SocketBuffer = new List(); //网络数据缓存 + private AutoResetEvent AutoReset = new AutoResetEvent(false); + public event Action ReceiveDataEvent; //读取到数据时发生 + public event Action CloseEvent; //关闭时发生 + public event Action ConnectEvent; //连接客户端时发生 + + public List ListMessage = new List(); + public List ListUserSocket = new List(); + + 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 SocketBuffer = new List(); + public List ListMessage = new List(); + 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 SocketBuffer = new List(); //网络数据缓存 + private AutoResetEvent AutoReset = new AutoResetEvent(false); + public event Action ReceiveDataEvent; //读取到数据时发生 + public event ThreadStart LoginEvent; //要求登陆时发生 + public List ListMessage = new List(); + + + 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 +} diff --git a/基础类库/HuizhongLibrary/PageMessageBox.cs b/基础类库/HuizhongLibrary/PageMessageBox.cs new file mode 100644 index 0000000..e89fa1a --- /dev/null +++ b/基础类库/HuizhongLibrary/PageMessageBox.cs @@ -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 +{ + /// + /// 弹出窗口类 + /// + public class MessageBox + { + + /// + /// 弹出一个新窗体,Property参数功能[yes为启用,no为不启用](height=窗口高度,width=窗口宽度,top=窗口距离屏幕上方的象素值,left=窗口距离屏幕左侧的象素值,toolbar=是否显示工具栏,menubar=是否显示菜单栏,scrollbars=是否显示滚动条,resizable=是否允许改变窗口大小,location=是否显示地址栏,status=是否显示状态栏内的信息) + /// + /// 需要输出的窗体 + /// 要显示的窗体文件名 + /// 窗体名称 + public static void OpenForm(Page page, string FormFileName, string FormName, string Property) + { + page.ClientScript.RegisterStartupScript(page.GetType(),"aa", ""); + + } + + /// + ///1.dialogHeight :对话框高度,不小于100px,IE4中dialogHeight 和 dialogWidth 默认的单位是em,而IE5中是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 } [IE5+]:是否可被改变大小。默认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。 + /// + /// 需要输出的窗体 + /// 要显示的窗体文件名 + /// 参数(对话框通过window.dialogArguments来取得传递进来的参数) + /// 窗体属性 + public static void OpenDialog(Page page, string FormFileName, string Arguments, string Property) + { + page.ClientScript.RegisterStartupScript(page.GetType(), "aa", ""); + + } + + + /// + /// 弹出一个新窗体,Property参数功能[yes为启用,no为不启用](height=窗口高度,width=窗口宽度,top=窗口距离屏幕上方的象素值,left=窗口距离屏幕左侧的象素值,toolbar=是否显示工具栏,menubar=是否显示菜单栏,scrollbars=是否显示滚动条,resizable=是否允许改变窗口大小,location=是否显示地址栏,status=是否显示状态栏内的信息) + /// + /// 需要输出的窗体 + /// 要显示的窗体文件名 + /// 窗体名称 + /// 窗体参数 + /// 要传递的变量名称 + /// 变量的值 + public static void OpenForm(Page page, string FormFileName, string FormName, string Property, string ValueName, string Value) + { + page.ClientScript.RegisterStartupScript(page.GetType(), "aa", ""); + } + + /// + //1.dialogHeight :对话框高度,不小于100px,IE4中dialogHeight 和 dialogWidth 默认的单位是em,而IE5中是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 } [IE5+]:是否可被改变大小。默认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。 + /// + /// 需要输出的窗体 + /// 要显示的窗体文件名 + /// 参数(对话框通过window.dialogArguments来取得传递进来的参数) + /// 窗体属性 + public static void OpenDialog(Page page, string FormFileName, string Arguments, string Property, string ValueName, string Value) + { + page.ClientScript.RegisterStartupScript(page.GetType(), "aa", ""); + + } + + /// + /// 弹出一个新窗体,Property参数功能[yes为启用,no为不启用](height=窗口高度,width=窗口宽度,top=窗口距离屏幕上方的象素值,left=窗口距离屏幕左侧的象素值,toolbar=是否显示工具栏,menubar=是否显示菜单栏,scrollbars=是否显示滚动条,resizable=是否允许改变窗口大小,location=是否显示地址栏,status=是否显示状态栏内的信息) + /// + /// 需要输出的窗体 + /// 要显示的窗体文件名 + /// 窗体名称 + /// 窗体参数 + /// 要传递的变量名称 + /// 变量的值 + 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", ""); + } + + /// + //1.dialogHeight :对话框高度,不小于100px,IE4中dialogHeight 和 dialogWidth 默认的单位是em,而IE5中是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 } [IE5+]:是否可被改变大小。默认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。 + /// + /// 需要输出的窗体 + /// 要显示的窗体文件名 + /// 参数(对话框通过window.dialogArguments来取得传递进来的参数) + /// 窗体属性 + 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", ""); + + } + + /// + /// 弹出一个新窗体,Property参数功能[yes为启用,no为不启用](height=窗口高度,width=窗口宽度,top=窗口距离屏幕上方的象素值,left=窗口距离屏幕左侧的象素值,toolbar=是否显示工具栏,menubar=是否显示菜单栏,scrollbars=是否显示滚动条,resizable=是否允许改变窗口大小,location=是否显示地址栏,status=是否显示状态栏内的信息) + /// + /// 需要输出的窗体 + /// 要显示的窗体文件名 + /// 窗体名称 + /// 窗体参数 + /// 要传递的变量名称 + /// 变量的值 + 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", ""); + } + + /// + //1.dialogHeight :对话框高度,不小于100px,IE4中dialogHeight 和 dialogWidth 默认的单位是em,而IE5中是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 } [IE5+]:是否可被改变大小。默认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。 + /// + /// 需要输出的窗体 + /// 要显示的窗体文件名 + /// 参数(对话框通过window.dialogArguments来取得传递进来的参数) + /// 窗体属性 + 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", ""); + + } + + + /// + /// 弹出一个新窗体,Property参数功能[yes为启用,no为不启用](height=窗口高度,width=窗口宽度,top=窗口距离屏幕上方的象素值,left=窗口距离屏幕左侧的象素值,toolbar=是否显示工具栏,menubar=是否显示菜单栏,scrollbars=是否显示滚动条,resizable=是否允许改变窗口大小,location=是否显示地址栏,status=是否显示状态栏内的信息) + /// + /// 需要输出的窗体 + /// 要显示的窗体文件名 + /// 窗体名称 + /// 窗体参数 + /// 要传递的变量名称 + /// 变量的值 + 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", ""); + } + + /// + //1.dialogHeight :对话框高度,不小于100px,IE4中dialogHeight 和 dialogWidth 默认的单位是em,而IE5中是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 } [IE5+]:是否可被改变大小。默认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。 + /// + /// 需要输出的窗体 + /// 要显示的窗体文件名 + /// 参数(对话框通过window.dialogArguments来取得传递进来的参数) + /// 窗体属性 + 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", ""); + + } + + + /// + /// 弹出一个新窗体,Property参数功能[yes为启用,no为不启用](height=窗口高度,width=窗口宽度,top=窗口距离屏幕上方的象素值,left=窗口距离屏幕左侧的象素值,toolbar=是否显示工具栏,menubar=是否显示菜单栏,scrollbars=是否显示滚动条,resizable=是否允许改变窗口大小,location=是否显示地址栏,status=是否显示状态栏内的信息) + /// + /// 需要输出的窗体 + /// 要显示的窗体文件名 + /// 窗体名称 + /// 窗体参数 + /// 要传递的变量名称 + /// 变量的值 + 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", ""); + } + + /// + //1.dialogHeight :对话框高度,不小于100px,IE4中dialogHeight 和 dialogWidth 默认的单位是em,而IE5中是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 } [IE5+]:是否可被改变大小。默认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。 + /// + /// 需要输出的窗体 + /// 要显示的窗体文件名 + /// 参数(对话框通过window.dialogArguments来取得传递进来的参数) + /// 窗体属性 + 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", ""); + + } + + /// + /// 弹出一个新窗体,Property参数功能[yes为启用,no为不启用](height=窗口高度,width=窗口宽度,top=窗口距离屏幕上方的象素值,left=窗口距离屏幕左侧的象素值,toolbar=是否显示工具栏,menubar=是否显示菜单栏,scrollbars=是否显示滚动条,resizable=是否允许改变窗口大小,location=是否显示地址栏,status=是否显示状态栏内的信息) + /// + /// 需要输出的窗体 + /// 要显示的窗体文件名 + /// 窗体名称 + /// 窗体参数 + /// 要传递的变量名称 + /// 变量的值 + 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", ""); + } + + /// + //1.dialogHeight :对话框高度,不小于100px,IE4中dialogHeight 和 dialogWidth 默认的单位是em,而IE5中是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 } [IE5+]:是否可被改变大小。默认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。 + /// + /// 需要输出的窗体 + /// 要显示的窗体文件名 + /// 参数(对话框通过window.dialogArguments来取得传递进来的参数) + /// 窗体属性 + 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", ""); + + } + + /// + /// 弹出一个新窗体,Property参数功能[yes为启用,no为不启用](height=窗口高度,width=窗口宽度,top=窗口距离屏幕上方的象素值,left=窗口距离屏幕左侧的象素值,toolbar=是否显示工具栏,menubar=是否显示菜单栏,scrollbars=是否显示滚动条,resizable=是否允许改变窗口大小,location=是否显示地址栏,status=是否显示状态栏内的信息) + /// + /// 需要输出的窗体 + /// 要显示的窗体文件名 + /// 窗体名称 + /// 窗体参数 + /// 要传递的变量名称 + /// 变量的值 + 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", ""); + } + + + /// + //1.dialogHeight :对话框高度,不小于100px,IE4中dialogHeight 和 dialogWidth 默认的单位是em,而IE5中是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 } [IE5+]:是否可被改变大小。默认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。 + /// + /// 需要输出的窗体 + /// 要显示的窗体文件名 + /// 参数(对话框通过window.dialogArguments来取得传递进来的参数) + /// 窗体属性 + 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", ""); + + } + + /// + /// 弹出一个确定按钮对话框 + /// + public static void Show(Page page, string msg) + { + if (page.Session["CodeTest"] != null) return; + page.ClientScript.RegisterStartupScript(page.GetType(), "b1", ""); + } + /// + /// 弹出一个确定按钮对话框 + /// + 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", ""); + ctrl.Focus(); + } + /// + /// 执行JS代码 + /// + public static void RegisterStartupScript(Page page, string script) + { + if (page.Session["CodeTest"] != null) return; + page.ClientScript.RegisterStartupScript(page.GetType(), "b3", ""); + } + + /// + /// 弹出一个确定与取消按钮对话框 + /// + 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, ""); + } + + }//类结束 +} diff --git a/基础类库/HuizhongLibrary/PhonePay/AliPay.cs b/基础类库/HuizhongLibrary/PhonePay/AliPay.cs new file mode 100644 index 0000000..d3f14be --- /dev/null +++ b/基础类库/HuizhongLibrary/PhonePay/AliPay.cs @@ -0,0 +1,11 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace HuizhongLibrary.PhonePay +{ + public class AliPay + { + } +} diff --git a/基础类库/HuizhongLibrary/PhonePay/WeiXinPay.cs b/基础类库/HuizhongLibrary/PhonePay/WeiXinPay.cs new file mode 100644 index 0000000..e20bb8d --- /dev/null +++ b/基础类库/HuizhongLibrary/PhonePay/WeiXinPay.cs @@ -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() + { + + } + + /// + /// openid用于调用统一下单接口 + /// + public string openid { get; set; } + + /// + /// access_token用于获取收货地址js函数入口参数 + /// + public string access_token { get; set; } + + /// + /// 商品金额,用于统一下单 + /// + public int total_fee { get; set; } + public string trade_type { get; set; } + /// + /// 统一下单接口返回结果 + /// + 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(""); + //sb.Append(""+model.appid+""); + //sb.Append(""+model.attach+""); + //sb.Append(""+model.body+""); + //sb.Append("" + model.mch_id + ""); + //sb.Append("" + model.nonce_str + ""); + //sb.Append("< notify_url >"+model.notify_url+""); + //if(model.openid!=null&&model.openid!="") + //sb.Append(""+ model.openid + ""); + //sb.Append(""+model.out_trade_no+""); + //sb.Append(""+model.spbill_create_ip+""); + //sb.Append(""+model.total_fee+""); + //sb.Append("" + model.spbill_create_ip + ""); + //sb.Append(""+model.trade_type+""); + //sb.Append("{ \"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+"} }"); + //sb.Append(""+model.sign+""); + //sb.Append(""); + + + return ""; + + //< appid > wx2421b1c4370ec43b + //< attach > 支付测试 + //< body > H5支付测试 + //< mch_id > 10000100 + //< nonce_str > 1add1a30ac87aa2db72f57a2375d8fec + + // < notify_url > http://wxpay.wxutil.com/pub_v2/pay/notify.v2.php + //< openid > oUpF8uMuAJO_M2pxb1Q9zNjWeS6o + //< out_trade_no > 1415659990 + //< spbill_create_ip > 14.23.150.211 + + // < total_fee > 1 + + // < trade_type > MWEB + + // < scene_info >{ "h5_info": { "type":"IOS","app_name": "王者荣耀","package_name": "com.tencent.tmgp.sgame"} } + + // < sign > 0CB01533B8C1EF103065174F50BCA001 + + // + + } + + } + + 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; } + // + // + // + // + // + // + // + // + // + // + // + // + + + + } +} diff --git a/基础类库/HuizhongLibrary/PhonePay/business/DownloadBill.cs b/基础类库/HuizhongLibrary/PhonePay/business/DownloadBill.cs new file mode 100644 index 0000000..0d2e337 --- /dev/null +++ b/基础类库/HuizhongLibrary/PhonePay/business/DownloadBill.cs @@ -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(); + } + } +} \ No newline at end of file diff --git a/基础类库/HuizhongLibrary/PhonePay/business/JsApiPay.cs b/基础类库/HuizhongLibrary/PhonePay/business/JsApiPay.cs new file mode 100644 index 0000000..0f4ea36 --- /dev/null +++ b/基础类库/HuizhongLibrary/PhonePay/business/JsApiPay.cs @@ -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 + { + /// + /// 保存页面对象,因为要在类的方法中使用Page的Request对象 + /// + private Page page {get;set;} + + /// + /// openid用于调用统一下单接口 + /// + public string openid { get; set; } + + /// + /// access_token用于获取收货地址js函数入口参数 + /// + public string access_token { get; set; } + + /// + /// 商品金额,用于统一下单 + /// + public int total_fee { get; set; } + + /// + /// 统一下单接口返回结果 + /// + public WxPayData unifiedOrderResult { get; set; } + + public JsApiPay(Page page) + { + this.page = page; + } + + + /** + * + * 网页授权获取用户基本信息的全部过程 + * 详情请参看网页授权获取用户基本信息:http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html + * 第一步:利用url跳转获取code + * 第二步:利用code去获取openid和access_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); + } + } + } + /** + * + * 通过code换取网页授权access_token和openid的返回数据,正确时返回的JSON数据包如下: + * { + * "access_token":"ACCESS_TOKEN", + * "expires_in":7200, + * "refresh_token":"REFRESH_TOKEN", + * "openid":"OPENID", + * "scope":"SCOPE", + * "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL" + * } + * 其中access_token可用于获取共享收货地址 + * openid是微信支付jsapi支付接口统一下单时必须的参数 + * 更详细的说明请参考网页授权获取用户基本信息: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 微信浏览器调起JSAPI时的输入参数,json格式可以直接做参数用 + * 更详细的说明请参考网页端调起支付API:http://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 共享收货地址js函数需要的参数,json格式可以直接做参数使用 + */ + 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; + } + } +} \ No newline at end of file diff --git a/基础类库/HuizhongLibrary/PhonePay/business/MicroPay.cs b/基础类库/HuizhongLibrary/PhonePay/business/MicroPay.cs new file mode 100644 index 0000000..06763ba --- /dev/null +++ b/基础类库/HuizhongLibrary/PhonePay/business/MicroPay.cs @@ -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 查询订单结果:0表示订单不成功,1表示订单成功,2表示继续查询 + * @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 false表示撤销失败,true表示撤销成功 + */ + 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; + } + } +} \ No newline at end of file diff --git a/基础类库/HuizhongLibrary/PhonePay/business/NativeNotify.cs b/基础类库/HuizhongLibrary/PhonePay/business/NativeNotify.cs new file mode 100644 index 0000000..896028c --- /dev/null +++ b/基础类库/HuizhongLibrary/PhonePay/business/NativeNotify.cs @@ -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 +{ + /// + /// 扫码支付模式一回调处理类 + /// 接收微信支付后台发送的扫码结果,调用统一下单接口并将下单结果返回给微信支付后台 + /// + 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
attach=test
bank_type=CFT
cash_fee=1
fee_type=CNY
is_subscribe=Y
mch_id=1438351202
nonce_str=0047c34002ef4ac597939d84984e8e9a
openid=o6CUIwKBdgyCy9B1xJMxNK8vdWeU
out_trade_no=14383512022018012310014931
result_code=SUCCESS
return_code=SUCCESS
sign=2E4C394C780D0C7BFAF2EDF54A73E927
time_end=20180123100323
total_fee=1
trade_type=JSAPI
transaction_id=4200000065201801239112746930
+ 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(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(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(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); + } + } + } +} \ No newline at end of file diff --git a/基础类库/HuizhongLibrary/PhonePay/business/NativePay.cs b/基础类库/HuizhongLibrary/PhonePay/business/NativePay.cs new file mode 100644 index 0000000..a6e23e2 --- /dev/null +++ b/基础类库/HuizhongLibrary/PhonePay/business/NativePay.cs @@ -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; + } + + /** + * 生成直接支付url,支付url有效期为2小时,模式二 + * @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 map) + { + string buff = ""; + foreach (KeyValuePair pair in map) + { + buff += pair.Key + "=" + pair.Value + "&"; + } + buff = buff.Trim('&'); + return buff; + } + } +} \ No newline at end of file diff --git a/基础类库/HuizhongLibrary/PhonePay/business/OrderQuery.cs b/基础类库/HuizhongLibrary/PhonePay/business/OrderQuery.cs new file mode 100644 index 0000000..09e2373 --- /dev/null +++ b/基础类库/HuizhongLibrary/PhonePay/business/OrderQuery.cs @@ -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(); + } + } +} \ No newline at end of file diff --git a/基础类库/HuizhongLibrary/PhonePay/business/Refund.cs b/基础类库/HuizhongLibrary/PhonePay/business/Refund.cs new file mode 100644 index 0000000..22985cf --- /dev/null +++ b/基础类库/HuizhongLibrary/PhonePay/business/Refund.cs @@ -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(); + } + } +} \ No newline at end of file diff --git a/基础类库/HuizhongLibrary/PhonePay/business/RefundQuery.cs b/基础类库/HuizhongLibrary/PhonePay/business/RefundQuery.cs new file mode 100644 index 0000000..c251451 --- /dev/null +++ b/基础类库/HuizhongLibrary/PhonePay/business/RefundQuery.cs @@ -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(); + } + } +} \ No newline at end of file diff --git a/基础类库/HuizhongLibrary/PhonePay/business/ResultNotify.cs b/基础类库/HuizhongLibrary/PhonePay/business/ResultNotify.cs new file mode 100644 index 0000000..8257455 --- /dev/null +++ b/基础类库/HuizhongLibrary/PhonePay/business/ResultNotify.cs @@ -0,0 +1,77 @@ +using System; +using System.Collections.Generic; +using System.Web; +using System.Web.UI; +using System.Web.UI.WebControls; + +namespace WxPayAPI +{ + /// + /// 支付结果通知回调处理类 + /// 负责接收微信支付后台发送的支付结果并对订单有效性进行验证,将验证结果反馈给微信支付后台 + /// + 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; + } + } + } +} \ No newline at end of file diff --git a/基础类库/HuizhongLibrary/PhonePay/lib/Config.cs b/基础类库/HuizhongLibrary/PhonePay/lib/Config.cs new file mode 100644 index 0000000..edf1ec5 --- /dev/null +++ b/基础类库/HuizhongLibrary/PhonePay/lib/Config.cs @@ -0,0 +1,62 @@ +using HuizhongLibrary.Common.Configuration; +using System; +using System.Collections.Generic; +using System.Web; + +namespace WxPayAPI +{ + /** + * 配置账号信息 + */ + public class WxPayConfig + { + //=======【基本信息设置】===================================== + /* 微信公众号信息配置 + * APPID:绑定支付的APPID(必须配置) + * MCHID:商户号(必须配置) + * KEY:商户支付密钥,参考开户邮件设置(必须配置) + * APPSECRET:公众帐号secert(仅JSAPI支付的时候需要配置) + */ + + 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"; + + + //=======【代理服务器设置】=================================== + /* 默认IP和端口号分别为0.0.0.0和0,此时不开启代理(如有需要才设置) + */ + public const string PROXY_URL = ""; + + //=======【上报信息配置】=================================== + /* 测速上报等级,0.关闭上报; 1.仅错误时上报; 2.全量上报 + */ + public const int REPORT_LEVENL = 1; + + //=======【日志级别】=================================== + /* 日志等级,0.不输出日志;1.只输出错误信息; 2.输出错误和正常信息; 3.输出错误信息、正常信息和调试信息 + */ + public const int LOG_LEVENL = 0; + } +} \ No newline at end of file diff --git a/基础类库/HuizhongLibrary/PhonePay/lib/Data.cs b/基础类库/HuizhongLibrary/PhonePay/lib/Data.cs new file mode 100644 index 0000000..cd33231 --- /dev/null +++ b/基础类库/HuizhongLibrary/PhonePay/lib/Data.cs @@ -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 +{ + /// + /// 微信支付协议接口数据类,所有的API接口通信都依赖这个数据结构, + /// 在调用接口之前先填充各个字段的值,然后进行接口通信, + /// 这样设计的好处是可扩展性强,用户可随意对协议进行更改而不用重新设计数据结构, + /// 还可以随意组合出不同的协议数据包,不用为每个协议设计一个数据包结构 + /// + public class WxPayData + { + public WxPayData() + { + + } + + //采用排序的Dictionary的好处是方便对数据包进行签名,不用再签名之前再做一次排序 + private SortedDictionary m_values = new SortedDictionary(); + + /** + * 设置某个字段的值 + * @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 若字段key已被设置,则返回true,否则返回false + */ + public bool IsSet(string key) + { + object o = null; + m_values.TryGetValue(key, out o); + if (null != o) + return true; + else + return false; + } + + /** + * @将Dictionary转成xml + * @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 = ""; + foreach (KeyValuePair 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 + ""; + } + else if (pair.Value.GetType() == typeof(string)) + { + xml += "<" + pair.Key + ">" + ""; + } + else//除了string和int类型不能含有其他数据类型 + { + Log.Error(this.GetType().ToString(), "WxPayData字段数据类型错误!"); + throw new WxPayException("WxPayData字段数据类型错误!"); + } + } + xml += ""; + return xml; + } + + /** + * @将xml转为WxPayData对象并返回对象内部的数据 + * @param string 待转换的xml串 + * @return 经转换得到的Dictionary + * @throws WxPayException + */ + public SortedDictionary 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;//获取到根节点 + 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; + } + + /** + * @Dictionary格式转化成url参数格式 + * @ return url格式串, 该串不包含sign字段值 + */ + public string ToUrl() + { + string buff = ""; + foreach (KeyValuePair 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; + } + + + /** + * @Dictionary格式化成Json + * @return json串数据 + */ + public string ToJson() + { + string jsonStr = JsonMapper.ToJson(m_values); + return jsonStr; + } + + /** + * @values格式化成能在Web页面上显示的结果(因为web页面上不能直接输出xml格式的字符串) + */ + public string ToPrintStr() + { + string str = ""; + foreach (KeyValuePair 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}
", 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 GetValues() + { + return m_values; + } + } +} \ No newline at end of file diff --git a/基础类库/HuizhongLibrary/PhonePay/lib/Exception.cs b/基础类库/HuizhongLibrary/PhonePay/lib/Exception.cs new file mode 100644 index 0000000..1c6dedb --- /dev/null +++ b/基础类库/HuizhongLibrary/PhonePay/lib/Exception.cs @@ -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) + { + + } + } +} \ No newline at end of file diff --git a/基础类库/HuizhongLibrary/PhonePay/lib/HttpService.cs b/基础类库/HuizhongLibrary/PhonePay/lib/HttpService.cs new file mode 100644 index 0000000..eeb62dc --- /dev/null +++ b/基础类库/HuizhongLibrary/PhonePay/lib/HttpService.cs @@ -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 +{ + /// + /// http连接基础类,负责底层的http通信 + /// + 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; + } + + /// + /// 处理http GET请求,返回数据 + /// + /// 请求的url地址 + /// http GET成功后返回的数据,失败抛WebException异常 + 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; + } + } +} \ No newline at end of file diff --git a/基础类库/HuizhongLibrary/PhonePay/lib/Log.cs b/基础类库/HuizhongLibrary/PhonePay/lib/Log.cs new file mode 100644 index 0000000..6bbf2a3 --- /dev/null +++ b/基础类库/HuizhongLibrary/PhonePay/lib/Log.cs @@ -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(); + } + } +} \ No newline at end of file diff --git a/基础类库/HuizhongLibrary/PhonePay/lib/Notify.cs b/基础类库/HuizhongLibrary/PhonePay/lib/Notify.cs new file mode 100644 index 0000000..3d54845 --- /dev/null +++ b/基础类库/HuizhongLibrary/PhonePay/lib/Notify.cs @@ -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 +{ + /// + /// 回调处理基类 + /// 主要负责接收微信支付后台发送过来的数据,对数据进行签名验证 + /// 子类在此类基础上进行派生并重写自己的回调处理过程 + /// + public class Notify + { + public Page page {get;set;} + public Notify(Page page) + { + this.page = page; + } + + /// + /// 接收从微信支付后台发送过来的数据并验证签名 + /// + /// 微信支付后台返回的数据 + 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() + { + + } + } +} \ No newline at end of file diff --git a/基础类库/HuizhongLibrary/PhonePay/lib/WxPayApi.cs b/基础类库/HuizhongLibrary/PhonePay/lib/WxPayApi.cs new file mode 100644 index 0000000..e1efdde --- /dev/null +++ b/基础类库/HuizhongLibrary/PhonePay/lib/WxPayApi.cs @@ -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 提交给撤销订单API接口的参数,out_trade_no和transaction_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_no、out_trade_no、transaction_id、refund_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) == "") + { + 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("统一支付接口中,缺少必填参数openid!trade_type为JSAPI时,openid为必填参数!"); + } + if (inputObj.GetValue("trade_type").ToString() == "NATIVE" && !inputObj.IsSet("product_id")) + { + throw new WxPayException("统一支付接口中,缺少必填参数product_id!trade_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); + } + /** + * 生成时间戳,标准北京时间,时区为东八区,自1970年1月1日 0点0分0秒以来的秒数 + * @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("-", ""); + } + } + } \ No newline at end of file diff --git a/基础类库/HuizhongLibrary/PrintSetup.Designer.cs b/基础类库/HuizhongLibrary/PrintSetup.Designer.cs new file mode 100644 index 0000000..fa5385f --- /dev/null +++ b/基础类库/HuizhongLibrary/PrintSetup.Designer.cs @@ -0,0 +1,484 @@ +namespace HuizhongLibrary.ReportPrint +{ + partial class PrintSetup + { + /// + /// 必需的设计器变量。 + /// + private System.ComponentModel.IContainer components = null; + + /// + /// 清理所有正在使用的资源。 + /// + /// 如果应释放托管资源,为 true;否则为 false。 + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows 窗体设计器生成的代码 + + /// + /// 设计器支持所需的方法 - 不要 + /// 使用代码编辑器修改此方法的内容。 + /// + 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; + } +} \ No newline at end of file diff --git a/基础类库/HuizhongLibrary/PrintSetup.cs b/基础类库/HuizhongLibrary/PrintSetup.cs new file mode 100644 index 0000000..1321bea --- /dev/null +++ b/基础类库/HuizhongLibrary/PrintSetup.cs @@ -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; + } + } +} \ No newline at end of file diff --git a/基础类库/HuizhongLibrary/PrintSetup.resx b/基础类库/HuizhongLibrary/PrintSetup.resx new file mode 100644 index 0000000..19dc0dd --- /dev/null +++ b/基础类库/HuizhongLibrary/PrintSetup.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/基础类库/HuizhongLibrary/Properties/AssemblyInfo.cs b/基础类库/HuizhongLibrary/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..fb75d17 --- /dev/null +++ b/基础类库/HuizhongLibrary/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 有关程序集的常规信息通过以下 +// 特性集控制。更改这些特性值可修改 +// 与程序集关联的信息。 +[assembly: AssemblyTitle("HuizhongLibrary")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("HuizhongLibrary")] +[assembly: AssemblyCopyright("Copyright © 2012")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 使此程序集中的类型 +// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型, +// 则将该类型上的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID +[assembly: Guid("5333507e-59ab-46d8-97dd-dc1318ff27b2")] + +// 程序集的版本信息由下面四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, +// 方法是按如下所示使用“*”: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/基础类库/HuizhongLibrary/Properties/Settings.Designer.cs b/基础类库/HuizhongLibrary/Properties/Settings.Designer.cs new file mode 100644 index 0000000..a34f7b7 --- /dev/null +++ b/基础类库/HuizhongLibrary/Properties/Settings.Designer.cs @@ -0,0 +1,36 @@ +//------------------------------------------------------------------------------ +// +// 此代码由工具生成。 +// 运行时版本:4.0.30319.42000 +// +// 对此文件的更改可能会导致不正确的行为,并且如果 +// 重新生成代码,这些更改将会丢失。 +// +//------------------------------------------------------------------------------ + +namespace HuizhongLibrary.Properties { + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.7.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; + } + } + + [global::System.Configuration.ApplicationScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.WebServiceUrl)] + [global::System.Configuration.DefaultSettingValueAttribute("http://47.114.82.162:7000/UpdateService.asmx")] + public string HuizhongLibrary_US_UpdateService { + get { + return ((string)(this["HuizhongLibrary_US_UpdateService"])); + } + } + } +} diff --git a/基础类库/HuizhongLibrary/Properties/Settings.settings b/基础类库/HuizhongLibrary/Properties/Settings.settings new file mode 100644 index 0000000..70e09a7 --- /dev/null +++ b/基础类库/HuizhongLibrary/Properties/Settings.settings @@ -0,0 +1,9 @@ + + + + + + http://47.114.82.162:7000/UpdateService.asmx + + + \ No newline at end of file diff --git a/基础类库/HuizhongLibrary/Safety.cs b/基础类库/HuizhongLibrary/Safety.cs new file mode 100644 index 0000000..7f13ccc --- /dev/null +++ b/基础类库/HuizhongLibrary/Safety.cs @@ -0,0 +1,467 @@ +using System; +using System.IO; +using System.Security.Cryptography; +using System.Text; +using System.Data; +using System.Data.SqlClient; +using System.Threading; +using System.Runtime.InteropServices; +using System.Security.Cryptography.X509Certificates; +using System.Collections.Generic; +using HuizhongLibrary.Log; + +namespace HuizhongLibrary.Safety +{ + /**//// + /// ˽Կ(ԳƼ) + /// + public class CryptoPrivate + { + + + private SymmetricAlgorithm mobjCryptoService; + private string Key; + /**//// + /// ԳƼĹ캯 + /// Կͨǰ˾б룬ΪKey + /// + /// Կ + public CryptoPrivate(string key) + { + mobjCryptoService = new RijndaelManaged(); + //mobjCryptoService. + Key=key; + } + /// + /// Կ + /// + /// Կ + private byte[] GetLegalKey() + { + string sTemp = Key; + mobjCryptoService.GenerateKey(); + //Կ + byte[] bytTemp = mobjCryptoService.Key; //ȡԿ + int KeyLength = bytTemp.Length; //Կ + if (sTemp.Length > KeyLength) //<<˾־>>ȴԿȣسȵԿһַ + sTemp = sTemp.Substring(0, KeyLength); + else if (sTemp.Length < KeyLength) //<<˾־>>СԿÿո䵽Կ賤 + sTemp = sTemp.PadRight(KeyLength, ' '); + return ASCIIEncoding.ASCII.GetBytes(sTemp); //Կ + } + /**//// + /// óʼIV + /// + /// IV + private byte[] GetLegalIV() + { + string sTemp = "E3ghj*Ghg7!rNIfb&95GUY86GfghUb#er57HBh(u%g6HJ($jhWk7&!hg4ui%$hjk"; + mobjCryptoService.GenerateIV(); + byte[] bytTemp = mobjCryptoService.IV; + int IVLength = bytTemp.Length; + if (sTemp.Length > IVLength) + sTemp = sTemp.Substring(0, IVLength); + else if (sTemp.Length < IVLength) + sTemp = sTemp.PadRight(IVLength, ' '); + return ASCIIEncoding.ASCII.GetBytes(sTemp); + } + /// + /// ܷ + /// + /// ܵĴ + /// ܵĴ + public string Encrypto(string Source) + { + try + { + byte[] bytIn = UTF8Encoding.UTF8.GetBytes(Source); + MemoryStream ms = new MemoryStream(); + mobjCryptoService.Key = GetLegalKey(); + mobjCryptoService.IV = GetLegalIV(); + ICryptoTransform encrypto = mobjCryptoService.CreateEncryptor(); + CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write); + cs.Write(bytIn, 0, bytIn.Length); + cs.FlushFinalBlock(); + ms.Close(); + byte[] bytOut = ms.ToArray(); + return Convert.ToBase64String(bytOut); + } + catch (Exception ex) + { + //ErrorFollow.TraceWrite("ܴ", ex.StackTrace, ex.Message); + } + return Source; + + } + /// + /// ܷ + /// + /// ܵĴ + /// ܵĴ + public string Decrypto(string Source) + { + try + { + StreamReader sr; + byte[] bytIn = Convert.FromBase64String(Source); + MemoryStream ms = new MemoryStream(bytIn, 0, bytIn.Length); + mobjCryptoService.Key = GetLegalKey(); + mobjCryptoService.IV = GetLegalIV(); + ICryptoTransform encrypto = mobjCryptoService.CreateDecryptor(); + CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Read); + sr = new StreamReader(cs); + return sr.ReadToEnd(); + } + catch (Exception ex) + { + //ErrorFollow.TraceWrite("ܴ", ex.StackTrace, ex.Message); + } + return Source; + } + + + public static string Encryp(string Source) + { + CryptoPrivate cp = new CryptoPrivate("formmatwizard54073"); + return cp.Encrypto(Source); + } + public static string Decryp(string Source) + { + CryptoPrivate cp = new CryptoPrivate("formmatwizard54073"); + return cp.Decrypto(Source); + } + + } + + + /// + /// Կ(ԳƼ) + /// + public class CryptoPublic + { + RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); + + + /// + /// ˽Կ + /// + public string GetPrikey() + { + string pubkey = rsa.ToXmlString(false); //Կ + return rsa.ToXmlString(true); //˽Կ + } + + /// + /// عԿ + /// + public string GetPubkey() + { + string pubkey = rsa.ToXmlString(false); //Կ + return rsa.ToXmlString(false); //عԿ + } + + /// + /// ܷ(Ҫַܵbyteܳ117ֽ) + /// + /// ܵĴ + /// Կ + public string Encrypto(string Source,string pubkey) + { + byte[] bytIn = UTF8Encoding.UTF8.GetBytes(Source); + rsa.FromXmlString(pubkey); + byte[] bytOut=rsa.Encrypt(bytIn,false); // + return Convert.ToBase64String(bytOut); + } + + /// + /// ܷ + /// + /// ܵĴ + /// ˽Կ + public string Decrypto(string Source,string prikey) + { + byte[] bytIn = Convert.FromBase64String(Source); + rsa.FromXmlString(prikey); + byte[] d=rsa.Decrypt(bytIn,false); // + return UTF8Encoding.UTF8.GetString(d); + } + + /// + /// ǩ + /// + /// Ҫǩַ + /// ˽Կ + public string RsaCreateSignature(string Source,string prikey) + { + rsa.FromXmlString(prikey); + RSAPKCS1SignatureFormatter f = new RSAPKCS1SignatureFormatter(rsa); + f.SetHashAlgorithm("MD5"); + byte[] bytIn = UTF8Encoding.UTF8.GetBytes(Source); + MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); + byte[] result = md5.ComputeHash(bytIn); + byte[] b = f.CreateSignature(result); //ϣֵǩ + return Convert.ToBase64String(b); //ȡǩϣֵ + } + /// + /// ֤ǩ + /// + /// Ҫַ֤ + /// Կ + /// ǩַ + public bool RsaVerifySignature(string Source,string Hash,string pubkey) + { + rsa.FromXmlString(pubkey); + RSAPKCS1SignatureDeformatter f = new RSAPKCS1SignatureDeformatter(rsa); + f.SetHashAlgorithm("MD5"); + byte[] key = Convert.FromBase64String(Hash); + MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); + byte[] name = md5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(Source)); + if (f.VerifySignature(name,key)==true){return true;} + return false; + + } + + + + public static string GetHashPassword(string password) + { + MD5 md5 = MD5.Create(); + byte[] hash = md5.ComputeHash(Encoding.UTF8.GetBytes(password)); + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < hash.Length; i++) + { + sb.Append(hash[i].ToString("X2")); + } + return sb.ToString(); + } + + public static string GetHashPassword(string password,int StartIndex,int Length) + { + MD5 md5 = MD5.Create(); + byte[] hash = md5.ComputeHash(Encoding.UTF8.GetBytes(password)); + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < hash.Length; i++) + { + sb.Append(hash[i].ToString("X2")); + } + return sb.ToString().Substring(StartIndex,Length); + } + + #region MD5 + public static string Md5For32(string str) + { + string cl = str; + string pwd = ""; + MD5 md5 = MD5.Create();//ʵһmd5 + // ܺһֽ͵飬ҪעUTF8/Unicodeȵѡ + byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(cl)); + // ͨʹѭֽ͵תΪַַdzַʽ + for (int i = 0; i < s.Length; i++) + { + // õַʹʮ͸ʽʽַСдĸʹôдXʽַǴдַ + + pwd = pwd + s[i].ToString("x2"); + + } + return pwd; + } + #endregion + + } + + + public class CryptoRsa + { + public string Sign(string contentForSign, string priKeyFile, string keyPwd) + { + var rsa = GetPrivateKey(priKeyFile, keyPwd); + // Create a new RSACryptoServiceProvider + var rsaClear = new RSACryptoServiceProvider(); + // Export RSA parameters from 'rsa' and import them into 'rsaClear' + var paras = rsa.ExportParameters(true); + rsaClear.ImportParameters(paras); + using (var sha256 = new SHA256CryptoServiceProvider()) + { + var signData = rsa.SignData(Encoding.UTF8.GetBytes(contentForSign), sha256); + return BytesToHex(signData); + } + } + + public bool VerifySign(string contentForSign, string signedData, string pubKeyFile) + { + var rsa = GetPublicKey(pubKeyFile); + + using (var sha256 = new SHA256CryptoServiceProvider()) + { + return rsa.VerifyData(Encoding.UTF8.GetBytes(contentForSign), sha256, HexToBytes(signedData)); + } + } + + /// + /// ȡǩ֤˽Կ + /// + /// + /// + /// + private static RSACryptoServiceProvider GetPrivateKey(string priKeyFile, string keyPwd) + { + var pc = new X509Certificate2(priKeyFile, keyPwd, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet); + return (RSACryptoServiceProvider)pc.PrivateKey; + } + + /// + /// ȡǩ֤ + /// + /// + /// + private static RSACryptoServiceProvider GetPublicKey(string pubKeyFile) + { + var pc = new X509Certificate2(pubKeyFile); + return (RSACryptoServiceProvider)pc.PublicKey.Key; + } + + public static byte[] HexToBytes(string text) + { + if (text.Length % 2 != 0) + throw new ArgumentException("text Ϊ"); + + List lstRet = new List(); + for (int i = 0; i < text.Length; i = i + 2) + { + lstRet.Add(Convert.ToByte(text.Substring(i, 2), 16)); + } + return lstRet.ToArray(); + } + + /// + /// bytesתhex + /// + /// bytes + /// תhexַ + public static string BytesToHex(byte[] data) + { + StringBuilder sbRet = new StringBuilder(data.Length * 2); + for (int i = 0; i < data.Length; i++) + { + sbRet.Append(Convert.ToString(data[i], 16).PadLeft(2, '0')); + } + return sbRet.ToString(); + } + + } + + + public class CryptoAes + { + #region AES + /// + /// AES + /// + /// ַ + /// ܵ + /// Կ + /// + public static string AESEncrypt(string text, string password, string iv) + { + RijndaelManaged rijndaelCipher = new RijndaelManaged(); + rijndaelCipher.Mode = CipherMode.CBC; + rijndaelCipher.Padding = PaddingMode.PKCS7; + rijndaelCipher.KeySize = 128; + rijndaelCipher.BlockSize = 128; + byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(password); + byte[] keyBytes = new byte[16]; + int len = pwdBytes.Length; + if (len > keyBytes.Length) len = keyBytes.Length; + System.Array.Copy(pwdBytes, keyBytes, len); + rijndaelCipher.Key = keyBytes; + byte[] ivBytes = System.Text.Encoding.UTF8.GetBytes(iv); + rijndaelCipher.IV = new byte[16]; + ICryptoTransform transform = rijndaelCipher.CreateEncryptor(); + byte[] plainText = Encoding.UTF8.GetBytes(text); + byte[] cipherBytes = transform.TransformFinalBlock(plainText, 0, plainText.Length); + + return Convert.ToBase64String(cipherBytes); + + } + #endregion + #region AES + /// + /// AES + /// + /// + /// + /// + /// + public static string AESDecrypt(string text, string password, string iv) + { + RijndaelManaged rijndaelCipher = new RijndaelManaged(); + rijndaelCipher.Mode = CipherMode.CBC; + rijndaelCipher.Padding = PaddingMode.PKCS7; + rijndaelCipher.KeySize = 128; + rijndaelCipher.BlockSize = 128; + byte[] encryptedData = Convert.FromBase64String(text); + byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(password); + byte[] keyBytes = new byte[16]; + int len = pwdBytes.Length; + if (len > keyBytes.Length) len = keyBytes.Length; + System.Array.Copy(pwdBytes, keyBytes, len); + rijndaelCipher.Key = keyBytes; + byte[] ivBytes = System.Text.Encoding.UTF8.GetBytes(iv); + rijndaelCipher.IV = ivBytes; + ICryptoTransform transform = rijndaelCipher.CreateDecryptor(); + byte[] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length); + return Encoding.UTF8.GetString(plainText); + } + #endregion + } + + /// + /// U̼ + /// + public class UCryptoPublic + { + [DllImport("HD_Security.dll")] + private static extern int HD_VerifyPassword(StringBuilder password, int passwordlen); + [DllImport("HD_Security.dll")] + private static extern int HD_Initialize(StringBuilder password, int passwordlen); + [DllImport("HD_Security.dll")] + public static extern int HD_GetDeviceSn(StringBuilder szSn, ref int nSnLen); + + /// + /// ֤'ɹ(9000)豸ʧ(0)֤벻ȷ(2)볤Ȳȷ(3)' + /// + /// + /// 볤 + public static int VerifyPassword(StringBuilder password, int passwordlen) + { + return HD_VerifyPassword(password, passwordlen); + } + + /// + /// ʼ'ɹ(9000)豸ʧ(0)ʼ豸ʧ(1)볤Ȳȷ(3)' + /// + /// + /// 볤 + public static int Initialize(StringBuilder password, int passwordlen) + { + return HD_Initialize(password, passwordlen); + } + + /// + /// Uк'ɹ(9000)豸ʧ(0)кʧ(4)' + /// + /// к + /// кų + public static int GetDeviceSn(out string szSn, out int nSnLen) + { + StringBuilder sb = new StringBuilder(60); + int snlen = 0; + int a = HD_GetDeviceSn(sb, ref snlen); + szSn = sb.ToString(); + nSnLen = snlen; + return a; + } + + } +} + diff --git a/基础类库/HuizhongLibrary/Safety/SM3.cs b/基础类库/HuizhongLibrary/Safety/SM3.cs new file mode 100644 index 0000000..8de7cc9 --- /dev/null +++ b/基础类库/HuizhongLibrary/Safety/SM3.cs @@ -0,0 +1,480 @@ +using Org.BouncyCastle.Crypto; +using Org.BouncyCastle.Crypto.Macs; +using Org.BouncyCastle.Crypto.Parameters; +using Org.BouncyCastle.Utilities.Encoders; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; + +namespace HuizhongLibrary.Safety +{ + public class SupportClass + { + /// + /// Performs an unsigned bitwise right shift with the specified number + /// + /// Number to operate on + /// Ammount of bits to shift + /// The resulting number from the shift operation + public static int URShift(int number, int bits) + { + if (number >= 0) + return number >> bits; + else + return (number >> bits) + (2 << ~bits); + } + + /// + /// Performs an unsigned bitwise right shift with the specified number + /// + /// Number to operate on + /// Ammount of bits to shift + /// The resulting number from the shift operation + public static int URShift(int number, long bits) + { + return URShift(number, (int)bits); + } + + /// + /// Performs an unsigned bitwise right shift with the specified number + /// + /// Number to operate on + /// Ammount of bits to shift + /// The resulting number from the shift operation + public static long URShift(long number, int bits) + { + if (number >= 0) + return number >> bits; + else + return (number >> bits) + (2L << ~bits); + } + + /// + /// Performs an unsigned bitwise right shift with the specified number + /// + /// Number to operate on + /// Ammount of bits to shift + /// The resulting number from the shift operation + public static long URShift(long number, long bits) + { + return URShift(number, (int)bits); + } + } + + /// + /// General + /// + public abstract class GeneralDigest : IDigest + { + private const int BYTE_LENGTH = 64; + + private byte[] xBuf; + private int xBufOff; + + private long byteCount; + + internal GeneralDigest() + { + xBuf = new byte[4]; + } + + internal GeneralDigest(GeneralDigest t) + { + xBuf = new byte[t.xBuf.Length]; + Array.Copy(t.xBuf, 0, xBuf, 0, t.xBuf.Length); + + xBufOff = t.xBufOff; + byteCount = t.byteCount; + } + + public void Update(byte input) + { + xBuf[xBufOff++] = input; + + if (xBufOff == xBuf.Length) + { + ProcessWord(xBuf, 0); + xBufOff = 0; + } + + byteCount++; + } + + public void BlockUpdate( + byte[] input, + int inOff, + int length) + { + // + // fill the current word + // + while ((xBufOff != 0) && (length > 0)) + { + Update(input[inOff]); + inOff++; + length--; + } + + // + // process whole words. + // + while (length > xBuf.Length) + { + ProcessWord(input, inOff); + + inOff += xBuf.Length; + length -= xBuf.Length; + byteCount += xBuf.Length; + } + + // + // load in the remainder. + // + while (length > 0) + { + Update(input[inOff]); + + inOff++; + length--; + } + } + + public void Finish() + { + long bitLength = (byteCount << 3); + + // + // add the pad bytes. + // + Update(unchecked((byte)128)); + + while (xBufOff != 0) Update(unchecked((byte)0)); + ProcessLength(bitLength); + ProcessBlock(); + } + + public virtual void Reset() + { + byteCount = 0; + xBufOff = 0; + Array.Clear(xBuf, 0, xBuf.Length); + } + + public int GetByteLength() + { + return BYTE_LENGTH; + } + + internal abstract void ProcessWord(byte[] input, int inOff); + internal abstract void ProcessLength(long bitLength); + internal abstract void ProcessBlock(); + public abstract string AlgorithmName { get; } + public abstract int GetDigestSize(); + public abstract int DoFinal(byte[] output, int outOff); + } + + public class SM3Digest : GeneralDigest + { + public override string AlgorithmName + { + get + { + return "SM3"; + } + + } + public override int GetDigestSize() + { + return DIGEST_LENGTH; + } + + private const int DIGEST_LENGTH = 32; + + private static readonly int[] v0 = new int[] { 0x7380166f, 0x4914b2b9, 0x172442d7, unchecked((int)0xda8a0600), unchecked((int)0xa96f30bc), 0x163138aa, unchecked((int)0xe38dee4d), unchecked((int)0xb0fb0e4e) }; + + private int[] v = new int[8]; + private int[] v_ = new int[8]; + + private static readonly int[] X0 = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + + private int[] X = new int[68]; + private int xOff; + + private int T_00_15 = 0x79cc4519; + private int T_16_63 = 0x7a879d8a; + + public SM3Digest() + { + Reset(); + } + + public SM3Digest(SM3Digest t) : base(t) + { + + Array.Copy(t.X, 0, X, 0, t.X.Length); + xOff = t.xOff; + + Array.Copy(t.v, 0, v, 0, t.v.Length); + } + + public override void Reset() + { + base.Reset(); + + Array.Copy(v0, 0, v, 0, v0.Length); + + xOff = 0; + Array.Copy(X0, 0, X, 0, X0.Length); + } + + internal override void ProcessBlock() + { + int i; + + int[] ww = X; + int[] ww_ = new int[64]; + + for (i = 16; i < 68; i++) + { + ww[i] = P1(ww[i - 16] ^ ww[i - 9] ^ (ROTATE(ww[i - 3], 15))) ^ (ROTATE(ww[i - 13], 7)) ^ ww[i - 6]; + } + + for (i = 0; i < 64; i++) + { + ww_[i] = ww[i] ^ ww[i + 4]; + } + + int[] vv = v; + int[] vv_ = v_; + + Array.Copy(vv, 0, vv_, 0, v0.Length); + + int SS1, SS2, TT1, TT2, aaa; + for (i = 0; i < 16; i++) + { + aaa = ROTATE(vv_[0], 12); + SS1 = aaa + vv_[4] + ROTATE(T_00_15, i); + SS1 = ROTATE(SS1, 7); + SS2 = SS1 ^ aaa; + + TT1 = FF_00_15(vv_[0], vv_[1], vv_[2]) + vv_[3] + SS2 + ww_[i]; + TT2 = GG_00_15(vv_[4], vv_[5], vv_[6]) + vv_[7] + SS1 + ww[i]; + vv_[3] = vv_[2]; + vv_[2] = ROTATE(vv_[1], 9); + vv_[1] = vv_[0]; + vv_[0] = TT1; + vv_[7] = vv_[6]; + vv_[6] = ROTATE(vv_[5], 19); + vv_[5] = vv_[4]; + vv_[4] = P0(TT2); + } + for (i = 16; i < 64; i++) + { + aaa = ROTATE(vv_[0], 12); + SS1 = aaa + vv_[4] + ROTATE(T_16_63, i); + SS1 = ROTATE(SS1, 7); + SS2 = SS1 ^ aaa; + + TT1 = FF_16_63(vv_[0], vv_[1], vv_[2]) + vv_[3] + SS2 + ww_[i]; + TT2 = GG_16_63(vv_[4], vv_[5], vv_[6]) + vv_[7] + SS1 + ww[i]; + vv_[3] = vv_[2]; + vv_[2] = ROTATE(vv_[1], 9); + vv_[1] = vv_[0]; + vv_[0] = TT1; + vv_[7] = vv_[6]; + vv_[6] = ROTATE(vv_[5], 19); + vv_[5] = vv_[4]; + vv_[4] = P0(TT2); + } + for (i = 0; i < 8; i++) + { + vv[i] ^= vv_[i]; + } + + // Reset + xOff = 0; + Array.Copy(X0, 0, X, 0, X0.Length); + } + + internal override void ProcessWord(byte[] in_Renamed, int inOff) + { + int n = in_Renamed[inOff] << 24; + n |= (in_Renamed[++inOff] & 0xff) << 16; + n |= (in_Renamed[++inOff] & 0xff) << 8; + n |= (in_Renamed[++inOff] & 0xff); + X[xOff] = n; + + if (++xOff == 16) + { + ProcessBlock(); + } + } + + internal override void ProcessLength(long bitLength) + { + if (xOff > 14) + { + ProcessBlock(); + } + + X[14] = (int)(SupportClass.URShift(bitLength, 32)); + X[15] = (int)(bitLength & unchecked((int)0xffffffff)); + } + + public static void IntToBigEndian(int n, byte[] bs, int off) + { + bs[off] = (byte)(SupportClass.URShift(n, 24)); + bs[++off] = (byte)(SupportClass.URShift(n, 16)); + bs[++off] = (byte)(SupportClass.URShift(n, 8)); + bs[++off] = (byte)(n); + } + + public override int DoFinal(byte[] out_Renamed, int outOff) + { + Finish(); + + for (int i = 0; i < 8; i++) + { + IntToBigEndian(v[i], out_Renamed, outOff + i * 4); + } + + Reset(); + + return DIGEST_LENGTH; + } + + private int ROTATE(int x, int n) + { + return (x << n) | (SupportClass.URShift(x, (32 - n))); + } + + private int P0(int X) + { + return ((X) ^ ROTATE((X), 9) ^ ROTATE((X), 17)); + } + + private int P1(int X) + { + return ((X) ^ ROTATE((X), 15) ^ ROTATE((X), 23)); + } + + private int FF_00_15(int X, int Y, int Z) + { + return (X ^ Y ^ Z); + } + + private int FF_16_63(int X, int Y, int Z) + { + return ((X & Y) | (X & Z) | (Y & Z)); + } + + private int GG_00_15(int X, int Y, int Z) + { + return (X ^ Y ^ Z); + } + + private int GG_16_63(int X, int Y, int Z) + { + return ((X & Y) | (~X & Z)); + } + } + + public static class Sm3Crypto + { + /// + /// sm3加密(使用自定义密钥) + /// + /// + /// + public static byte[] ToSM3byte(string data, string key) + { + byte[] msg1 = Encoding.Default.GetBytes(data); + byte[] key1 = Encoding.Default.GetBytes(key); + + KeyParameter keyParameter = new KeyParameter(key1); + SM3Digest sm3 = new SM3Digest(); + + HMac mac = new HMac(sm3);//带密钥的杂凑算法 + mac.Init(keyParameter); + mac.BlockUpdate(msg1, 0, msg1.Length); + byte[] result = new byte[mac.GetMacSize()]; + + mac.DoFinal(result, 0); + return Hex.Encode(result); + } + + /// + /// sm3加密 + /// + /// + /// 二进制数组 + public static byte[] ToSM3byte(string data) + { + var msg = Encoding.Default.GetBytes(data);//把字符串转成16进制的ASCII码 + SM3Digest sm3 = new SM3Digest(); + sm3.BlockUpdate(msg, 0, msg.Length); + byte[] md = new byte[sm3.GetDigestSize()];//SM3算法产生的哈希值大小 + sm3.DoFinal(md, 0); + return Hex.Encode(md); + } + + /// + /// sm3加密 + /// + /// + /// 16进制字符串 + public static string ToSM3HexStr(string data) + { + var msg = Encoding.Default.GetBytes(data);//把字符串转成16进制的ASCII码 + SM3Digest sm3 = new SM3Digest(); + sm3.BlockUpdate(msg, 0, msg.Length); + byte[] md = new byte[sm3.GetDigestSize()];//SM3算法产生的哈希值大小 + sm3.DoFinal(md, 0); + return new UTF8Encoding().GetString(Hex.Encode(md)); + } + + /// + /// sm3加密(使用自定义Hex密钥) + /// + /// + /// + /// + public static string ToSM3HexStr(string data, string key) + { + byte[] msg1 = Encoding.Default.GetBytes(data); + byte[] key1 = HexStringToBytes(key); + + KeyParameter keyParameter = new KeyParameter(key1); + SM3Digest sm3 = new SM3Digest(); + + HMac mac = new HMac(sm3);//带密钥的杂凑算法 + mac.Init(keyParameter); + mac.BlockUpdate(msg1, 0, msg1.Length); + byte[] result = new byte[mac.GetMacSize()]; + + mac.DoFinal(result, 0); + return new UTF8Encoding().GetString(Hex.Encode(result)); + } + + /// + /// 16进制格式字符串转字节数组 + /// + /// + /// + public static byte[] HexStringToBytes(string hexString) + { + hexString = Regex.Replace(hexString, @".{2}", "$0 "); + //以 ' ' 分割字符串,并去掉空字符 + string[] chars = hexString.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); + byte[] returnBytes = new byte[chars.Length]; + //逐个字符变为16进制字节数据 + for (int i = 0; i < chars.Length; i++) + { + returnBytes[i] = Convert.ToByte(chars[i], 16); + } + return returnBytes; + } + } +} diff --git a/基础类库/HuizhongLibrary/Safety/SM4.cs b/基础类库/HuizhongLibrary/Safety/SM4.cs new file mode 100644 index 0000000..66d445b --- /dev/null +++ b/基础类库/HuizhongLibrary/Safety/SM4.cs @@ -0,0 +1,531 @@ +using Org.BouncyCastle.Utilities.Encoders; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; + +namespace HuizhongLibrary.Safety +{ + //加密和解密结构相同,只不过,解密密钥是加密密钥的逆序 + /// + /// Sm4算法 + /// 对标国际DES算法 + /// + public class SM4Utils + { + public SM4Utils() + { + Key = "9814548961710661";//密钥长度必须为16字节。 + Iv = "0000000000000000"; + HexString = false; + CryptoMode = Sm4CryptoEnum.ECB; + } + /// + /// 数据 + /// + public string Data { get; set; } + /// + /// 秘钥 + /// + public string Key { get; }//不同的key,加密出来的数据不一样,所以此处设定好key以后,禁止修改 + /// + /// 向量 + /// + public string Iv { get; set; } + /// + /// 明文是否是十六进制 + /// + public bool HexString { get; }//set; + /// + /// 加密模式(默认ECB) + /// 统一改为ECB模式 + /// + public Sm4CryptoEnum CryptoMode { get; } + + #region 加密 + public string Encrypt(SM4Utils entity) + { + return entity.CryptoMode == Sm4CryptoEnum.CBC ? EncryptCBC(entity) : EncryptECB(entity); + } + /// + /// ECB加密 + /// + /// + /// + public static string EncryptECB(SM4Utils entity) + { + Sm4Context ctx = new Sm4Context + { + IsPadding = true + }; + byte[] keyBytes = entity.HexString ? Hex.Decode(entity.Key) : Encoding.Default.GetBytes(entity.Key); + SM4 sm4 = new SM4(); + sm4.SetKeyEnc(ctx, keyBytes); + byte[] encrypted = sm4.Sm4CryptEcb(ctx, Encoding.Default.GetBytes(entity.Data)); + return Encoding.Default.GetString(Hex.Encode(encrypted)); + } + /// + /// CBC加密 + /// + /// + /// + public static string EncryptCBC(SM4Utils entity) + { + Sm4Context ctx = new Sm4Context + { + IsPadding = true + }; + byte[] keyBytes = entity.HexString ? Hex.Decode(entity.Key) : Encoding.Default.GetBytes(entity.Key); + byte[] ivBytes = entity.HexString ? Hex.Decode(entity.Iv) : Encoding.Default.GetBytes(entity.Iv); + SM4 sm4 = new SM4(); + sm4.SetKeyEnc(ctx, keyBytes); + byte[] encrypted = sm4.Sm4CryptCbc(ctx, ivBytes, Encoding.Default.GetBytes(entity.Data)); + return Convert.ToBase64String(encrypted); + } + #endregion + #region 解密 + public object Decrypt(SM4Utils entity) + { + return entity.CryptoMode == Sm4CryptoEnum.CBC ? DecryptCBC(entity) : DecryptECB(entity); + } + /// + /// ECB解密 + /// + /// + /// + public static string DecryptECB(SM4Utils entity) + { + Sm4Context ctx = new Sm4Context + { + IsPadding = true, + Mode = 0 + }; + byte[] keyBytes = entity.HexString ? Hex.Decode(entity.Key) : Encoding.Default.GetBytes(entity.Key); + SM4 sm4 = new SM4(); + sm4.Sm4SetKeyDec(ctx, keyBytes); + byte[] decrypted = sm4.Sm4CryptEcb(ctx, Hex.Decode(entity.Data)); + return Encoding.Default.GetString(decrypted); + } + /// + /// CBC解密 + /// + /// + /// + public static string DecryptCBC(SM4Utils entity) + { + Sm4Context ctx = new Sm4Context + { + IsPadding = true, + Mode = 0 + }; + byte[] keyBytes = entity.HexString ? Hex.Decode(entity.Key) : Encoding.Default.GetBytes(entity.Key); + byte[] ivBytes = entity.HexString ? Hex.Decode(entity.Iv) : Encoding.Default.GetBytes(entity.Iv); + SM4 sm4 = new SM4(); + sm4.Sm4SetKeyDec(ctx, keyBytes); + byte[] decrypted = sm4.Sm4CryptCbc(ctx, ivBytes, Convert.FromBase64String(entity.Data)); + return Encoding.Default.GetString(decrypted); + } + #endregion + /// + /// 加密类型 + /// + public enum Sm4CryptoEnum + { + /// + /// ECB(电码本模式) + /// + [Description("ECB模式")] + ECB = 0, + /// + /// CBC(密码分组链接模式) + /// + [Description("CBC模式")] + CBC = 1 + } + } + /// + /// + /// + internal class Sm4Context + { + public Sm4Context() + { + Mode = 1; + IsPadding = true; + Key = new long[32]; + } + /// + /// 1表示加密,0表示解密 + /// + public int Mode; + /// + /// 密钥 + /// + public long[] Key; + /// + /// 是否补足16进制字符串 + /// + public bool IsPadding; + } + /// + /// + /// + internal class SM4 + { + /// + /// 加密 非线性τ函数B=τ(A) + /// + /// + /// + /// + private static long GetULongByBe(byte[] b, int i) + { + long n = (long)(b[i] & 0xff) << 24 | + (long)((b[i + 1] & 0xff) << 16) | + (long)((b[i + 2] & 0xff) << 8) | + (long)(b[i + 3] & 0xff) & 0xffffffffL; + return n; + } + /// + /// 解密 非线性τ函数B=τ(A) + /// + /// + /// + /// + private static void PutULongToBe(long n, byte[] b, int i) + { + b[i] = (byte)(int)(0xFF & n >> 24); + b[i + 1] = (byte)(int)(0xFF & n >> 16); + b[i + 2] = (byte)(int)(0xFF & n >> 8); + b[i + 3] = (byte)(int)(0xFF & n); + } + /// + /// 循环移位,为32位的x循环左移n位 + /// + /// + /// + /// + private static long Rotl(long x, int n) + { + return ((x & 0xFFFFFFFF) << n) | x >> (32 - n); + } + /// + /// 将密钥逆序 + /// + /// + /// + private static void Swap(long[] sk, int i) + { + long t = sk[i]; + sk[i] = sk[(31 - i)]; + sk[(31 - i)] = t; + } + /// + /// S盒 + /// + public byte[] SboxTable = new byte[] { + // 0 1 2 3 4 5 6 7 8 9 a b c d e f + 0xd6, 0x90, 0xe9, 0xfe, 0xcc, 0xe1, 0x3d, 0xb7, 0x16, 0xb6, 0x14, 0xc2, 0x28, 0xfb, 0x2c, 0x05, + 0x2b, 0x67, 0x9a, 0x76, 0x2a, 0xbe, 0x04, 0xc3, 0xaa, 0x44, 0x13, 0x26, 0x49, 0x86, 0x06, 0x99, + 0x9c, 0x42, 0x50, 0xf4, 0x91, 0xef, 0x98, 0x7a, 0x33, 0x54, 0x0b, 0x43, 0xed, 0xcf, 0xac, 0x62, + 0xe4, 0xb3, 0x1c, 0xa9, 0xc9, 0x08, 0xe8, 0x95, 0x80, 0xdf, 0x94, 0xfa, 0x75, 0x8f, 0x3f, 0xa6, + 0x47, 0x07, 0xa7, 0xfc, 0xf3, 0x73, 0x17, 0xba, 0x83, 0x59, 0x3c, 0x19, 0xe6, 0x85, 0x4f, 0xa8, + 0x68, 0x6b, 0x81, 0xb2, 0x71, 0x64, 0xda, 0x8b, 0xf8, 0xeb, 0x0f, 0x4b, 0x70, 0x56, 0x9d, 0x35, + 0x1e, 0x24, 0x0e, 0x5e, 0x63, 0x58, 0xd1, 0xa2, 0x25, 0x22, 0x7c, 0x3b, 0x01, 0x21, 0x78, 0x87, + 0xd4, 0x00, 0x46, 0x57, 0x9f, 0xd3, 0x27, 0x52, 0x4c, 0x36, 0x02, 0xe7, 0xa0, 0xc4, 0xc8, 0x9e, + 0xea, 0xbf, 0x8a, 0xd2, 0x40, 0xc7, 0x38, 0xb5, 0xa3, 0xf7, 0xf2, 0xce, 0xf9, 0x61, 0x15, 0xa1, + 0xe0, 0xae, 0x5d, 0xa4, 0x9b, 0x34, 0x1a, 0x55, 0xad, 0x93, 0x32, 0x30, 0xf5, 0x8c, 0xb1, 0xe3, + 0x1d, 0xf6, 0xe2, 0x2e, 0x82, 0x66, 0xca, 0x60, 0xc0, 0x29, 0x23, 0xab, 0x0d, 0x53, 0x4e, 0x6f, + 0xd5, 0xdb, 0x37, 0x45, 0xde, 0xfd, 0x8e, 0x2f, 0x03, 0xff, 0x6a, 0x72, 0x6d, 0x6c, 0x5b, 0x51, + 0x8d, 0x1b, 0xaf, 0x92, 0xbb, 0xdd, 0xbc, 0x7f, 0x11, 0xd9, 0x5c, 0x41, 0x1f, 0x10, 0x5a, 0xd8, + 0x0a, 0xc1, 0x31, 0x88, 0xa5, 0xcd, 0x7b, 0xbd, 0x2d, 0x74, 0xd0, 0x12, 0xb8, 0xe5, 0xb4, 0xb0, + 0x89, 0x69, 0x97, 0x4a, 0x0c, 0x96, 0x77, 0x7e, 0x65, 0xb9, 0xf1, 0x09, 0xc5, 0x6e, 0xc6, 0x84, + 0x18, 0xf0, 0x7d, 0xec, 0x3a, 0xdc, 0x4d, 0x20, 0x79, 0xee, 0x5f, 0x3e, 0xd7, 0xcb, 0x39, 0x48 + }; + /// + /// 系统参数FK + /// + public uint[] FK = { 0xa3b1bac6, 0x56aa3350, 0x677d9197, 0xb27022dc }; + /// + /// 固定参数CK + /// + public uint[] CK = { + 0x00070e15,0x1c232a31,0x383f464d,0x545b6269, + 0x70777e85,0x8c939aa1,0xa8afb6bd,0xc4cbd2d9, + 0xe0e7eef5,0xfc030a11,0x181f262d,0x343b4249, + 0x50575e65,0x6c737a81,0x888f969d,0xa4abb2b9, + 0xc0c7ced5,0xdce3eaf1,0xf8ff060d,0x141b2229, + 0x30373e45,0x4c535a61,0x686f767d,0x848b9299, + 0xa0a7aeb5,0xbcc3cad1,0xd8dfe6ed,0xf4fb0209, + 0x10171e25,0x2c333a41,0x484f565d,0x646b7279 + }; + /// + /// Sm4的S盒取值 + /// + /// + /// + private byte Sm4Sbox(byte inch) + { + int i = inch & 0xFF; + byte retVal = SboxTable[i]; + return retVal; + } + /// + /// 线性变换 L + /// + /// + /// + private long Sm4Lt(long ka) + { + byte[] a = new byte[4]; + byte[] b = new byte[4]; + PutULongToBe(ka, a, 0); + b[0] = Sm4Sbox(a[0]); + b[1] = Sm4Sbox(a[1]); + b[2] = Sm4Sbox(a[2]); + b[3] = Sm4Sbox(a[3]); + long bb = GetULongByBe(b, 0); + long c = bb ^ Rotl(bb, 2) ^ Rotl(bb, 10) ^ Rotl(bb, 18) ^ Rotl(bb, 24); + return c; + } + /// + /// 轮函数 F + /// + /// + /// + /// + /// + /// + /// + private long Sm4F(long x0, long x1, long x2, long x3, long rk) + { + return x0 ^ Sm4Lt(x1 ^ x2 ^ x3 ^ rk); + } + /// + /// 轮密钥rk + /// + /// + /// + private long Sm4CalciRk(long ka) + { + byte[] a = new byte[4]; + byte[] b = new byte[4]; + PutULongToBe(ka, a, 0); + b[0] = Sm4Sbox(a[0]); + b[1] = Sm4Sbox(a[1]); + b[2] = Sm4Sbox(a[2]); + b[3] = Sm4Sbox(a[3]); + long bb = GetULongByBe(b, 0); + long rk = bb ^ Rotl(bb, 13) ^ Rotl(bb, 23); + return rk; + } + /// + /// 加密密钥 + /// + /// + /// + private void SetKey(long[] SK, byte[] key) + { + //加密密钥长度为 128 比特 + long[] MK = new long[4]; + int i = 0; + MK[0] = GetULongByBe(key, 0); + MK[1] = GetULongByBe(key, 4); + MK[2] = GetULongByBe(key, 8); + MK[3] = GetULongByBe(key, 12); + long[] k = new long[36]; + //轮密钥生成方法 + k[0] = MK[0] ^ (long)FK[0]; + k[1] = MK[1] ^ (long)FK[1]; + k[2] = MK[2] ^ (long)FK[2]; + k[3] = MK[3] ^ (long)FK[3]; + for (; i < 32; i++) + { + k[(i + 4)] = (k[i] ^ Sm4CalciRk(k[(i + 1)] ^ k[(i + 2)] ^ k[(i + 3)] ^ (long)CK[i])); + SK[i] = k[(i + 4)]; + } + } + /// + /// 解密函数 + /// + /// 轮密钥 + /// 输入分组的密文 + /// 输出的对应的分组明文 + private void Sm4OneRound(long[] sk, byte[] input, byte[] output) + { + int i = 0; + long[] ulbuf = new long[36]; + ulbuf[0] = GetULongByBe(input, 0); + ulbuf[1] = GetULongByBe(input, 4); + ulbuf[2] = GetULongByBe(input, 8); + ulbuf[3] = GetULongByBe(input, 12); + while (i < 32) //开始32轮解密 ,一次进行4轮,共计八次 + { + ulbuf[(i + 4)] = Sm4F(ulbuf[i], ulbuf[(i + 1)], ulbuf[(i + 2)], ulbuf[(i + 3)], sk[i]); + i++; + } + PutULongToBe(ulbuf[35], output, 0); + PutULongToBe(ulbuf[34], output, 4); + PutULongToBe(ulbuf[33], output, 8); + PutULongToBe(ulbuf[32], output, 12); + } + /// + /// 补足 16 进制字符串的 0 字符,返回不带 0x 的16进制字符串 + /// + /// + /// 1表示加密,0表示解密 + /// + private static byte[] Padding(byte[] input, int mode) + { + if (input == null) + { + return null; + } + byte[] ret = (byte[])null; + if (mode == 1) + { + int p = 16 - input.Length % 16; + ret = new byte[input.Length + p]; + Array.Copy(input, 0, ret, 0, input.Length); + for (int i = 0; i < p; i++) + { + ret[input.Length + i] = (byte)p; + } + } + else + { + int p = input[input.Length - 1]; + ret = new byte[input.Length - p]; + Array.Copy(input, 0, ret, 0, input.Length - p); + } + return ret; + } + /// + /// 设置加密的key + /// + /// + /// + public void SetKeyEnc(Sm4Context ctx, byte[] key) + { + ctx.Mode = 1; + SetKey(ctx.Key, key); + } + /// + /// 设置解密的key + /// + /// + /// + public void Sm4SetKeyDec(Sm4Context ctx, byte[] key) + { + ctx.Mode = 0; + SetKey(ctx.Key, key); + int i; + for (i = 0; i < 16; i++) + { + Swap(ctx.Key, i); + } + } + /// + /// ECB + /// + /// + /// + /// + public byte[] Sm4CryptEcb(Sm4Context ctx, byte[] input) + { + if (ctx.IsPadding && (ctx.Mode == 1)) + { + input = Padding(input, 1); + } + int length = input.Length; + byte[] bins = new byte[length]; + Array.Copy(input, 0, bins, 0, length); + byte[] bous = new byte[length]; + for (int i = 0; length > 0; length -= 16, i++) + { + byte[] inBytes = new byte[16]; + byte[] outBytes = new byte[16]; + Array.Copy(bins, i * 16, inBytes, 0, length > 16 ? 16 : length); + Sm4OneRound(ctx.Key, inBytes, outBytes); + Array.Copy(outBytes, 0, bous, i * 16, length > 16 ? 16 : length); + } + if (ctx.IsPadding && ctx.Mode == 0) + { + bous = Padding(bous, 0); + } + return bous; + } + /// + /// CBC + /// + /// + /// + /// + /// + public byte[] Sm4CryptCbc(Sm4Context ctx, byte[] iv, byte[] input) + { + if (ctx.IsPadding && ctx.Mode == 1) + { + input = Padding(input, 1); + } + int length = input.Length; + byte[] bins = new byte[length]; + Array.Copy(input, 0, bins, 0, length); + List bousList = new List(); + int i; + if (ctx.Mode == 1) + { + for (int j = 0; length > 0; length -= 16, j++) + { + byte[] inBytes = new byte[16]; + byte[] outBytes = new byte[16]; + byte[] out1 = new byte[16]; + Array.Copy(bins, j * 16, inBytes, 0, length > 16 ? 16 : length); + for (i = 0; i < 16; i++) + { + outBytes[i] = ((byte)(inBytes[i] ^ iv[i])); + } + Sm4OneRound(ctx.Key, outBytes, out1); + Array.Copy(out1, 0, iv, 0, 16); + for (int k = 0; k < 16; k++) + { + bousList.Add(out1[k]); + } + } + } + else + { + byte[] temp = new byte[16]; + for (int j = 0; length > 0; length -= 16, j++) + { + byte[] inBytes = new byte[16]; + byte[] outBytes = new byte[16]; + byte[] out1 = new byte[16]; + Array.Copy(bins, j * 16, inBytes, 0, length > 16 ? 16 : length); + Array.Copy(inBytes, 0, temp, 0, 16); + Sm4OneRound(ctx.Key, inBytes, outBytes); + for (i = 0; i < 16; i++) + { + out1[i] = ((byte)(outBytes[i] ^ iv[i])); + } + Array.Copy(temp, 0, iv, 0, 16); + for (int k = 0; k < 16; k++) + { + bousList.Add(out1[k]); + } + } + } + if (ctx.IsPadding && ctx.Mode == 0) + { + byte[] bous = Padding(bousList.ToArray(), 0); + return bous; + } + else + { + return bousList.ToArray(); + } + } + } + +} diff --git a/基础类库/HuizhongLibrary/SerialPortService.cs b/基础类库/HuizhongLibrary/SerialPortService.cs new file mode 100644 index 0000000..f3cd14a --- /dev/null +++ b/基础类库/HuizhongLibrary/SerialPortService.cs @@ -0,0 +1,304 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.IO.Ports; +using System.Threading; +using System.Collections; +using HuizhongLibrary.Network; +using HuizhongLibrary.Log; + +namespace HuizhongLibrary +{ + public class SerialPortService + { + private Byte[] m_Data; + public Byte[] Data + { + get { return m_Data; } + set { m_Data = value; } + } + private List m_SocketBuffer = new List(); + /// + /// 网络数据缓存 + /// + public List SocketBuffer + { + get { return m_SocketBuffer; } + set { m_SocketBuffer = value; } + } + private int m_RefshSecond = 30; + public int RefshSecond + { + get { return m_RefshSecond; } + set { m_RefshSecond = value; } + } + private int m_MaxWaitMsgNumber = 1; + /// + /// 最大消息等待回包数量(滑动窗口) + /// + public int MaxWaitMsgNumber + { + get { return m_MaxWaitMsgNumber; } + set { m_MaxWaitMsgNumber = value; } + } + private int m_ReadBufferSize = 4096; + public int ReadBufferSize + { + get { return m_ReadBufferSize; } + set { m_ReadBufferSize = value; } + } + private int m_WriteBufferSize = 4096; + public int WriteBufferSize + { + get { return m_WriteBufferSize; } + set { m_WriteBufferSize = value; } + } + private string m_StringNewLine = "0"; + /// + /// 读取数据的方式(0 byte方式读取1按回车读取 + /// + public string StringNewLine + { + get { return m_StringNewLine; } + set { m_StringNewLine = value; } + } + public int ReadSleep = 0; + public bool IsRunSendThread = true; + public int MaxSendNumber = 0; + + + public event Action ReceiveData; + public event Action SendData; + public event Action ReceiveString; + /// + /// 超出最大发送次数 + /// + public event Action OverMaxSend; + + public SocketMessages ListMessage = new SocketMessages(); + public int WaitMsgNumber = 0; + private AutoResetEvent AutoReset = new AutoResetEvent(false); + private bool IsRun = false; + private DateTime CacheDataTime = DateTime.Now; + + public SerialPortService() + { + + } + SerialPort comm = null; + #region 使用串口通讯 + public void Start(string PortName, int BaudRate, int DataBits, Parity par, StopBits sBits) + { + comm = new SerialPort(); + comm.ReadBufferSize = ReadBufferSize; + comm.WriteBufferSize = WriteBufferSize; + comm.PortName = PortName; + comm.BaudRate = BaudRate; + comm.DataBits = DataBits; + comm.Parity = par; + comm.StopBits = sBits; + //comm.ReadTimeout = 500; + //comm.WriteTimeout = 500; + comm.NewLine = StringNewLine; + comm.Encoding = Encoding.Default; + comm.DataReceived += new SerialDataReceivedEventHandler(comm_DataReceived); + comm.Open(); + if (IsRunSendThread == true) + { + IsRun = true; + Thread t1 = new Thread(new ThreadStart(this.WhileListUserSocket)); + t1.Start(); + } + } + #endregion + #region 停止通讯 + public void Stop() + { + this.IsRun = false; + if (comm!=null)comm.Close(); + } + #endregion + #region 读取到数据发生 + void comm_DataReceived(object sender, SerialDataReceivedEventArgs e) + { + if (ReadSleep > 0) Thread.Sleep(ReadSleep); + if (this.StringNewLine == "0") + { + int ReceiveLen = comm.BytesToRead;//先记录下来,避免某种原因,人为的原因,操作几次之间时间长,缓存不一致 + byte[] Bytes = new byte[ReceiveLen];//声明一个临时数组存储当前来的串口数据 + comm.Read(Bytes, 0, ReceiveLen); + AddData(Bytes, ReceiveLen); + if (this.ReceiveData != null) this.ReceiveData(comm); + } + else + { + try + { + while (true) + { + if (comm.BytesToRead == 0) return; + string RevData = comm.ReadLine(); + if (string.IsNullOrEmpty(RevData) == true) return; + if (this.ReceiveString != null) this.ReceiveString(RevData); + } + } + catch (Exception ex) + { + ErrorFollow.TraceWrite("comm_DataReceived", ex.StackTrace, ex.Message); + } + } + } + #endregion + + + #region 返回要发送的消息 + public SocketMessage GetNextSocketMessage(int RefshSecond) + { + try + { + var item = ListMessage.GetNextSocketMessage(RefshSecond); + if (item == null) return null; + if (item.SendNumber > 0) DecrementWaitMsgNumber(); + return item; + } + catch (Exception ex) + { + ErrorFollow.TraceWrite("SerialPortService.GetNextSocketMessage", ex.StackTrace, ex.Message); + } + return null; + } + #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); + } + #endregion、 + #region 消除已回复消息 + public SocketMessage EndWaitMsg(string SequenceID) + { + try + { + SocketMessage msg = ListMessage.CheckOut(SequenceID); + DecrementWaitMsgNumber(); + return msg; + } + catch (Exception ex) + { + ErrorFollow.TraceWrite("SerialPortService.IncrementWaitMsgNumber", ex.StackTrace, ex.Message); + } + return null; + } + #endregion + #region 消除已回复首行消息 + public SocketMessage EndFirstMsg() + { + try + { + SocketMessage msg = ListMessage.CheckOut(); + DecrementWaitMsgNumber(); + return msg; + } + catch (Exception ex) + { + ErrorFollow.TraceWrite("SerialPortService.EndFirstMsg", ex.StackTrace, ex.Message); + } + return null; + } + #endregion + #region 移除消息 + public void RemoveMsg(string FunNo) + { + try + { + ListMessage.Remove(FunNo); + } + catch (Exception ex) + { + ErrorFollow.TraceWrite("SerialPortService.RemoveMsg", ex.StackTrace, ex.Message); + } + } + #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 Send(byte[] Bytes) + { + comm.Write(Bytes, 0, Bytes.Length); + } + #endregion + #region 直接发送数据(String) + public void Send(string Data) + { + comm.Write(Data); + } + #endregion + #region 轮循消息列表 + void WhileListUserSocket() + { + while (IsRun) + { + SocketMessage Msg = GetNextSocketMessage(this.RefshSecond); + try + { + if (Msg != null) + { + Msg.SendTime = DateTime.Now; + Msg.SendNumber++; + IncrementWaitMsgNumber(); + if (this.MaxSendNumber > 0 && Msg.SendNumber > this.MaxSendNumber) + { + EndWaitMsg(Msg.SequenceID); + if (this.OverMaxSend != null) this.OverMaxSend(Msg); + continue; + } + comm.Write(Msg.Bytes, 0, Msg.Bytes.Length); + if (this.SendData != null) this.SendData(comm); + } + } + catch { } + AutoReset.WaitOne(500, false); + } + } + #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 + + } +} diff --git a/基础类库/HuizhongLibrary/SoundVoice.cs b/基础类库/HuizhongLibrary/SoundVoice.cs new file mode 100644 index 0000000..b5763b3 --- /dev/null +++ b/基础类库/HuizhongLibrary/SoundVoice.cs @@ -0,0 +1,364 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading; + +namespace HuizhongLibrary +{ + public class SoundVoice + { + private AutoResetEvent AutoReset = new AutoResetEvent(false); + //public event Action PlayFront; + Queue ListVoice = new Queue(); + private bool IsRun = false; + public SoundVoice() + { + + } + + #region 播放Wav + public void PlayWav(string FileName, bool IsSync) + { + if (IsSync == false) + { + + SystemInfo.W32_PlaySound(FileName, IntPtr.Zero, SystemInfo.SoundFlag.SND_SYNC + SystemInfo.SoundFlag.SND_FILENAME); + } + else + { + SystemInfo.W32_PlaySound(FileName, IntPtr.Zero, SystemInfo.SoundFlag.SND_ASYNC + SystemInfo.SoundFlag.SND_FILENAME); + } + } + #endregion + #region 播放Wav流 + public void PlayWav(byte[] source, bool IsSync) + { + if (IsSync == false) + { + SystemInfo.W32_PlaySound(source, IntPtr.Zero, SystemInfo.SoundFlag.SND_SYNC + SystemInfo.SoundFlag.SND_MEMORY); + } + else + { + SystemInfo.W32_PlaySound(source, IntPtr.Zero, SystemInfo.SoundFlag.SND_ASYNC + SystemInfo.SoundFlag.SND_MEMORY); + } + } + #endregion + #region 播放文件合并 + public byte[] WavUnion(List files) + { + try + { + MemoryStream msm = new MemoryStream(); + byte[] fsbyte = null; + for (int i = 0; i < files.Count; i++) + { + string filePath = files[i] + ".wav"; + if (File.Exists(filePath)) + { + FileInfo fi = new FileInfo(filePath); + FileStream fs = fi.OpenRead(); + if (i == 0) + { + fsbyte = new byte[fs.Length]; + } + else + { + fsbyte = new byte[fs.Length - 44]; + fs.Seek(44, SeekOrigin.Begin); + } + + fs.Read(fsbyte, 0, fsbyte.Length); + msm.Write(fsbyte, 0, fsbyte.Length); + fs.Close(); + + } + } + + if (files.Count > 1) + { + msm.Seek(4, SeekOrigin.Begin); + msm.Write(BitConverter.GetBytes(msm.Length - 8), 0, 4); + + msm.Seek(40, SeekOrigin.Begin); + msm.Write(BitConverter.GetBytes(msm.Length - 44), 0, 4); + } + + byte[] soundbyte = new byte[msm.Length]; + msm.Seek(0, SeekOrigin.Begin); + msm.Read(soundbyte, 0, soundbyte.Length); + msm.Close(); + return soundbyte; + } + catch + { + return null; + } + } + #endregion + #region 播放文件合并 + public byte[] WavUnion(string fileName) + { + List list = new List(); + list.Add(fileName); + return WavUnion(list); + } + #endregion + #region 停止播放WAV + public void StopWav() + { + ClearVoice(); + SystemInfo.W32_PlaySound((string)null, IntPtr.Zero, SystemInfo.SoundFlag.SND_FILENAME); + } + #endregion + #region 播放文本语音 + /// + /// 播放文本语音 + /// + /// 文本 + /// 朗读语速 + /// 朗读音量 + public void PlayVoice(string ptext, Int32 val, Int32 vol, bool IsSync) + { + //try + //{ + // if (IsSync == false) { SystemInfo.Tts_Play(ptext, val, vol, 0xAF18); } + // else { SystemInfo.Tts_Play_A(ptext, val, vol, 0xAF18); } + //} + //catch { } + } + #endregion + #region 停止语音播报 + public void StopPlayVoice() + { + try + { + ClearVoice(); + //SystemInfo.Tts_Stop(); + } + catch { } + } + #endregion + #region 转换金额 + public string MoneyToCHN(double dbFee) + { + if (dbFee == 2) return "两元"; + int iLoop = 0, iCur = 0, iCount = 0; + string strTemp = "", strMoney = "", strCur = "", strZero = ""; + string[] strDigital = new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }; + string[] strUnit = new string[] { "分", "角", "元", "十", "百", "千", "万", "十", "百", "千", "亿", "十", "百", "千", "万" }; + + strTemp = Convert.ToString(System.Math.Round(System.Math.Abs(dbFee) * 100, 0)); + + if (strTemp.Equals("") || strTemp.Equals("0")) + return "0元"; + + iCount = strTemp.Length; + if (iCount > strUnit.GetUpperBound(0) + 1) + return ""; + + + for (iLoop = 0; iLoop < iCount; iLoop++) + { + iCur = Convert.ToInt32(strTemp.Substring(iLoop, 1)) + 1; + strCur = strUnit[iCount - iLoop - 1]; + if (iCur == 1) + { + if (strCur.Equals("元") || strCur.Equals("亿")) + { + strMoney = strMoney + strCur; + strZero = ""; + } + else if (strCur.Equals("万")) + { + if (strMoney.Length < 2 || strMoney.Substring(strMoney.Length - 2, 2) != "亿") + { + strMoney = strMoney + strCur; + strZero = ""; + } + } + else + { + strZero = "0"; + } + } + else + { + strMoney = strMoney + strZero + strDigital[iCur - 1] + strCur; + strZero = ""; + } + } + + if (strMoney.Substring(strMoney.Length - 1, 1) != "分") + { + strMoney = strMoney + ""; + } + return strMoney; + } + #endregion + #region 数字转换 + public static string IntToCHN(long n, bool fang) + { + string strn = n.ToString(); + string str = ""; + string nn = "零壹贰叁肆伍陆柒捌玖"; + string ln = "零一二三四五六七八九"; + + string mm = " 拾佰仟萬拾佰仟亿拾佰仟萬兆拾佰仟萬亿"; + string lm = " 十百千万十百千亿十百千万兆十百千万亿"; + + int i = 0; + while (i < strn.Length)//>>>>>>>>>>>>>>>>出现空格 + { + + int m = int.Parse(strn.Substring(i, 1)); + if (fang)//返回繁体字 + { + str += nn.Substring(m, 1); + if (lm.Substring(strn.Length - i, 1) != " ") + { str += mm.Substring(strn.Length - i, 1); } + } + else//返回简体字 + { + str += ln.Substring(m, 1); + if (lm.Substring(strn.Length - i, 1) != " ") + { + str += lm.Substring(strn.Length - i, 1); + } + } + i++; + } + if (str.Substring(str.Length - 1) == "零") + { str = str.Substring(0, str.Length - 1); } + if (str.Length > 1 && str.Substring(0, 2) == "一十") + { str = str.Substring(1); } + if (str.Length > 1 && str.Substring(0, 2) == "壹拾") + { str = str.Substring(1); } + + return str; + } + #endregion + #region 设置金额文件列表 + public void SetMoney(ref List ListModel, string dir, string Money) + { + + string buy1 = Money; + string buy3 = ""; + + int i; + int k; + + //string CurrentPath = "";// "ResidentFlash"; + //string wavdir = "";// "Wav"; + + //buy4 = qz + ".wav" + "#"; + + string[] strUnit = new string[] { "分", "角", "元", "十", "百", "千", "万", "亿" }; + + for (i = 6; i >= 0; i--) + { + + k = buy1.IndexOf(strUnit[i]); + + if (k == -1) continue; + buy3 = buy1.Substring(0, k + 1); + buy1 = buy1.Remove(0, k + 1); + if (k <= 1) + { + ListModel.Add(dir + buy3); + } + else + { + ListModel.Add(dir + buy3.Substring(0, 1)); + ListModel.Add(dir + buy3.Substring(1, k)); + } + } + } + #endregion + #region 新增语音 + public void CheckIn(Voice item) + { + lock (ListVoice) + { + ListVoice.Enqueue(item); + } + } + #endregion + #region 读取语音 + public Voice CheckOut() + { + lock (ListVoice) + { + if (ListVoice.Count == 0) return null; + return ListVoice.Dequeue(); + } + } + #endregion + #region 清除语音 + public void Clear() + { + lock (ListVoice) + { + ListVoice.Clear(); + } + } + #endregion + #region 语音切断 + public void ClearVoice() + { + while (true) + { + Voice model = CheckOut(); + if (model == null) break; + } + + } + #endregion + #region 播放线程 + void OnStart() + { + IsRun = true; + while (IsRun == true) + { + Voice model = CheckOut(); + if (model != null) + { + if (model.VoiceType == 0) + { + PlayWav(model.Bytes, model.IsSync); + } + else + { + PlayVoice(model.Source, 0, 0, model.IsSync); + } + } + AutoReset.WaitOne(500, false); + } + } + #endregion + #region 开始执行播放 + public void Start() + { + Thread t = new Thread(this.OnStart); + t.Start(); + } + #endregion + #region 停止播放 + public void Stop() + { + IsRun = false; + } + #endregion + } + + + public class Voice + { + public byte[] Bytes; + public string Source = ""; + public int VoiceType = 0; + public bool IsSync = false; + } + +} diff --git a/基础类库/HuizhongLibrary/SqlSelectService/QueryService.cs b/基础类库/HuizhongLibrary/SqlSelectService/QueryService.cs new file mode 100644 index 0000000..465a2c8 --- /dev/null +++ b/基础类库/HuizhongLibrary/SqlSelectService/QueryService.cs @@ -0,0 +1,255 @@ +using HuizhongLibrary.Log; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Text; + +namespace HuizhongLibrary.Data +{ + #region 分页查询服务 + public class QueryService + { + /// + /// 表名 + /// + public string Tables { get; set; } + /// + /// 排序 + /// + public string Sort { get; set; } + /// + /// 当前页索引 + /// + public int PageIndex { get; set; } + /// + /// 每页行数 + /// + public int PageSize { get; set; } + /// + /// 列名 + /// + public string Fields { get; set; } + /// + /// 条件 + /// + public string Filter { get; set; } + /// + /// 主键 + /// + public string KeyName { get; set; } + + public string GetText() + { + if (string.IsNullOrEmpty(Tables) == true) throw new Exception("表名不能为空"); + if (string.IsNullOrEmpty(Fields) == true) throw new Exception("列名不能为空"); + if (string.IsNullOrEmpty(KeyName) == true) throw new Exception("主键不能为空"); + if (PageIndex < 1) throw new Exception("当前页不能小于1"); + if (PageSize < 1) throw new Exception("每页行数不能小于1"); + if (string.IsNullOrEmpty(Sort) == true) { Sort = " order by " + this.KeyName + " desc"; } + else { Sort = " order by " + Sort; } + string tsql = ""; + if (PageIndex == 1) + { + //第一页提高性能 + //查询记录总数,返回给@RowCount输出参数 + tsql += "select @RowCount=count(0) from " + Tables + " " + Filter + "\r\n"; + //返回数据 + tsql += "select top " + PageSize.ToString() + " " + Fields + " from " + Tables + " " + Filter + " " + Sort; + } + else + { + int start = PageSize * (PageIndex - 1) + 1; + int stop = PageSize * PageIndex; + //查询记录总数,返回给@RowCount输出参数 + tsql += "select @RowCount=count(1) from " + Tables + " " + Filter + "\r\n"; + + //插入临时表 + tsql += @"select top " + stop.ToString() + " identity(int,1,1) as RowIndex," + Fields + " into #temptable from " + Tables + " " + Filter + " " + Sort + "\r\n"; + //查询总记录数 + //tsql += "select @RowCount=count(1) from #temptable" + "\r\n"; + //返回数据 + tsql += "select * from #temptable where RowIndex between " + start.ToString() + " and " + stop.ToString(); + } + bool bk= CustomIO.CheckSQL(tsql,false); + if (bk == false) + { + ErrorFollow.TraceWrite("疑似SQL注入攻击,不允许执行", "", tsql); + throw new Exception("疑似SQL注入攻击,不允许执行"); + } + bk = CustomIO.CheckSQL(Sort, true); + if (bk == false) + { + ErrorFollow.TraceWrite("疑似SQL注入攻击,不允许执行", "", tsql); + throw new Exception("疑似SQL注入攻击,不允许执行"); + } + return tsql; + } + } + #endregion + #region 分页查询服务2 + public class QueryService2 + { + /// + /// 排序 + /// + public string Sort { get; set; } + /// + /// 当前页索引 + /// + public int PageIndex { get; set; } + /// + /// 每页行数 + /// + public int PageSize { get; set; } + /// + /// Tsql + /// + public string Tsql { get; set; } + + + public string GetText() + { + if (string.IsNullOrEmpty(Tsql) == true) throw new Exception("Tsql不能为空"); + if (PageIndex < 1) throw new Exception("当前页不能小于1"); + if (PageSize < 1) throw new Exception("每页行数不能小于1"); + Sort = " order by " + Sort; + + + CompareInfo Compare = CultureInfo.InvariantCulture.CompareInfo; + int index = Compare.IndexOf(this.Tsql, "from", CompareOptions.IgnoreCase); + int index2 = Compare.IndexOf(this.Tsql, "select", CompareOptions.IgnoreCase)+6; + string tsql2 = this.Tsql.Substring(index); + string tsql = "select @RowCount=count(0) "+ tsql2 + System.Environment.NewLine; + + if (PageIndex == 1) + { + //第一页提高性能 + //查询记录总数,返回给@RowCount输出参数 + //返回数据 + tsql += "select top " + PageSize.ToString() + " " + this.Tsql.Substring(index2) + " " + Sort; + } + else + { + int start = PageSize * (PageIndex - 1) + 1; + int stop = PageSize * PageIndex; + //查询记录总数,返回给@RowCount输出参数 + //插入临时表 + tsql += @"select top " + stop.ToString() + " identity(int,1,1) as RowIndex," + this.Tsql.Substring(index2, index- index2) + " into #temptable " + tsql2 + " " + Sort + System.Environment.NewLine; + //查询总记录数 + //tsql += "select @RowCount=count(1) from #temptable" + "\r\n"; + //返回数据 + tsql += "select * from #temptable where RowIndex between " + start.ToString() + " and " + stop.ToString(); + } + bool bk = CustomIO.CheckSQL(tsql, false); + if (bk == false) + { + ErrorFollow.TraceWrite("疑似SQL注入攻击,不允许执行", "", tsql); + throw new Exception("疑似SQL注入攻击,不允许执行"); + } + bk = CustomIO.CheckSQL(Sort, true); + if (bk == false) + { + ErrorFollow.TraceWrite("疑似SQL注入攻击,不允许执行", "", tsql); + throw new Exception("疑似SQL注入攻击,不允许执行"); + } + return tsql; + } + + public string Filter(string where) + { + return where; + } + + + + } + #endregion + + #region 普通查询服务 + public class QueryOrdService + { + /// + /// 表名 + /// + public string Tables { get; set; } + /// + /// 排序 + /// + public string Sort { get; set; } + /// + /// 列名 + /// + public string Fields { get; set; } + /// + /// 条件 + /// + public string Filter { get; set; } + /// + /// 主键 + /// + public string KeyName { get; set; } + + public string GetText() + { + if (string.IsNullOrEmpty(Tables) == true) throw new Exception("表名不能为空"); + if (string.IsNullOrEmpty(Fields) == true) throw new Exception("列名不能为空"); + if (string.IsNullOrEmpty(Sort) == true) { Sort = " order by " + this.KeyName + " desc"; } + + else { Sort = " order by " + Sort; } + + string tsql = "select " + Fields + " from " + Tables + " " + Filter + Sort + "\r\n"; + bool bk = CustomIO.CheckSQL(tsql, false); + if (bk == false) + { + ErrorFollow.TraceWrite("疑似SQL注入攻击,不允许执行", "", tsql); + throw new Exception("疑似SQL注入攻击,不允许执行"); + } + bk = CustomIO.CheckSQL(Sort, true); + if (bk == false) + { + ErrorFollow.TraceWrite("疑似SQL注入攻击,不允许执行", "", tsql); + throw new Exception("疑似SQL注入攻击,不允许执行"); + } + return tsql; + } + } + #endregion + #region 普通查询服务2 + public class QueryOrdService2 + { + /// + /// 排序 + /// + public string Sort { get; set; } + /// + /// Tsql + /// + public string Tsql { get; set; } + + + public string GetText() + { + if (string.IsNullOrEmpty(Tsql) == true) throw new Exception("Tsql不能为空"); + if (string.IsNullOrEmpty(Sort)==false)Sort = " order by " + Sort; + CompareInfo Compare = CultureInfo.InvariantCulture.CompareInfo; + int index = Compare.IndexOf(this.Tsql, "select", CompareOptions.IgnoreCase) + 6; + string tsql = "select " + this.Tsql.Substring(index) + " " + Sort; + bool bk = CustomIO.CheckSQL(tsql, false); + if (bk == false) + { + ErrorFollow.TraceWrite("疑似SQL注入攻击,不允许执行", "", tsql); + throw new Exception("疑似SQL注入攻击,不允许执行"); + } + bk = CustomIO.CheckSQL(Sort, true); + if (bk == false) + { + ErrorFollow.TraceWrite("疑似SQL注入攻击,不允许执行", "", tsql); + throw new Exception("疑似SQL注入攻击,不允许执行"); + } + return tsql; + } + } + #endregion + +} diff --git a/基础类库/HuizhongLibrary/SqlSelectService/RefParameter.cs b/基础类库/HuizhongLibrary/SqlSelectService/RefParameter.cs new file mode 100644 index 0000000..0725983 --- /dev/null +++ b/基础类库/HuizhongLibrary/SqlSelectService/RefParameter.cs @@ -0,0 +1,1153 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Text; +using System.Text.RegularExpressions; +using HuizhongLibrary.RegularExpressions; + +namespace HuizhongLibrary.Data +{ + public class RefParameter + { + public RefParameter() + { + this.Caption = Guid.NewGuid().ToString().Replace("-", ""); + } + + public RefParameter(string name, ConditionType Condition, Object Value, DbType Type) + { + if (name == null || name == "") throw new Exception("ֶƲΪ"); + this.Caption = Guid.NewGuid().ToString().Replace("-", ""); + this.Name = name; + this.Condition = ConvertConditionType(Condition); + this.Type = Type; + this.Value = Value; + CheckValue(Value, Type); + } + + public RefParameter(string name, ConditionTypeNull Condition) + { + if (name == null || name == "") throw new Exception("ֶƲΪ"); + this.Caption = Guid.NewGuid().ToString().Replace("-", ""); + this.Name = name; + this.Condition = ConvertConditionTypeNull(Condition); + this.Type = DbType.String; + this.Value = ""; + + } + + public RefParameter(string name, string Condition, Object Value, DbType Type) + { + if (name == null || name == "") throw new Exception("ֶƲΪ"); + if (Condition == null || Condition == "") throw new Exception("Ϊ"); + CheckCondition(Condition); + this.Caption = Guid.NewGuid().ToString().Replace("-", ""); + this.Name = name; + this.Condition = Condition; + this.Type = Type; + this.Value = Value; + CheckValue(Value, Type); + } + + public RefParameter(string name, string Condition, string Value) + { + if (name == null || name == "") throw new Exception("ֶƲΪ"); + if (Condition == null || Condition == "") throw new Exception("Ϊ"); + CheckCondition(Condition); + this.Caption = Guid.NewGuid().ToString().Replace("-", ""); + this.Name = name; + this.Condition = Condition; + this.Type = Type; + this.Value = Value; + + } + + + /// + /// һ + /// + /// + /// ϵ + /// ֵ + /// + /// Ƿ(trueĬ,falseɵ,Ϊ@name) + public RefParameter(string name, string Condition, Object Value, DbType Type, bool IsDeclare) + { + if (name == null || name == "") throw new Exception("ֶƲΪ"); + if (Condition == null || Condition == "") throw new Exception("Ϊ"); + CheckCondition(Condition); + this.Caption = Guid.NewGuid().ToString().Replace("-", ""); + this.Name = name; + this.Type = Type; + this.Condition = Condition; + this.Value = Value; + this.IsDeclare = IsDeclare; + CheckValue(Value, Type); + } + + public RefParameter(string name, ConditionType Condition, Object Value, DbType Type, bool IsDeclare) + { + if (name == null || name == "") throw new Exception("ֶƲΪ"); + this.Caption = Guid.NewGuid().ToString().Replace("-", ""); + this.Name = name; + this.Condition = ConvertConditionType(Condition); + this.Type = Type; + this.Value = Value; + this.IsDeclare = IsDeclare; + CheckValue(Value, Type); + } + + public RefParameter(string name, string Condition, Object Value, string RelateTo, DbType Type) + { + if (name == null || name == "") throw new Exception("ֶƲΪ"); + if (Condition == null || Condition == "") throw new Exception("Ϊ"); + CheckCondition(Condition); + CheckRelateTo(RelateTo); + this.Caption = Guid.NewGuid().ToString().Replace("-", ""); + this.Name = name; + this.Condition = Condition; + this.Type = Type; + this.Value = Value; + this.RelateTo = RelateTo; + CheckValue(Value, Type); + } + + public RefParameter(string name, string Condition, Object Value, string RelateTo, string EndString, DbType Type) + { + if (name == null || name == "") throw new Exception("ֶƲΪ"); + if (Condition == null || Condition == "") throw new Exception("Ϊ"); + CheckCondition(Condition); + CheckRelateTo(RelateTo); + this.Caption = Guid.NewGuid().ToString().Replace("-", ""); + this.Name = name; + this.Condition = Condition; + this.EndString = EndString; + this.Type = Type; + this.Value = Value; + this.RelateTo = RelateTo; + CheckValue(Value, Type); + } + + public RefParameter(string name, ConditionType Condition, Object Value, string RelateTo, DbType Type) + { + if (name == null || name == "") throw new Exception("ֶƲΪ"); + CheckRelateTo(RelateTo); + this.Caption = Guid.NewGuid().ToString().Replace("-", ""); + this.Type = Type; + this.Name = name; + this.Condition = ConvertConditionType(Condition); + this.Value = Value; + this.RelateTo = RelateTo; + CheckValue(Value, Type); + } + + public RefParameter(string name, string Condition, Object Value, string RelateTo, DbType Type, ParameterDirection Direction) + { + if (name == null || name == "") throw new Exception("ֶƲΪ"); + if (Condition == null || Condition == "") throw new Exception("Ϊ"); + CheckCondition(Condition); + CheckRelateTo(RelateTo); + this.Caption = Guid.NewGuid().ToString().Replace("-", ""); + this.Name = name; + this.Condition = Condition; + this.Type = Type; + this.Value = Value; + this.RelateTo = RelateTo; + this.Direction = Direction; + CheckValue(Value, Type); + } + + public RefParameter(string name, ConditionType Condition, Object Value, string RelateTo, DbType Type, ParameterDirection Direction) + { + if (name == null || name == "") throw new Exception("ֶƲΪ"); + CheckRelateTo(RelateTo); + this.Caption = Guid.NewGuid().ToString().Replace("-", ""); + this.Name = name; + this.Condition = ConvertConditionType(Condition); + this.Type = Type; + this.Value = Value; + this.RelateTo = RelateTo; + this.Direction = Direction; + CheckValue(Value, Type); + } + + private void CheckRelateTo(string RelateTo) + { + if (RelateTo != "and" && RelateTo != "or") + { + throw new Exception("֮ϵֻandor"); + } + } + + private void CheckCondition(string Condition) + {//Ƿд + if (Condition != ">=" && Condition != "<=" && Condition != ">" && Condition != "<" && Condition != "=" && Condition != "<>" && Condition != "in" && Condition != "not in" && Condition != "like left" && Condition != "like right" && Condition != "like" && Condition != "is" && Condition != "is not" && Condition != "where") throw new Exception("ѯֻΪ>,<,=,<>,in, not in,like left,like right,like,is,is not,where"); + } + + #region תConditionType + private string ConvertConditionType(ConditionType ctype) + { + switch (ctype) + { + case ConditionType.Equals: + return "="; + case ConditionType.Ceiling: + return ">"; + case ConditionType.CeilingEqual: + return ">="; + case ConditionType.Floor: + return "<"; + case ConditionType.FloorEqual: + return "<="; + case ConditionType.NotEquals: + return "<>"; + case ConditionType.In: + return "in"; + case ConditionType.NotIn: + return "not in"; + case ConditionType.LikeLeft: + return "like left"; + case ConditionType.LikeRight: + return "like right"; + case ConditionType.Like: + return "like"; + default: + return ""; + } + } + #endregion + + #region תConditionTypeNull + private string ConvertConditionTypeNull(ConditionTypeNull ctype) + { + switch (ctype) + { + case ConditionTypeNull.Is: + return "is"; + case ConditionTypeNull.IsNot: + return "is not"; + default: + return ""; + } + } + #endregion + + private void CheckValue(Object Value, DbType Type) + {//Ƿ + if (Value == null || Value.ToString() == "" || Type == DbType.String) return; + if (Type == DbType.Object) return; + if (this.Condition == "in" || this.Condition == "not in") + { + string[] chars1 = Value.ToString().Split(new char[] { ',' }); + foreach (string s in chars1) + { + if (Type == DbType.Byte || Type == DbType.Int16 || Type == DbType.Int32 || Type == DbType.Int64) + { + if (DataRegex.IsNumberInteger(s) == false) throw new Exception(this.Name + ":" + Value.ToString() + ":ֻ"); + } + else + { + if (DataRegex.IsNumberDouble(s) == false) throw new Exception(this.Name + ":" + Value.ToString() + ":ֻǸ"); + } + } + return; + } + if (Type == DbType.DateTime) + { + try { Convert.ToDateTime(Value); } + catch { throw new Exception(Value.ToString() + ":ֻڸʽ"); } + } + if (Type == DbType.Byte || Type == DbType.Int16 || Type == DbType.Int32 || Type == DbType.Int64) + { + if (DataRegex.IsNumberInteger(Value.ToString()) == false) throw new Exception(this.Name + ":" + Value.ToString() + ":ֻ"); + } + if (Type == DbType.Currency || Type == DbType.Single || Type == DbType.Decimal || Type == DbType.Double) + { + if (DataRegex.IsNumberDouble(Value.ToString()) == false) throw new Exception(this.Name + ":" + Value.ToString() + ":ֻǸ"); + } + if (Type == DbType.Boolean) + { + if (Value.ToString() != "True" && Value.ToString() != "False" && Value.ToString() != "0" && Value.ToString() != "1") + { + throw new Exception(this.Name + ":" + Value.ToString() + ":ֻTrueFalse01"); + } + } + } + + private string m_Caption; + + /// + /// б + /// + public string Caption + { + get { return m_Caption; } + set { m_Caption = value; } + } + + private string m_Name; + + /// + /// + /// + public string Name + { + get { return m_Name; } + set { m_Name = value; } + } + + private string m_Condition; + + /// + /// (,,С,,in, not in,like,like left,like right) + /// + public string Condition + { + get { return m_Condition; } + set + { + CheckCondition(value); + m_Condition = value; + } + } + + private Object m_Value; + + /// + /// ֵ + /// + public Object Value + { + get { return m_Value; } + set + { + CheckValue(value, this.Type); + if (value != null && value != DBNull.Value && this.Type == DbType.String) { m_Value = value.ToString().Replace("'", "''"); } + else { m_Value = value; } + } + } + + private string m_RelateTo = "and"; + + /// + /// ϵ(and,or)ĬΪand + /// + public string RelateTo + { + get { return m_RelateTo; } + set { m_RelateTo = value; } + } + private string m_EndString = ""; + /// + /// () + /// + public string EndString + { + get { return m_EndString; } + set { m_EndString = value; } + } + private System.Data.DbType m_Type = DbType.Object; + /// + /// + /// + public System.Data.DbType Type + { + get { return m_Type; } + set { m_Type = value; } + } + private ParameterDirection m_Direction = ParameterDirection.Input; + /// + /// + /// + public ParameterDirection Direction + { + get { return m_Direction; } + set { m_Direction = value; } + } + private bool m_IsDeclare = true; + /// + /// Ƿ(trueĬ,falseɵ,Ϊ@name) + /// + public bool IsDeclare + { + get { return m_IsDeclare; } + set { m_IsDeclare = value; } + } + } + + [Serializable] + public class RefParameterCollection : List + { + private int m_PageIndex = 1; + /// + /// ҳ + /// + public int PageIndex + { + get { return m_PageIndex; } + set { m_PageIndex = value; } + } + private int m_PageSize = 10; + /// + /// ÿҳʾ + /// + public int PageSize + { + get { return m_PageSize; } + set { m_PageSize = value; } + } + + public RefParameterCollection() + { } + + public RefParameterCollection(int PageIndex, int PageSize) + { + this.PageIndex = PageIndex; + this.PageSize = PageSize; + } + + public void Add(string name, ConditionType Condition, Object Value, DbType Type) + { + this.Add(new RefParameter(name, Condition, Value, Type)); + } + public void Add(string name, ConditionTypeNull Condition) + { + this.Add(new RefParameter(name, Condition)); + } + + public void Add(string name, string Condition, Object Value, DbType Type) + { + this.Add(new RefParameter(name, Condition, Value, Type)); + } + + /// + /// һ + /// + /// + /// ϵ + /// ֵ + /// + /// Ƿ(trueĬ,falseɵ,Ϊ@name) + public void Add(string name, string Condition, Object Value, DbType Type, bool IsDeclare) + { + this.Add(new RefParameter(name, Condition, Value, Type, IsDeclare)); + } + + + + public void Add(string name, ConditionType Condition, Object Value, DbType Type, bool IsDeclare) + { + this.Add(new RefParameter(name, Condition, Value, Type, IsDeclare)); + } + + public void Add(string name, string Condition, Object Value, string RelateTo, DbType Type) + { + this.Add(new RefParameter(name, Condition, Value, RelateTo, Type)); + } + + public void Add(string name, string Condition, Object Value, string RelateTo, string EndString, DbType Type) + { + this.Add(new RefParameter(name, Condition, Value, RelateTo, EndString, Type)); + } + + public void Add(string name, ConditionType Condition, Object Value, string RelateTo, DbType Type) + { + this.Add(new RefParameter(name, Condition, Value, RelateTo, Type)); + } + + public void Add(string name, string Condition, Object Value, string RelateTo, DbType Type, ParameterDirection Direction) + { + this.Add(new RefParameter(name, Condition, Value, RelateTo, Type, Direction)); + } + + public void Add(string name, ConditionType Condition, Object Value, string RelateTo, DbType Type, ParameterDirection Direction) + { + this.Add(new RefParameter(name, Condition, Value, RelateTo, Type, Direction)); + } + + public void AddOutParameter(string name, DbType Type) + { + this.Add(new RefParameter(name, "=", null, "and", Type, ParameterDirection.Output)); + } + + public bool Contains(string name) + { + foreach (RefParameter pam in this) + { + if (pam.Name == name) return true; + + } + return false; + } + + public RefParameter this[string name] + { + get + { + foreach (RefParameter cf in this) + { + if (cf.Name == name) return cf; + } + return null; + } + } + + public void Remove(string name) + { + foreach (RefParameter cf in this) + { + if (cf.Name == name) { this.Remove(cf); return; } + } + } + + #region תַ + private string ConvertUnionChar(string value) + { + string a = value; + a = a.ToString().Replace("*", "[*]"); + //a = a.ToString().Replace("~", "[~]"); + //a = a.ToString().Replace("(", "[(]"); + //a = a.ToString().Replace(")", "[)]"); + //a = a.ToString().Replace("#", "[#]"); + //a = a.ToString().Replace("/", "[/]"); + //a = a.ToString().Replace("=", "[=]"); + //a = a.ToString().Replace(">", "[>]"); + //a = a.ToString().Replace("<", "[<]"); + //a = a.ToString().Replace("+", "[+]"); + //a = a.ToString().Replace("-", "[-]"); + //a = a.ToString().Replace("|", "[|]"); + //a = a.ToString().Replace("^", "[^]"); + //a = a.ToString().Replace("%", "[%]"); + //a = a.ToString().Replace("&", "[&]"); + return a; + } + #endregion + + #region DataTableѯ + public string GetDataTableWhere() + { + string tsql = ""; + foreach (RefParameter pam in this) + { + string value = pam.Value.ToString(); + if (pam.Type == DbType.String) value = ConvertUnionChar(value); + if (this.IndexOf(pam) == 0) + { + switch (pam.Condition) + { + case "in": + if (pam.Type != DbType.String) + { + tsql = pam.Name + " in (" + value + ")" + pam.EndString; + } + else + { + string[] chars1 = pam.Value.ToString().Split(new char[] { ',' }); + string ss = ""; + foreach (string s in chars1) + { + if (ss == "") { ss = "'" + s + "'"; } + else { ss = ss + ",'" + s + "'"; } + } + tsql = pam.Name + " in (" + ss + ")" + pam.EndString; + } + break; + case "not in": + if (pam.Type != DbType.String) + { + tsql = pam.Name + " not in (" + value + ")" + pam.EndString; + } + else + { + string[] chars2 = value.Split(new char[] { ',' }); + string ss = ""; + foreach (string s in chars2) + { + if (ss == "") { ss = "'" + s + "'"; } + else { ss = ss + ",'" + s + "'"; } + } + + tsql = pam.Name + " not in (" + ss + ")" + pam.EndString; + } + break; + case "like": + tsql = pam.Name + " like '%" + value + "%'" + pam.EndString; + break; + case "like left": + tsql = pam.Name + " like '%" + value + "'" + pam.EndString; + break; + case "like right": + tsql = pam.Name + " like '" + value + "%'" + pam.EndString; + break; + case "is": + tsql = pam.Name + " is null" + pam.EndString; + break; + case "is not": + tsql = pam.Name + " is not null" + pam.EndString; + break; + default: + if (pam.Type == DbType.String && Convert.ToString(pam.Value) == "") + { + tsql = pam.Name + pam.Condition + "''" + pam.EndString; + } + else if (pam.Value == null || pam.Value == DBNull.Value) + { + tsql = pam.Name + " is null" + pam.EndString; + } + else if (pam.Type == DbType.String || pam.Type == DbType.DateTime) + { + tsql = pam.Name + pam.Condition + "'" + value + "'" + pam.EndString; + } + else + { + tsql = pam.Name + pam.Condition + value + pam.EndString; + } + break; + } + } + else + { + switch (pam.Condition) + { + case "in": + if (pam.Type != DbType.String) + { + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " in (" + value + ")" + pam.EndString; + } + else + { + string[] chars3 = pam.Value.ToString().Split(new char[] { ',' }); + string ss = ""; + foreach (string s in chars3) + { + if (ss == "") { ss = "'" + s + "'"; } + else { ss = ss + ",'" + s + "'"; } + } + + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " in (" + ss + ")" + pam.EndString; + } + break; + case "not in": + if (pam.Type != DbType.String) + { + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " not in (" + value + ")" + pam.EndString; + } + else + { + string[] chars4 = pam.Value.ToString().Split(new char[] { ',' }); + string ss = ""; + foreach (string s in chars4) + { + if (ss == "") { ss = "'" + s + "'"; } + else { ss = ss + ",'" + s + "'"; } + } + + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " not in (" + ss + ")" + pam.EndString; + } + break; + case "like": + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " like '%" + value + "%'" + pam.EndString; + break; + case "like left": + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " like '%" + value + "'" + pam.EndString; + break; + case "like right": + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " like '" + value + "%'" + pam.EndString; + break; + case "is": + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " is null" + pam.EndString; + break; + case "is not": + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " is not null" + pam.EndString; + break; + default: + if (pam.Type == DbType.String && Convert.ToString(pam.Value) == "") + { + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + pam.Condition + "''" + pam.EndString; + } + else if (pam.Value == null || pam.Value == DBNull.Value) + { + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " is null" + pam.EndString; + } + else if (pam.Type == DbType.String || pam.Type == DbType.DateTime) + { + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + pam.Condition + "'" + value + "'" + pam.EndString; + } + else + { + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + pam.Condition + value + pam.EndString; + } + + break; + } + } + } + return tsql; + } + #endregion + + #region + public string GetWhere(CommandType CommandType) + { + string tsql = ""; + if (this.Count != 0) + { + if (CommandType == CommandType.Text) + { + foreach (RefParameter pam in this) + { + if (pam.Direction != ParameterDirection.Input) continue; + if (pam.IsDeclare == false) continue; // + if (tsql.IndexOf("where") == -1) + { + + if (pam.Type == DbType.Object) + { + tsql += " where " + pam.Name + " " + pam.Condition + " " + pam.Value; + continue; + } + switch (pam.Condition) + { + case "in": + tsql = tsql + " where " + pam.Name + " " + pam.Condition + " (@" + pam.Caption + "0"; + string[] chars1 = pam.Value.ToString().Split(new char[] { ',' }); + for (int i = 1; i < chars1.Length; i++) + { + tsql = tsql + " ,@" + pam.Caption + i.ToString(); + } + tsql = tsql + ")" + pam.EndString; + break; + case "not in": + tsql = tsql + " where " + pam.Name + " " + pam.Condition + " (@" + pam.Caption + "0"; + string[] chars2 = pam.Value.ToString().Split(new char[] { ',' }); + for (int i = 1; i < chars2.Length; i++) + { + tsql = tsql + " ,@" + pam.Caption + i.ToString(); + } + tsql = tsql + ")" + pam.EndString; + break; + case "like": + tsql = tsql + " where " + pam.Name + " like '%'+" + "@" + pam.Caption + "+'%'" + pam.EndString; + break; + case "like left": + tsql = tsql + " where " + pam.Name + " like '%'+" + "@" + pam.Caption + pam.EndString; + break; + case "like right": + tsql = tsql + " where " + pam.Name + " like " + "@" + pam.Caption + "+'%'" + pam.EndString; + break; + case "is": + tsql = tsql + " where " + pam.Name + " is null" + pam.EndString; + break; + case "is not": + tsql = tsql + " where " + pam.Name + " is not null" + pam.EndString; + break; + case "where": + tsql = tsql + " where " + pam.Name; + break; + default: + if (pam.Type == DbType.String && Convert.ToString(pam.Value) == "") + { + tsql = tsql + " where " + pam.Name + pam.Condition + "''" + pam.EndString; + } + else if (pam.Value == null || pam.Value == DBNull.Value) + { + tsql = tsql + " where " + pam.Name + " is null" + pam.EndString; + } + else + { + tsql = tsql + " where " + pam.Name + pam.Condition + "@" + pam.Caption + pam.EndString; + } + break; + } + } + else + { + if (pam.Type == DbType.Object) + { + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " " + pam.Condition + " " + pam.Value; + continue; + } + switch (pam.Condition) + { + case "in": + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " " + pam.Condition + " (@" + pam.Caption + "0"; + string[] chars3 = pam.Value.ToString().Split(new char[] { ',' }); + for (int i = 1; i < chars3.Length; i++) + { + tsql = tsql + " ,@" + pam.Caption + i.ToString(); + } + tsql = tsql + ")" + pam.EndString; + break; + case "not in": + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " " + pam.Condition + " (@" + pam.Caption + "0"; + string[] chars4 = pam.Value.ToString().Split(new char[] { ',' }); + for (int i = 1; i < chars4.Length; i++) + { + tsql = tsql + " ,@" + pam.Caption + i.ToString(); + } + tsql = tsql + ")" + pam.EndString; + break; + case "like": + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " like '%'+" + "@" + pam.Caption + "+'%'" + pam.EndString; + break; + case "like left": + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " like '%'+" + "@" + pam.Caption + pam.EndString; + break; + case "like right": + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " like " + "@" + pam.Caption + "+'%'" + pam.EndString; + break; + case "is": + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " is null" + pam.EndString; + break; + case "is not": + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " is not null" + pam.EndString; + break; + case "where": + tsql = tsql + " " + pam.RelateTo + " " + pam.Name; + break; + default: + if (pam.Type == DbType.String && Convert.ToString(pam.Value) == "") + { + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + pam.Condition + "''" + pam.EndString; + } + else if (pam.Value == null || pam.Value == DBNull.Value) + { + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " is null" + pam.EndString; + } + else + { + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + pam.Condition + "@" + pam.Caption + pam.EndString; + } + break; + } + } + } + } + else + { + foreach (RefParameter pam in this) + { + if (pam.Direction != ParameterDirection.Input) continue; + if (pam.IsDeclare == false) continue; // + if (tsql.IndexOf("where") == -1) + { + switch (pam.Condition) + { + case "in": + if (pam.Type != DbType.String) + { + tsql = tsql + " where " + pam.Name + " in (" + pam.Value.ToString() + ")" + pam.EndString; + } + else + { + string[] chars1 = pam.Value.ToString().Split(new char[] { ',' }); + string ss = ""; + foreach (string s in chars1) + { + if (ss == "") { ss = "'" + s + "'"; } + else { ss = ss + ",'" + s + "'"; } + } + tsql = tsql + " where " + pam.Name + " in (" + ss + ")" + pam.EndString; + } + break; + case "not in": + if (pam.Type != DbType.String) + { + tsql = tsql + " where " + pam.Name + " not in (" + pam.Value.ToString() + ")" + pam.EndString; + } + else + { + string[] chars2 = pam.Value.ToString().Split(new char[] { ',' }); + string ss = ""; + foreach (string s in chars2) + { + if (ss == "") { ss = "'" + s + "'"; } + else { ss = ss + ",'" + s + "'"; } + } + tsql = tsql + " where " + pam.Name + " not in (" + ss + ")" + pam.EndString; + } + break; + case "like": + tsql = tsql + " where " + pam.Name + " like '%" + pam.Value.ToString() + "%'" + pam.EndString; + break; + case "like left": + tsql = tsql + " where " + pam.Name + " like '%" + pam.Value.ToString() + "'" + pam.EndString; + break; + case "like right": + tsql = tsql + " where " + pam.Name + " like '" + pam.Value.ToString() + "%'" + pam.EndString; + break; + case "is": + tsql = tsql + " where " + pam.Name + " is null" + pam.EndString; + break; + case "is not": + tsql = tsql + " where " + pam.Name + " is not null" + pam.EndString; + break; + default: + + if (pam.Type == DbType.String && Convert.ToString(pam.Value) == "") + { + tsql = " where " + pam.Name + pam.Condition + "''" + pam.EndString; + } + else if (pam.Value == null || pam.Value == DBNull.Value) + { + tsql = " where " + pam.Name + " is null" + pam.EndString; + } + else if (pam.Type == DbType.String || pam.Type == DbType.DateTime) + { + tsql = " where " + pam.Name + pam.Condition + "'" + pam.Value.ToString() + "'" + pam.EndString; + } + else + { + tsql = " where " + pam.Name + pam.Condition + pam.Value.ToString() + pam.EndString; + } + break; + } + + } + else + { + switch (pam.Condition) + { + case "in": + if (pam.Type != DbType.String) + { + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " in (" + pam.Value.ToString() + ")" + pam.EndString; + } + else + { + string[] chars3 = pam.Value.ToString().Split(new char[] { ',' }); + string ss = ""; + foreach (string s in chars3) + { + if (ss == "") { ss = "'" + s + "'"; } + else { ss = ss + ",'" + s + "'"; } + } + + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " in (" + ss + ")" + pam.EndString; + } + break; + case "not in": + if (pam.Type != DbType.String) + { + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " not in (" + pam.Value.ToString() + ")" + pam.EndString; + } + else + { + string[] chars4 = pam.Value.ToString().Split(new char[] { ',' }); + string ss = ""; + foreach (string s in chars4) + { + if (ss == "") { ss = "'" + s + "'"; } + else { ss = ss + ",'" + s + "'"; } + } + + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " not in (" + ss + ")" + pam.EndString; + } + break; + case "like": + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " like '%" + pam.Value.ToString() + "%'" + pam.EndString; + break; + case "like left": + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " like '%" + pam.Value.ToString() + "'" + pam.EndString; + break; + case "like right": + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " like '" + pam.Value.ToString() + "%'" + pam.EndString; + break; + case "is": + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " is null" + pam.EndString; + break; + case "is not": + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " is not null" + pam.EndString; + break; + default: + if (pam.Type == DbType.String && Convert.ToString(pam.Value) == "") + { + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + pam.Condition + "''" + pam.EndString; + } + else if (pam.Value == null || pam.Value == DBNull.Value) + { + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + " is null" + pam.EndString; + } + else if (pam.Type == DbType.String || pam.Type == DbType.DateTime) + { + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + pam.Condition + "'" + pam.Value.ToString() + "'" + pam.EndString; + } + else + { + tsql = tsql + " " + pam.RelateTo + " " + pam.Name + pam.Condition + pam.Value.ToString() + pam.EndString; + } + + break; + } + } + } + } + } + return tsql; + } + #endregion + + #region ز + public System.Data.SqlClient.SqlParameter[] GetParameter() + { + List list = new List(); + if (this.Count == 0) return list.ToArray(); + int i = 0; + foreach (RefParameter pam in this) + { + int index = this.IndexOf(pam); + if (pam.Direction == ParameterDirection.Input) + { + if (pam.IsDeclare == true) + { + if (pam.Condition == "in" || pam.Condition == "not in") + { + string[] chars = pam.Value.ToString().Split(new char[] { ',' }); + i = 0; + foreach (string s in chars) + { + list.Add(new System.Data.SqlClient.SqlParameter() { ParameterName = pam.Caption + i.ToString(), DbType = pam.Type, Value = s }); + i++; + } + } + else + { + if (pam.Value != null) + { + list.Add(new System.Data.SqlClient.SqlParameter() { ParameterName = pam.Caption, DbType = pam.Type, Value = pam.Value }); + } + } + } + else + { + list.Add(new System.Data.SqlClient.SqlParameter() { ParameterName = pam.Name, DbType = pam.Type, Value = pam.Value }); + } + } + else + { + list.Add(new System.Data.SqlClient.SqlParameter() { ParameterName = pam.Name, DbType = pam.Type, Direction = ParameterDirection.Output }); + } + } + return list.ToArray(); + } + #endregion + + #region ز + public System.Data.OleDb.OleDbParameter[] GetOledbParameter() + { + List list = new List(); + if (this.Count == 0) return list.ToArray(); + int i = 0; + foreach (RefParameter pam in this) + { + int index = this.IndexOf(pam); + if (pam.Direction == ParameterDirection.Input) + { + if (pam.IsDeclare == true) + { + if (pam.Condition == "in" || pam.Condition == "not in") + { + string[] chars = pam.Value.ToString().Split(new char[] { ',' }); + i = 0; + foreach (string s in chars) + { + list.Add(new System.Data.OleDb.OleDbParameter() { ParameterName = pam.Caption + i.ToString(), DbType = pam.Type, Value = s }); + i++; + } + } + else + { + if (pam.Value != null) + { + list.Add(new System.Data.OleDb.OleDbParameter() { ParameterName = pam.Caption, DbType = pam.Type, Value = pam.Value }); + } + } + } + else + { + list.Add(new System.Data.OleDb.OleDbParameter() { ParameterName = pam.Name, DbType = pam.Type, Value = pam.Value }); + } + } + else + { + list.Add(new System.Data.OleDb.OleDbParameter() { ParameterName = pam.Name, DbType = pam.Type, Direction = ParameterDirection.Output }); + } + } + return list.ToArray(); + } + #endregion + } + + public enum ConditionType + { + /// + /// = + /// + Equals = 0, + /// + /// > + /// + Ceiling = 1, + /// + /// ڵ(>=) + /// + CeilingEqual = 2, + /// + /// С(<) + /// + Floor = 3, + /// + /// Сڵ(<=) + /// + FloorEqual = 4, + /// + /// (<>) + /// + NotEquals = 5, + /// + /// in + /// + In = 6, + /// + /// not in + /// + NotIn = 7, + /// + /// like left + /// + LikeLeft = 8, + /// + /// like right + /// + LikeRight = 9, + /// + /// like + /// + Like = 10 + } + + public enum ConditionTypeNull + { + /// + /// is + /// + Is = 0, + /// + /// is not + /// + IsNot = 1 + } + + public enum EditDataType + { + /// + /// ǰʹDataSetDataTableԴ + /// + DataSetIndex, + /// + /// ǰʹDataViewԴ + /// + DataViewIndex + } +} diff --git a/基础类库/HuizhongLibrary/SqlSelectService/SelectParameter.cs b/基础类库/HuizhongLibrary/SqlSelectService/SelectParameter.cs new file mode 100644 index 0000000..ad5efb8 --- /dev/null +++ b/基础类库/HuizhongLibrary/SqlSelectService/SelectParameter.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace HuizhongLibrary.Data +{ + public class SelectParameter + { + public string Name { get; set; } + public string Condition { get; set; } + public string Value { get; set; } + public string RelateTo { get; set; } + public string EndString { get; set; } + } +} diff --git a/基础类库/HuizhongLibrary/SystemInfo.cs b/基础类库/HuizhongLibrary/SystemInfo.cs new file mode 100644 index 0000000..1cfd769 --- /dev/null +++ b/基础类库/HuizhongLibrary/SystemInfo.cs @@ -0,0 +1,1024 @@ +using System; +using System.Collections.Generic; +using System.Text; +using HuizhongLibrary.Safety; +using HuizhongLibrary.Common.Configuration; +using System.Management; +using System.Runtime.InteropServices; +using System.Drawing; +using System.Diagnostics; +using HuizhongLibrary.Log; +using System.Net; +using System.IO; + +namespace HuizhongLibrary +{ + public static class SystemInfo + { + private const Int32 WM_SYSCOMMAND = 274; + private const UInt32 SC_CLOSE = 61536; + [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] + private static extern bool PostMessage(IntPtr hWnd, int Msg, int wParam, int lParam); + [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] + private static extern bool PostMessage(IntPtr hWnd, int Msg, uint wParam, uint lParam); + [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] + private static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam); + [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] + private static extern IntPtr FindWindow(string lpClassName, string lpWindowName); + [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] + private static extern int RegisterWindowMessage(string lpString); + + [DllImport("winmm.dll", EntryPoint = "PlaySound", SetLastError = true)] + public static extern bool W32_PlaySound(string szSound, IntPtr hmod, UInt32 fdwSound); + + [DllImport("winmm.dll", EntryPoint = "PlaySound", SetLastError = true)] + public static extern bool W32_PlaySound(byte[] szSound, IntPtr hmod, UInt32 fdwSound); + + [DllImport("user32")] + public static extern long ExitWindowsEx(long uFlags, long dwReserved); //定义API变量 + + [DllImport("kernel32.dll")] + public static extern int SetProcessWorkingSetSize(IntPtr process, int minSize, int maxSize); + + [DllImport("gdi32.dll")] + public static extern bool BitBlt(IntPtr hObject, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hObjectSource, int nXSrc, int nYSrc, int dwRop); + + [DllImport("Kernel32.dll", SetLastError = true)] + public static extern int SetLocalTime(ref SystemTime lpSystemTime); + public struct SystemTime + { + public short wYear; + public short wMonth; + public short wDayOfWeek; + public short wDay; + public short wHour; + public short wMinute; + public short wSecond; + public short wMilliseconds; + } + + public class SoundFlag + { + public const UInt32 SND_SYNC = 0x0000; // 同步 + public const UInt32 SND_ASYNC = 0x0001; // 用异步方式播放声音,PlaySound函数在开始播放后立即返回。 + public const UInt32 SND_NODEFAULT = 0x0002; // 静音 + public const UInt32 SND_MEMORY = 0x0004; // 流文件 + public const UInt32 SND_LOOP = 0x0008; // 循环 + public const UInt32 SND_NOSTOP = 0x0010; // 不打断原来的声音播出并立即返回FALSE。 + public const UInt32 SND_NOWAIT = 0x00002000; // 如果驱动程序正忙则函数就不播放声音并立即返回。 + public const UInt32 SND_ALIAS = 0x00010000; // name is a registry alias + public const UInt32 SND_ALIAS_ID = 0x00110000; // alias is a predefined ID + public const UInt32 SND_FILENAME = 0x00020000; // name is file name + public const UInt32 SND_RESOURCE = 0x00040004; // name is resource name or atom + } + + public enum ShowCommands : int + + { + + SW_HIDE = 0, + + SW_SHOWNORMAL = 1, + + SW_NORMAL = 1, + + SW_SHOWMINIMIZED = 2, + + SW_SHOWMAXIMIZED = 3, + + SW_MAXIMIZE = 3, + + SW_SHOWNOACTIVATE = 4, + + SW_SHOW = 5, + + SW_MINIMIZE = 6, + + SW_SHOWMINNOACTIVE = 7, + + SW_SHOWNA = 8, + + SW_RESTORE = 9, + + SW_SHOWDEFAULT = 10, + + SW_FORCEMINIMIZE = 11, + + SW_MAX = 11 + + } + + [DllImport("shell32.dll")] + static extern IntPtr ShellExecute(IntPtr hwnd, string lpOperation, string lpFile, string lpParameters, string lpDirectory, ShowCommands nShowCmd); + + #region 获取CPU序列号 + /// + /// 获取CPU序列号 + /// + public static string GetProcessorID() + { + try + { + string cpuInfo = "";//cpu序列号 + ManagementClass cimobject = new ManagementClass("Win32_Processor"); + ManagementObjectCollection moc = cimobject.GetInstances(); + foreach (ManagementObject mo in moc) + { + cpuInfo = mo.Properties["ProcessorId"].Value.ToString(); + if (cpuInfo != "") { return cpuInfo; } + } + } + catch { return ""; } + return ""; + } + #endregion + #region 获取网卡硬件地址 + /// + /// 获取网卡硬件地址 + /// + public static string GetNetworkCardID() + { + try + { + ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); + ManagementObjectCollection moc = mc.GetInstances(); + foreach (ManagementObject mo in moc) + { + if ((bool)mo["IPEnabled"] == true) + return mo["MacAddress"].ToString(); + mo.Dispose(); + } + } + catch { return ""; } + return ""; + } + #endregion + #region 获取硬盘ID + /// + /// 获取硬盘ID + /// + public static string GetDiskDriveID() + { + try + { + String HDid; + ManagementClass cimobject = new ManagementClass("Win32_DiskDrive"); + ManagementObjectCollection moc = cimobject.GetInstances(); + foreach (ManagementObject mo in moc) + { + HDid = (string)mo.Properties["Model"].Value; + return HDid; + } + } + catch { return ""; } + return ""; + } + #endregion + #region 获取硬件唯一序列号 + public static string GetHardwareID() + { + string code = SystemInfo.GetProcessorID(); + if (string.IsNullOrEmpty(code) == true) code = SystemInfo.GetNetworkCardID(); + if (string.IsNullOrEmpty(code) == true) code = SystemInfo.GetDiskDriveID(); + if (string.IsNullOrEmpty(code) == true) code = "BFEBFBFF000306C3"; + return code; + } + #endregion + #region 判断注册码是否正确 + /// + /// 判断注册码是否正确 + /// + public static bool IsRegisterCode(string filePath, string pubkey, string keyName) + { + CryptoPublic cp = new CryptoPublic(); + //string pubkey = "0zzXz1C4sKN0bWqWhMs8fp8EG+xI1o5f2xe/HztS65PPp2DGMpOfY9hyOuFW9Rkfm/aBeenzmBaqRhG0h5spc/0SRSbEWR76oP/3z/mDmWBBqsbz7iKDuEs08Zi34UogmRX2t5FpQmcVfjBNvWhYhEoDUDxutRvmNHB4P0/nluE=AQAB"; + string jqm = ""; //返回CPU序列号 + jqm = SystemInfo.GetProcessorID(); + if (jqm == "") { jqm = SystemInfo.GetNetworkCardID(); } + if (jqm == "") { jqm = SystemInfo.GetDiskDriveID(); } + string zcm = ConfigurationSourceSection.LoadXml_Attribute(filePath, keyName); //返回注册码 + if (cp.RsaVerifySignature(jqm, zcm, pubkey) == false) { return false; } + return true; + } + #endregion + #region 设置系统时间 + public static void SetDateTime(DateTime dt) + { + SystemTime st = new SystemTime(); + st.wYear = Convert.ToInt16(dt.Year); + st.wMonth = Convert.ToInt16(dt.Month); + st.wDay = Convert.ToInt16(dt.Day); + st.wHour = Convert.ToInt16(dt.Hour); + st.wMinute = Convert.ToInt16(dt.Minute); + st.wSecond = Convert.ToInt16(dt.Second); + st.wMilliseconds = Convert.ToInt16(dt.Millisecond); + st.wDayOfWeek = Convert.ToInt16(dt.DayOfWeek); + SetLocalTime(ref st); + } + #endregion + #region 根据颜色名称创建颜色 + public static Color CreateColor(string ColorName) + { + switch (ColorName) + { + case "AliceBlue": + return Color.AliceBlue; + case "AntiqueWhite": + return Color.AntiqueWhite; + case "Aqua": + return Color.Aqua; + case "Aquamarine": + return Color.Aquamarine; + case "Azure": + return Color.Azure; + case "Beige": + return Color.Beige; + case "Bisque": + return Color.Bisque; + case "Black": + return Color.Black; + case "BlanchedAlmond": + return Color.BlanchedAlmond; + case "Blue": + return Color.Blue; + case "BlueViolet": + return Color.BlueViolet; + case "Brown": + return Color.Brown; + case "BurlyWood": + return Color.BurlyWood; + case "CadetBlue": + return Color.CadetBlue; + case "Chartreuse": + return Color.Chartreuse; + case "Chocolate": + return Color.Chocolate; + case "Coral": + return Color.Coral; + case "CornflowerBlue": + return Color.CornflowerBlue; + case "Cornsilk": + return Color.Cornsilk; + case "Crimson": + return Color.Crimson; + case "Cyan": + return Color.Cyan; + case "DarkBlue": + return Color.DarkBlue; + case "DarkCyan": + return Color.DarkCyan; + case "DarkGoldenrod": + return Color.DarkGoldenrod; + case "DarkGray": + return Color.DarkGray; + case "DarkGreen": + return Color.DarkGreen; + case "DarkKhaki": + return Color.DarkKhaki; + case "DarkMagenta": + return Color.DarkMagenta; + case "DarkOliveGreen": + return Color.DarkOliveGreen; + case "DarkOrange": + return Color.DarkOrange; + case "DarkOrchid": + return Color.DarkOrchid; + case "DarkRed": + return Color.DarkRed; + case "DarkSalmon": + return Color.DarkSalmon; + case "DarkSeaGreen": + return Color.DarkSeaGreen; + case "DarkSlateBlue": + return Color.DarkSlateBlue; + case "DarkSlateGray": + return Color.DarkSlateGray; + case "DarkTurquoise": + return Color.DarkTurquoise; + case "DarkViolet": + return Color.DarkViolet; + case "DeepPink": + return Color.DeepPink; + case "DeepSkyBlue": + return Color.DeepSkyBlue; + case "DimGray": + return Color.DimGray; + case "DodgerBlue": + return Color.DodgerBlue; + case "Firebrick": + return Color.Firebrick; + case "FloralWhite": + return Color.FloralWhite; + case "ForestGreen": + return Color.ForestGreen; + case "Fuchsia": + return Color.Fuchsia; + case "Gainsboro": + return Color.Gainsboro; + case "GhostWhite": + return Color.GhostWhite; + case "Gold": + return Color.Gold; + case "Goldenrod": + return Color.Goldenrod; + case "Gray": + return Color.Gray; + case "Green": + return Color.Green; + case "GreenYellow": + return Color.GreenYellow; + case "Honeydew": + return Color.Honeydew; + case "HotPink": + return Color.HotPink; + case "IndianRed": + return Color.IndianRed; + case "Indigo": + return Color.Indigo; + case "Ivory": + return Color.Ivory; + case "Khaki": + return Color.Khaki; + case "Lavender": + return Color.Lavender; + case "LavenderBlush": + return Color.LavenderBlush; + case "LawnGreen": + return Color.LawnGreen; + case "LemonChiffon": + return Color.LemonChiffon; + case "LightBlue": + return Color.LightBlue; + case "LightCoral": + return Color.LightCoral; + case "LightCyan": + return Color.LightCyan; + case "LightGoldenrodYellow": + return Color.LightGoldenrodYellow; + case "LightGray": + return Color.LightGray; + case "LightGreen": + return Color.LightGreen; + case "LightPink": + return Color.LightPink; + case "LightSalmon": + return Color.LightSalmon; + case "LightSeaGreen": + return Color.LightSeaGreen; + case "LightSkyBlue": + return Color.LightSkyBlue; + case "LightSlateGray": + return Color.LightSlateGray; + case "LightSteelBlue": + return Color.LightSteelBlue; + case "LightYellow": + return Color.LightYellow; + case "Lime": + return Color.Lime; + case "LimeGreen": + return Color.LimeGreen; + case "Linen": + return Color.Linen; + case "Magenta": + return Color.Magenta; + case "Maroon": + return Color.Maroon; + case "MediumAquamarine": + return Color.MediumAquamarine; + case "MediumBlue": + return Color.MediumBlue; + case "MediumOrchid": + return Color.MediumOrchid; + case "MediumPurple": + return Color.MediumPurple; + case "MediumSeaGreen": + return Color.MediumSeaGreen; + case "MediumSlateBlue": + return Color.MediumSlateBlue; + case "MediumSpringGreen": + return Color.MediumSpringGreen; + case "MediumTurquoise": + return Color.MediumTurquoise; + case "MediumVioletRed": + return Color.MediumVioletRed; + case "MidnightBlue": + return Color.MidnightBlue; + case "MintCream": + return Color.MintCream; + case "MistyRose": + return Color.MistyRose; + case "Moccasin": + return Color.Moccasin; + case "NavajoWhite": + return Color.NavajoWhite; + case "Navy": + return Color.Navy; + case "OldLace": + return Color.OldLace; + case "Olive": + return Color.Olive; + case "OliveDrab": + return Color.OliveDrab; + case "Orange": + return Color.Orange; + case "OrangeRed": + return Color.OrangeRed; + case "Orchid": + return Color.Orchid; + case "PaleGoldenrod": + return Color.PaleGoldenrod; + case "PaleGreen": + return Color.PaleGreen; + case "PaleTurquoise": + return Color.PaleTurquoise; + case "PaleVioletRed": + return Color.PaleVioletRed; + case "PapayaWhip": + return Color.PapayaWhip; + case "PeachPuff": + return Color.PeachPuff; + case "Peru": + return Color.Peru; + case "Pink": + return Color.Pink; + case "Plum": + return Color.Plum; + case "PowderBlue": + return Color.PowderBlue; + case "Purple": + return Color.Purple; + case "Red": + return Color.Red; + case "RosyBrown": + return Color.RosyBrown; + case "SaddleBrown": + return Color.SaddleBrown; + case "Salmon": + return Color.Salmon; + case "SandyBrown": + return Color.SandyBrown; + case "SeaGreen": + return Color.SeaGreen; + case "SeaShell": + return Color.SeaShell; + case "Sienna": + return Color.Sienna; + case "Silver": + return Color.Silver; + case "SkyBlue": + return Color.SkyBlue; + case "SlateBlue": + return Color.SlateBlue; + case "SlateGray": + return Color.SlateGray; + case "Snow": + return Color.Snow; + case "SpringGreen": + return Color.SpringGreen; + case "SteelBlue": + return Color.SteelBlue; + case "Tan": + return Color.Tan; + case "Teal": + return Color.Teal; + case "Thistle": + return Color.Thistle; + case "Tomato": + return Color.Tomato; + case "Transparent": + return Color.Transparent; + case "Turquoise": + return Color.Turquoise; + case "Violet": + return Color.Violet; + case "Wheat": + return Color.Wheat; + case "White": + return Color.White; + case "WhiteSmoke": + return Color.WhiteSmoke; + case "Yellow": + return Color.Yellow; + case "YellowGreen": + return Color.YellowGreen; + default: + return Color.Black; + } + } + #endregion + #region 像素转毫米 + public static int PxConvertMm(int Pixel) + { + ManagementClass mc = new ManagementClass("Win32_DesktopMonitor"); + ManagementObjectCollection moc = mc.GetInstances(); + int PixelsPerXLogicalInch = 0; // dpi for x + //int PixelsPerYLogicalInch = 0; // dpi for y + foreach (ManagementObject each in moc) + { + PixelsPerXLogicalInch = int.Parse((each.Properties["PixelsPerXLogicalInch"].Value.ToString())); + //PixelsPerYLogicalInch = int.Parse((each.Properties["PixelsPerYLogicalInch"].Value.ToString())); + } + int a =Convert.ToInt32(Pixel / PixelsPerXLogicalInch * 25.4); + return a; + } + #endregion + #region 读取当前文件夹路径 + public static string AppPath() + { + string path = AppDomain.CurrentDomain.BaseDirectory; + path = path.Replace("\\", "/"); + return path; + } + #endregion + #region 播放声音文件 + public static void PlayWav(string FileName) + { + try + { + W32_PlaySound(FileName, IntPtr.Zero, SoundFlag.SND_ASYNC + SoundFlag.SND_FILENAME); + } + catch { } + } + #endregion + #region 关机 + public static void CloseWindows() + { + Process MyProcess = new Process(); + //设定程序名 + MyProcess.StartInfo.FileName = "cmd.exe"; + //关闭Shell的使用 + MyProcess.StartInfo.UseShellExecute = false; + //重定向标准输入 + MyProcess.StartInfo.RedirectStandardInput = true; + //重定向标准输出 + MyProcess.StartInfo.RedirectStandardOutput = true; + //重定向错误输出 + MyProcess.StartInfo.RedirectStandardError = true; + //设置不显示窗口 + MyProcess.StartInfo.CreateNoWindow = true; + //执行VER命令 + MyProcess.Start(); + MyProcess.StandardInput.WriteLine("shutdown -f -s -t 1"); + MyProcess.StandardInput.WriteLine("exit"); + + } + #endregion + #region 重启 + public static void WindowReStart() + { + try + { + System.Diagnostics.ProcessStartInfo startinfo = new System.Diagnostics.ProcessStartInfo("shutdown.exe", "-r -t 00"); + System.Diagnostics.Process.Start(startinfo); + } + catch { } + } + #endregion + #region 判断进程是否已经进行 + public static bool IsProcessRunning(string applicationName) + { + try + { + Process[] list=Process.GetProcessesByName(applicationName); + if (list.Length > 1) return true; + //int count = 0; + //foreach (Process item in list) + //{ + // //ErrorFollow.TraceWrite("进程名称", "", item.ProcessName); + // if (item.ProcessName.ToLower() == applicationName.ToLower()) + // { + // count++; + // if (count > 1) return true; + // } + //} + return false; + } + catch (Exception ex) + { + ErrorFollow.TraceWrite("判断进程是否已经进行", "", ex.Message); + } + return false; + } + #endregion + #region 判断进程是否已经进行 + public static bool IsProcessRunning2(string applicationName) + { + try + { + Process[] list = Process.GetProcessesByName(applicationName); + if (list.Length > 0) return true; + return false; + } + catch (Exception ex) + { + ErrorFollow.TraceWrite("判断进程是否已经进行", "", ex.Message); + } + return false; + } + #endregion + #region 读取IP地址 + public static List GetLocalIPv4() + { + string hostName = Dns.GetHostName(); + IPAddress[] list=Dns.GetHostAddresses(hostName); + List list2 = new List(); + for (int i = list.Length - 1; i >= 0; i--) + { + var item = list[i]; + string FamilyName = item.AddressFamily.ToString(); + if (FamilyName == "InterNetwork") list2.Add(item.ToString()); + } + return list2; + } + #endregion + #region 读取IP地址 + public static bool IsLocalIPv4(string ip) + { + string hostName = Dns.GetHostName(); + IPAddress[] list = Dns.GetHostAddresses(hostName); + if (list.Length == 0) return true; + bool bk = false; + for (int i = list.Length - 1; i >= 0; i--) + { + var item = list[i]; + string FamilyName = item.AddressFamily.ToString(); + if (FamilyName == "InterNetwork") + { + string ip2 = item.ToString(); + ErrorFollow.TraceWrite("本地IP", "", ip2); + if (ip == ip2) + { + bk = true; + break; + } + } + } + return bk; + } + #endregion + #region 清除IE缓存 + public static void ClearCache_IE() + { + //清除IE临时文件 + ShellExecute(IntPtr.Zero, "open", "rundll32.exe", " InetCpl.cpl,ClearMyTracksByProcess 8", "", ShowCommands.SW_HIDE); + } + #endregion + #region Winform按键码转换字符串 + public static string FormKeyCode(System.Windows.Forms.KeyEventArgs e) + { + switch (e.KeyCode) + { + case System.Windows.Forms.Keys.D0: + return "0"; + case System.Windows.Forms.Keys.D1: + return "1"; + case System.Windows.Forms.Keys.D2: + return "2"; + case System.Windows.Forms.Keys.D3: + return "3"; + case System.Windows.Forms.Keys.D4: + return "4"; + case System.Windows.Forms.Keys.D5: + return "5"; + case System.Windows.Forms.Keys.D6: + return "6"; + case System.Windows.Forms.Keys.D7: + return "7"; + case System.Windows.Forms.Keys.D8: + return "8"; + case System.Windows.Forms.Keys.D9: + return "9"; + case System.Windows.Forms.Keys.NumPad0: + return "0"; + case System.Windows.Forms.Keys.NumPad1: + return "1"; + case System.Windows.Forms.Keys.NumPad2: + return "2"; + case System.Windows.Forms.Keys.NumPad3: + return "3"; + case System.Windows.Forms.Keys.NumPad4: + return "4"; + case System.Windows.Forms.Keys.NumPad5: + return "5"; + case System.Windows.Forms.Keys.NumPad6: + return "6"; + case System.Windows.Forms.Keys.NumPad7: + return "7"; + case System.Windows.Forms.Keys.NumPad8: + return "8"; + case System.Windows.Forms.Keys.NumPad9: + return "9"; + case System.Windows.Forms.Keys.A: + return "A"; + case System.Windows.Forms.Keys.B: + return "B"; + case System.Windows.Forms.Keys.C: + return "C"; + case System.Windows.Forms.Keys.D: + return "D"; + case System.Windows.Forms.Keys.E: + return "E"; + case System.Windows.Forms.Keys.F: + return "F"; + case System.Windows.Forms.Keys.G: + return "G"; + case System.Windows.Forms.Keys.H: + return "H"; + case System.Windows.Forms.Keys.I: + return "I"; + case System.Windows.Forms.Keys.J: + return "J"; + case System.Windows.Forms.Keys.K: + return "K"; + case System.Windows.Forms.Keys.L: + return "L"; + case System.Windows.Forms.Keys.M: + return "M"; + case System.Windows.Forms.Keys.N: + return "N"; + case System.Windows.Forms.Keys.O: + return "O"; + case System.Windows.Forms.Keys.P: + return "P"; + case System.Windows.Forms.Keys.Q: + return "Q"; + case System.Windows.Forms.Keys.R: + return "R"; + case System.Windows.Forms.Keys.S: + return "S"; + case System.Windows.Forms.Keys.T: + return "T"; + case System.Windows.Forms.Keys.U: + return "U"; + case System.Windows.Forms.Keys.V: + return "V"; + case System.Windows.Forms.Keys.W: + return "W"; + case System.Windows.Forms.Keys.X: + return "X"; + case System.Windows.Forms.Keys.Y: + return "Y"; + case System.Windows.Forms.Keys.Z: + return "Z"; + case System.Windows.Forms.Keys.F1: + return "F1"; + case System.Windows.Forms.Keys.F2: + return "F2"; + case System.Windows.Forms.Keys.F3: + return "F3"; + case System.Windows.Forms.Keys.F4: + return "F4"; + case System.Windows.Forms.Keys.F5: + return "F5"; + case System.Windows.Forms.Keys.F6: + return "F6"; + case System.Windows.Forms.Keys.F7: + return "F7"; + case System.Windows.Forms.Keys.F8: + return "F8"; + case System.Windows.Forms.Keys.F9: + return "F9"; + case System.Windows.Forms.Keys.F10: + return "F10"; + case System.Windows.Forms.Keys.F11: + return "F11"; + case System.Windows.Forms.Keys.F12: + return "F12"; + case System.Windows.Forms.Keys.Oemcomma: + if (e.Shift == true) + { + return "<"; + } + else + { + return ","; + } + case System.Windows.Forms.Keys.Separator: + return ";"; + case System.Windows.Forms.Keys.Oem1: + return ":"; + case System.Windows.Forms.Keys.Divide: + return "/"; + case System.Windows.Forms.Keys.Multiply: + return "*"; + default: + return ""; + } + } + #endregion + #region wpf按键码转换字符串 + public static string WindowKeyCode(System.Windows.Input.ModifierKeys Modifiers, System.Windows.Input.Key Key) + { + + switch (Key) + { + case System.Windows.Input.Key.D0: + return "0"; + case System.Windows.Input.Key.D1: + return "1"; + case System.Windows.Input.Key.D2: + return "2"; + case System.Windows.Input.Key.D3: + return "3"; + case System.Windows.Input.Key.D4: + return "4"; + case System.Windows.Input.Key.D5: + return "5"; + case System.Windows.Input.Key.D6: + return "6"; + case System.Windows.Input.Key.D7: + return "7"; + case System.Windows.Input.Key.D8: + return "8"; + case System.Windows.Input.Key.D9: + return "9"; + case System.Windows.Input.Key.NumPad0: + return "0"; + case System.Windows.Input.Key.NumPad1: + return "1"; + case System.Windows.Input.Key.NumPad2: + return "2"; + case System.Windows.Input.Key.NumPad3: + return "3"; + case System.Windows.Input.Key.NumPad4: + return "4"; + case System.Windows.Input.Key.NumPad5: + return "5"; + case System.Windows.Input.Key.NumPad6: + return "6"; + case System.Windows.Input.Key.NumPad7: + return "7"; + case System.Windows.Input.Key.NumPad8: + return "8"; + case System.Windows.Input.Key.NumPad9: + return "9"; + case System.Windows.Input.Key.A: + return "A"; + case System.Windows.Input.Key.B: + return "B"; + case System.Windows.Input.Key.C: + return "C"; + case System.Windows.Input.Key.D: + return "D"; + case System.Windows.Input.Key.E: + return "E"; + case System.Windows.Input.Key.F: + return "F"; + case System.Windows.Input.Key.G: + return "G"; + case System.Windows.Input.Key.H: + return "H"; + case System.Windows.Input.Key.I: + return "I"; + case System.Windows.Input.Key.J: + return "J"; + case System.Windows.Input.Key.K: + return "K"; + case System.Windows.Input.Key.L: + return "L"; + case System.Windows.Input.Key.M: + return "M"; + case System.Windows.Input.Key.N: + return "N"; + case System.Windows.Input.Key.O: + return "O"; + case System.Windows.Input.Key.P: + return "P"; + case System.Windows.Input.Key.Q: + return "Q"; + case System.Windows.Input.Key.R: + return "R"; + case System.Windows.Input.Key.S: + return "S"; + case System.Windows.Input.Key.T: + return "T"; + case System.Windows.Input.Key.U: + return "U"; + case System.Windows.Input.Key.V: + return "V"; + case System.Windows.Input.Key.W: + return "W"; + case System.Windows.Input.Key.X: + return "X"; + case System.Windows.Input.Key.Y: + return "Y"; + case System.Windows.Input.Key.Z: + return "Z"; + case System.Windows.Input.Key.OemComma: + if (Modifiers == System.Windows.Input.ModifierKeys.Shift) + { + return "<"; + } + else + { + return ","; + } + case System.Windows.Input.Key.Separator: + if (Modifiers == System.Windows.Input.ModifierKeys.Shift) + { + return ":"; + } + else + { + return ";"; + } + case System.Windows.Input.Key.Oem1: + return ":"; + default: + return ""; + } + } + #endregion + + #region 显示屏幕键盘 + public static void ShowInputPanel() + { + try + { + string filepath = "C:\\Program Files\\Common Files\\microsoft shared\\ink\\TabTip.exe"; + if (File.Exists(filepath) == false) + { + ShowScreenOsk(); + return; + } + HideInputPanel(); + Process.Start(filepath); + } + catch (Exception) + { + + } + } + #endregion + #region 隐藏屏幕键盘 + public static void HideInputPanel() + { + IntPtr TouchhWnd = new IntPtr(0); + TouchhWnd = FindWindow("IPTip_Main_Window", null); + if (TouchhWnd == IntPtr.Zero) + return; + PostMessage(TouchhWnd, WM_SYSCOMMAND, SC_CLOSE, 0); + } + #endregion + #region 显示虚拟键盘 + public static void ShowScreenOsk() + { + string filepath = @"C:\Windows\System32\osk.exe"; + if (File.Exists(filepath) == false) return; + Process[] pp=Process.GetProcessesByName("osk"); + if (pp.Length > 0) + { + foreach (var item in pp) + { + item.Kill(); + } + } + Process.Start(filepath); + } + #endregion + #region 显示第三方键盘 + public static void ShowOtherKeyboard() + { + string filepath = AppDomain.CurrentDomain.BaseDirectory + @"ScreenKey/ScreenKey.exe"; + if (File.Exists(filepath) == false) return; + Process[] pp = Process.GetProcessesByName("ScreenKey"); + if (pp.Length > 0) return; + Process.Start(filepath); + } + #endregion + #region 强制回收内存 + public static void ClearMemory() + { + GC.Collect(); + //GC.WaitForPendingFinalizers(); + //if (Environment.OSVersion.Platform == PlatformID.Win32NT) + //{ + // SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle, -1, -1); + //} + } + #endregion + #region 取得当前内存占用 + public static string GetMemory() + { + //throw new Exception("OutOfMemoryException"); + //string SetupPath = AppDomain.CurrentDomain.BaseDirectory + "Setup.ini"; + //string IsReStartServer = ConfigurationSourceSection.LoadXml_Attribute(SetupPath, "IsReStartServer"); + //if (IsReStartServer == "1") return ""; + //ConfigurationSourceSection.SaveXml_Attribute(SetupPath, "IsReStartServer", "1", false); + //string file2 = AppDomain.CurrentDomain.BaseDirectory + "自动启动服务脚本/hz.bat"; + //CustomIO.ReStartService(file2); + //return ""; + Process proc = Process.GetCurrentProcess(); + long b = proc.PrivateMemorySize64; + for (int i = 0; i < 2; i++) + { + b /= 1024; + } + return b + "MB"; + } + #endregion + + + + } +} diff --git a/基础类库/HuizhongLibrary/TimeTask.cs b/基础类库/HuizhongLibrary/TimeTask.cs new file mode 100644 index 0000000..161859e --- /dev/null +++ b/基础类库/HuizhongLibrary/TimeTask.cs @@ -0,0 +1,155 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading; +using System.Linq; +using HuizhongLibrary.Log; + +namespace HuizhongLibrary +{ + public class TimeTask + { + public List ListModel = new List(); + private AutoResetEvent AutoReset = new AutoResetEvent(false); + public int TimeType = 1; //0秒1分钟 + bool IsRun = false; + + TaskModel cTask = null; //当前任务 + + #region 启动任务 + public void Start() + { + cTask = null; + if (ListModel.Count == 0) return; + DateTime dt=DateTime.Now; + foreach (var item in ListModel) + { + if (item.NextTime < dt) + { + if (TimeType == 0) item.NextTime = item.NextTime.AddSeconds(item.Interval); + if (TimeType == 1) item.NextTime = item.NextTime.AddMinutes(item.Interval); + } + } + Thread t1 = new Thread(new ThreadStart(this.OnStart)); + t1.Name = "定时任务"; + t1.Start(); + + } + #endregion + #region 停止任务 + public void Stop() + { + IsRun = false; + AutoReset.Set(); + } + #endregion + #region 计算下一个任务 + public void MathNextTask() + { + if (cTask != null) + { + if (cTask.Interval == 0) + { + ListModel.Remove(cTask); + if (ListModel.Count == 0) + { + cTask = null; + Stop(); + return; + } + if (ListModel.Count == 1) cTask = ListModel[0]; + return; + } + else + { + if (TimeType==0) cTask.NextTime = cTask.NextTime.AddSeconds(cTask.Interval); + if (TimeType == 1) cTask.NextTime = cTask.NextTime.AddMinutes(cTask.Interval); + } + //ErrorFollow.TraceWrite("下次执行任务时间", "", cTask.NextTime.ToString("yyyy-MM-dd HH:mm:00")); + } + if (ListModel.Count == 1) + { + if (cTask==null) cTask = ListModel[0]; + return; + } + var query = from item in ListModel + orderby item.NextTime ascending + select item; + cTask = query.First(); + //foreach (TaskModel item in ListModel) + //{ + // if (cTask == null) { cTask = item; } + // else + // { + // if (item.NextTime < cTask.NextTime) cTask = item; + // } + //} + } + #endregion + #region 睡眠 + public void WaitOne() + { + if (cTask == null) return; + if (cTask.NextTime < DateTime.Now) + { + if (TimeType == 0) cTask.NextTime = cTask.NextTime.AddSeconds(cTask.Interval); + if (TimeType == 1) cTask.NextTime = cTask.NextTime.AddMinutes(cTask.Interval); + } + + TimeSpan ts =cTask.NextTime - DateTime.Now; + ErrorFollow.TraceWrite("定时", "", "下次运行时间:" + cTask.NextTime.ToString("MM-dd HH:mm:ss")); + if (IsRun == true && ts.TotalSeconds>0) AutoReset.WaitOne(ts, false); + } + #endregion + #region 执行任务 + void OnStart() + { + IsRun = true; + ErrorFollow.TraceWrite("启动定时", "", "计算时间"); + MathNextTask(); + ErrorFollow.TraceWrite("启动定时", "", "下次运行时间:"+cTask.NextTime.ToString("MM-dd HH:mm:ss")); + WaitOne(); + if (ListModel.Count == 0) { ErrorFollow.TraceWrite("停止定时", "", cTask.NextTime.ToString("MM-dd HH:mm:ss")); return; } + if (IsRun == false) { ErrorFollow.TraceWrite("停止定时", "", cTask.NextTime.ToString("MM-dd HH:mm:ss")); return; } + while (IsRun) + { + cTask.RunTask.Invoke(cTask); + MathNextTask(); + WaitOne(); + if (ListModel.Count == 0) { ErrorFollow.TraceWrite("停止定时", "", cTask.NextTime.ToString("MM-dd HH:mm:ss")); return; } + if (IsRun == false) { ErrorFollow.TraceWrite("停止定时", "", cTask.NextTime.ToString("MM-dd HH:mm:ss")); return; } + } + } + #endregion + #region 关机 + public void CloseWindows(DateTime dt) + { + IsRun = true; + Action hand = new Action(this.CloseWindows_Action); + hand.BeginInvoke(dt, null, null); + } + void CloseWindows_Action(DateTime dt) + { + TimeSpan ts = dt - DateTime.Now; + if (ts.TotalSeconds < 1) return; + AutoReset.WaitOne(ts, true); + if (IsRun == false) return; + SystemInfo.CloseWindows(); + } + #endregion + + + + } + + public class TaskModel + { + public Action RunTask = null; + public DateTime NextTime = DateTime.Today; + /// + /// 间隔时间(分钟) + /// + public int Interval = 0; + public object CustomModel = null; + } +} diff --git a/基础类库/HuizhongLibrary/UFace/UfaceModel.cs b/基础类库/HuizhongLibrary/UFace/UfaceModel.cs new file mode 100644 index 0000000..3a821a9 --- /dev/null +++ b/基础类库/HuizhongLibrary/UFace/UfaceModel.cs @@ -0,0 +1,264 @@ +using HuizhongLibrary.Safety; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace HuizhongLibrary.UFace +{ + #region 鉴权 + public class UFace_Auth + { + public string appId { get; set; } + public string appKey { get; set; } + public string timestamp { get; set; } + public string sign { get; set; } + + #region 创建签名 + public void CreateSign(string appSecret) + { + timestamp =Convert.ToString(CustomIO.GetTimeStamp(DateTime.Now)); + string str = appKey + timestamp + appSecret; + sign=CryptoPublic.Md5For32(str); + } + #endregion + } + #endregion + #region 鉴权结果 + public class UFace_Auth_Result + { + public string code { get; set; } + public string data { get; set; } + public string msg { get; set; } + public int result { get; set; } + } + #endregion + #region 创建设备 + public class UFace_Device + { + public string appId { get; set; } + public string token { get; set; } + public string deviceKey { get; set; } + public string name { get; set; } + public string tag { get; set; } + } + #endregion + #region 创建设备结果 + public class UFace_Device_Result: UFace_Auth_Result + { + public string appId { get; set; } + public string deviceKey { get; set; } + public string name { get; set; } + public string sceneGuid { get; set; } + public string tag { get; set; } + } + #endregion + #region 设备列表查询 + public class UFace_Device_Search + { + public string appId { get; set; } + public string token { get; set; } + public int index { get; set; } + public int length { get; set; } + + public UFace_Device_Search() + { + length = 100; + } + } + #endregion + #region 设备列表查询结果 + public class UFace_Device_Search_Result : UFace_Auth_Result + { + public UFace_Device_Search_Result_data data{get;set;} + } + public class UFace_Device_Search_Result_data + { + public List content { get; set; } + public UFace_Device_Search_Result_Pagination pagination { get; set; } + } + public class UFace_Device_Search_Result_DeviceInfo + { + /// + /// 设备序列号 + /// + public string deviceKey { get; set; } + /// + /// 设备名称 + /// + public string name { get; set; } + /// + /// 设备状态,1:未绑定,2:绑定中,3:解绑中,4:未同步,5:同步中,6:已同步,7:已禁用,8:禁用中,9:启用中 + /// + public int state { get; set; } + /// + /// 设备网络状态,1:在线,2:离线 + /// + public int status { get; set; } + /// + /// 设备应用版本号 + /// + public string versionNo { get; set; } + /// + /// 设备系统版本号 + /// + public string systemVersionNo { get; set; } + /// + /// 是否需要系统升级 + /// + public bool needUpgradeSystem { get; set; } + /// + /// 是否需要APP升级 + /// + public bool needUpgradeApp { get; set; } + /// + /// 是否需要升级(包括系统和APP升级) + /// + public bool needUpgrade { get; set; } + + public UFace_Device_Search_Result_DeviceInfo Copy() + { + var model = new UFace_Device_Search_Result_DeviceInfo(); + model.deviceKey = deviceKey; + model.name = name; + model.state = state; + model.status = status; + model.versionNo = versionNo; + model.systemVersionNo = systemVersionNo; + model.needUpgradeSystem = needUpgradeSystem; + model.needUpgradeApp = needUpgradeApp; + model.needUpgrade = needUpgrade; + return model; + } + } + public class UFace_Device_Search_Result_Pagination + { + /// + /// 总条目数 + /// + public int total { get; set; } + /// + /// 总页数 + /// + public int size { get; set; } + /// + /// 当前页数 + /// + public int index { get; set; } + /// + /// 每页最大显示数量,默认5 + /// + public int length { get; set; } + /// + /// 分页开始条目于总数位置 + /// + public int beginIndex { get; set; } + /// + /// 分页结束条目于总数位置 + /// + public int endIndex { get; set; } + } + #endregion + #region 人员新增 + public class UFace_Person + { + public string appId { get; set; } + public string token { get; set; } + public string name { get; set; } + public string idNo { get; set; } + public string phone { get; set; } + public string tag { get; set; } + public int type { get; set; } + public string idcardNo { get; set; } + } + #endregion + #region 人员新增_结果 + public class UFace_Person_Result : UFace_Auth_Result + { + public UFace_Person_Info data { get; set; } + } + public class UFace_Person_Info + { + public string guid { get; set; } + public string userGuid { get; set; } + public string phone { get; set; } + public string idNo { get; set; } + public string tag { get; set; } + public int type { get; set; } + public string name { get; set; } + } + #endregion + #region 人员新增 + public class UFace_Person_Delete + { + public string appId { get; set; } + public string token { get; set; } + public string guid { get; set; } + } + #endregion + #region 人员更新 + public class UFace_Person_Update + { + public string appId { get; set; } + public string token { get; set; } + public string guid { get; set; } + public string name { get; set; } + public string idNo { get; set; } + public string phone { get; set; } + public string tag { get; set; } + public string type { get; set; } + public string idcardNo { get; set; } + } + #endregion + #region 人员设备授权 + public class UFace_PersonPermission + { + public string appId { get; set; } + public string token { get; set; } + public string guid { get; set; } + public string deviceKeys { get; set; } + public string passTimes { get; set; } + public string effectiveTime { get; set; } + public int facePermission { get; set; } + public int cardPermission { get; set; } + public int cardFacePermission { get; set; } + public int idcardFacePermission { get; set; } + } + #endregion + #region 人员设备消权 + public class UFace_PersonPermission_Delete + { + public string appId { get; set; } + public string token { get; set; } + public string guid { get; set; } + public string deviceKey { get; set; } + } + #endregion + #region 照片上传 + public class UFace_Photo + { + public string appId { get; set; } + public string token { get; set; } + public string guid { get; set; } + public string img { get; set; } + public byte type { get; set; } + public int validLevel { get; set; } + } + #endregion + #region 照片上传结果 + public class UFace_Photo_Result : UFace_Auth_Result + { + public UFace_Photo_Result_data data { get; set; } + } + public class UFace_Photo_Result_data + { + public string appId { get; set; } + public string guid { get; set; } + public string userGuid { get; set; } + public string personGuid { get; set; } + public int type { get; set; } + public string faceUrl { get; set; } + } + #endregion + +} diff --git a/基础类库/HuizhongLibrary/UFace/UfaceService.cs b/基础类库/HuizhongLibrary/UFace/UfaceService.cs new file mode 100644 index 0000000..f033189 --- /dev/null +++ b/基础类库/HuizhongLibrary/UFace/UfaceService.cs @@ -0,0 +1,260 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Text; +using System.Web.Script.Serialization; + +namespace HuizhongLibrary.UFace +{ + public class UfaceService + { + public static string appId=""; + public static string appKey = ""; + public static string appSecret = ""; + public static string token = ""; + + #region 获取AccessToken + public static string GetAccessToken(out string ErrorMessage) + { + ErrorMessage=""; + string url = "http://gs-api.uface.uni-ubi.com/v1/{"+ UfaceService.appId + "}/auth"; + var model = new UFace_Auth(); + model.appId = UfaceService.appId; + model.appKey = UfaceService.appKey; + model.CreateSign(UfaceService.appSecret); + String postmessage = model.ToJsonString(); + JavaScriptSerializer JsonConvert = new JavaScriptSerializer(); + UTF8Encoding encoding = new UTF8Encoding(); + byte[] data = encoding.GetBytes(postmessage); + string XmlContent = CustomIO.HttpRequest(url, "POST", "", null, HttpVersion.Version10, null, out ErrorMessage); + if (string.IsNullOrEmpty(ErrorMessage) == false) return ""; + var model2 = JsonConvert.Deserialize(XmlContent); + if (model2.result == 1) + { + return model2.data; + } + else + { + ErrorMessage = model2.msg; + } + return ""; + } + #endregion + #region 创建设备 + public static string CreateDevice(string deviceKey,string name,string tag,out string ErrorMessage) + { + ErrorMessage = ""; + string url = "http://gs-api.uface.uni-ubi.com/v1/" + UfaceService.appId + "/device"; + var model = new UFace_Device(); + model.appId = UfaceService.appId; + model.token = UfaceService.token; + model.deviceKey= deviceKey; + model.name = name; + model.tag = tag; + String postmessage = model.ToJsonString(); + JavaScriptSerializer JsonConvert = new JavaScriptSerializer(); + UTF8Encoding encoding = new UTF8Encoding(); + byte[] data = encoding.GetBytes(postmessage); + string XmlContent = CustomIO.HttpRequest(url, "POST", "", null, HttpVersion.Version10, null, out ErrorMessage); + if (string.IsNullOrEmpty(ErrorMessage) == false) return ""; + var model2 = JsonConvert.Deserialize(XmlContent); + if (model2.result == 1) + { + return model2.data; + } + else + { + ErrorMessage = model2.msg; + } + return ""; + } + #endregion + #region 设备列表查询 + public static List GetListDevice(string deviceKey, string name, string tag, out string ErrorMessage) + { + ErrorMessage = ""; + var ListModel = new List(); + string url = "http://gs-api.uface.uni-ubi.com/v1/" + UfaceService.appId + "/device/search"; + var model = new UFace_Device_Search(); + model.appId = UfaceService.appId; + model.token = UfaceService.token; + String postmessage = model.ToJsonString(); + JavaScriptSerializer JsonConvert = new JavaScriptSerializer(); + UTF8Encoding encoding = new UTF8Encoding(); + byte[] data = encoding.GetBytes(postmessage); + string XmlContent = CustomIO.HttpRequest(url, "POST", "", null, HttpVersion.Version10, null, out ErrorMessage); + if (string.IsNullOrEmpty(ErrorMessage) == false) return ListModel; + var model2 = JsonConvert.Deserialize(XmlContent); + if (model2.result == 1) + { + foreach (var item in model2.data.content) + { + var mm = item.Copy(); + ListModel.Add(mm); + } + } + else + { + ErrorMessage = model2.msg; + } + return ListModel; + } + #endregion + #region 人员新增 + public static UFace_Person_Info AddPerson(string deviceKey, string name, string tag, out string ErrorMessage) + { + ErrorMessage = ""; + string url = "http://gs-api.uface.uni-ubi.com/v1/" + UfaceService.appId + "/device/search"; + var model = new UFace_Person(); + model.appId = UfaceService.appId; + model.token = UfaceService.token; + String postmessage = model.ToJsonString(); + JavaScriptSerializer JsonConvert = new JavaScriptSerializer(); + UTF8Encoding encoding = new UTF8Encoding(); + byte[] data = encoding.GetBytes(postmessage); + string XmlContent = CustomIO.HttpRequest(url, "POST", "", null, HttpVersion.Version10, null, out ErrorMessage); + if (string.IsNullOrEmpty(ErrorMessage) == false) return null; + var model2 = JsonConvert.Deserialize(XmlContent); + if (model2.result == 1) + { + return model2.data; + } + else + { + ErrorMessage = model2.msg; + } + return null; + } + #endregion + #region 人员删除 + public static void DeletePerson(string guid, out string ErrorMessage) + { + ErrorMessage = ""; + string url = "http://gs-api.uface.uni-ubi.com/v1/"+ UfaceService.appId + "/person/"+ guid; + var model = new UFace_Person_Delete(); + model.appId = UfaceService.appId; + model.token = UfaceService.token; + model.guid = guid; + String postmessage = model.ToJsonString(); + JavaScriptSerializer JsonConvert = new JavaScriptSerializer(); + UTF8Encoding encoding = new UTF8Encoding(); + byte[] data = encoding.GetBytes(postmessage); + string XmlContent = CustomIO.HttpRequest(url, "DELETE", "", null, HttpVersion.Version10, null, out ErrorMessage); + if (string.IsNullOrEmpty(ErrorMessage) == false) return; + var model2 = JsonConvert.Deserialize(XmlContent); + if (model2.result == 1) + { + + } + else + { + ErrorMessage = model2.msg; + } + } + #endregion + #region 人员修改 + public static void UpdatePerson(string guid, out string ErrorMessage) + { + ErrorMessage = ""; + string url = "http://gs-api.uface.uni-ubi.com/v1/" + UfaceService.appId + "/person/" + guid; + var model = new UFace_Person_Delete(); + model.appId = UfaceService.appId; + model.token = UfaceService.token; + model.guid = guid; + String postmessage = model.ToJsonString(); + JavaScriptSerializer JsonConvert = new JavaScriptSerializer(); + UTF8Encoding encoding = new UTF8Encoding(); + byte[] data = encoding.GetBytes(postmessage); + string XmlContent = CustomIO.HttpRequest(url, "POST", "", null, HttpVersion.Version10, null, out ErrorMessage); + if (string.IsNullOrEmpty(ErrorMessage) == false) return; + var model2 = JsonConvert.Deserialize(XmlContent); + if (model2.result == 1) + { + + } + else + { + ErrorMessage = model2.msg; + } + } + #endregion + #region 人员授权 + public static void AddPersonPermission(UFace_PersonPermission model, out string ErrorMessage) + { + ErrorMessage = ""; + string url = "http://gs-api.uface.uni-ubi.com/v1/" + UfaceService.appId + "/person/" + model.guid + "/devices"; + model.appId = UfaceService.appId; + model.token = UfaceService.token; + String postmessage = model.ToJsonString(); + JavaScriptSerializer JsonConvert = new JavaScriptSerializer(); + UTF8Encoding encoding = new UTF8Encoding(); + byte[] data = encoding.GetBytes(postmessage); + string XmlContent = CustomIO.HttpRequest(url, "POST", "", null, HttpVersion.Version10, null, out ErrorMessage); + if (string.IsNullOrEmpty(ErrorMessage) == false) return; + var model2 = JsonConvert.Deserialize(XmlContent); + if (model2.result == 1) + { + + } + else + { + ErrorMessage = model2.msg; + } + } + #endregion + #region 人员消权 + public static void DeletePersonPermission(string guid,string deviceKey, out string ErrorMessage) + { + ErrorMessage = ""; + string url = "http://gs-api.uface.uni-ubi.com/v1/" + UfaceService.appId + "/person/" + guid + "/devices"; + var model = new UFace_PersonPermission_Delete(); + model.appId = UfaceService.appId; + model.token = UfaceService.token; + model.guid = guid; + model.deviceKey = deviceKey; + String postmessage = model.ToJsonString(); + JavaScriptSerializer JsonConvert = new JavaScriptSerializer(); + UTF8Encoding encoding = new UTF8Encoding(); + byte[] data = encoding.GetBytes(postmessage); + string XmlContent = CustomIO.HttpRequest(url, "POST", "", null, HttpVersion.Version10, null, out ErrorMessage); + if (string.IsNullOrEmpty(ErrorMessage) == false) return; + var model2 = JsonConvert.Deserialize(XmlContent); + if (model2.result == 1) + { + + } + else + { + ErrorMessage = model2.msg; + } + } + #endregion + #region 照片上传 + public static UFace_Photo_Result_data AddPhoto(UFace_Photo model, out string ErrorMessage) + { + ErrorMessage = ""; + string url = "http://gs-api.uface.uni-ubi.com/v1/" + UfaceService.appId + "/person/" + model.guid + "/face/valid"; + model.appId = UfaceService.appId; + model.token = UfaceService.token; + String postmessage = model.ToJsonString(); + JavaScriptSerializer JsonConvert = new JavaScriptSerializer(); + UTF8Encoding encoding = new UTF8Encoding(); + byte[] data = encoding.GetBytes(postmessage); + string XmlContent = CustomIO.HttpRequest(url, "POST", "", null, HttpVersion.Version10, null, out ErrorMessage); + if (string.IsNullOrEmpty(ErrorMessage) == false) return null; + var model2 = JsonConvert.Deserialize(XmlContent); + if (model2.result == 1) + { + return model2.data; + } + else + { + ErrorMessage = model2.msg; + } + return null; + } + #endregion + + } +} diff --git a/基础类库/HuizhongLibrary/UsingDll/AipSdk.dll b/基础类库/HuizhongLibrary/UsingDll/AipSdk.dll new file mode 100644 index 0000000..4adaac8 Binary files /dev/null and b/基础类库/HuizhongLibrary/UsingDll/AipSdk.dll differ diff --git a/基础类库/HuizhongLibrary/UsingDll/AopSdk.dll b/基础类库/HuizhongLibrary/UsingDll/AopSdk.dll new file mode 100644 index 0000000..0d19a48 Binary files /dev/null and b/基础类库/HuizhongLibrary/UsingDll/AopSdk.dll differ diff --git a/基础类库/HuizhongLibrary/UsingDll/Aspose.Pdf.dll b/基础类库/HuizhongLibrary/UsingDll/Aspose.Pdf.dll new file mode 100644 index 0000000..821b217 Binary files /dev/null and b/基础类库/HuizhongLibrary/UsingDll/Aspose.Pdf.dll differ diff --git a/基础类库/HuizhongLibrary/UsingDll/Aspose.Words.dll b/基础类库/HuizhongLibrary/UsingDll/Aspose.Words.dll new file mode 100644 index 0000000..1484ee9 Binary files /dev/null and b/基础类库/HuizhongLibrary/UsingDll/Aspose.Words.dll differ diff --git a/基础类库/HuizhongLibrary/UsingDll/BarcodeLib.dll b/基础类库/HuizhongLibrary/UsingDll/BarcodeLib.dll new file mode 100644 index 0000000..3fbf1e1 Binary files /dev/null and b/基础类库/HuizhongLibrary/UsingDll/BarcodeLib.dll differ diff --git a/基础类库/HuizhongLibrary/UsingDll/BlogComm.dll b/基础类库/HuizhongLibrary/UsingDll/BlogComm.dll new file mode 100644 index 0000000..61316db Binary files /dev/null and b/基础类库/HuizhongLibrary/UsingDll/BlogComm.dll differ diff --git a/基础类库/HuizhongLibrary/UsingDll/DirectShowLib-2005.dll b/基础类库/HuizhongLibrary/UsingDll/DirectShowLib-2005.dll new file mode 100644 index 0000000..ba11a16 Binary files /dev/null and b/基础类库/HuizhongLibrary/UsingDll/DirectShowLib-2005.dll differ diff --git a/基础类库/HuizhongLibrary/UsingDll/DysoftUCenter.dll b/基础类库/HuizhongLibrary/UsingDll/DysoftUCenter.dll new file mode 100644 index 0000000..89e4504 Binary files /dev/null and b/基础类库/HuizhongLibrary/UsingDll/DysoftUCenter.dll differ diff --git a/基础类库/HuizhongLibrary/UsingDll/Gma.QrCodeNet.Encoding.dll b/基础类库/HuizhongLibrary/UsingDll/Gma.QrCodeNet.Encoding.dll new file mode 100644 index 0000000..6295b86 Binary files /dev/null and b/基础类库/HuizhongLibrary/UsingDll/Gma.QrCodeNet.Encoding.dll differ diff --git a/基础类库/HuizhongLibrary/UsingDll/ICSharpCode.SharpZipLib.dll b/基础类库/HuizhongLibrary/UsingDll/ICSharpCode.SharpZipLib.dll new file mode 100644 index 0000000..fe643eb Binary files /dev/null and b/基础类库/HuizhongLibrary/UsingDll/ICSharpCode.SharpZipLib.dll differ diff --git a/基础类库/HuizhongLibrary/UsingDll/Interop.RTXCAPILib.dll b/基础类库/HuizhongLibrary/UsingDll/Interop.RTXCAPILib.dll new file mode 100644 index 0000000..c909630 Binary files /dev/null and b/基础类库/HuizhongLibrary/UsingDll/Interop.RTXCAPILib.dll differ diff --git a/基础类库/HuizhongLibrary/UsingDll/Interop.RTXCMODULEINTERFACELib.dll b/基础类库/HuizhongLibrary/UsingDll/Interop.RTXCMODULEINTERFACELib.dll new file mode 100644 index 0000000..da1d31b Binary files /dev/null and b/基础类库/HuizhongLibrary/UsingDll/Interop.RTXCMODULEINTERFACELib.dll differ diff --git a/基础类库/HuizhongLibrary/UsingDll/Interop.RTXClient.dll b/基础类库/HuizhongLibrary/UsingDll/Interop.RTXClient.dll new file mode 100644 index 0000000..6792ca1 Binary files /dev/null and b/基础类库/HuizhongLibrary/UsingDll/Interop.RTXClient.dll differ diff --git a/基础类库/HuizhongLibrary/UsingDll/Interop.RTXSAPILib.dll b/基础类库/HuizhongLibrary/UsingDll/Interop.RTXSAPILib.dll new file mode 100644 index 0000000..d86b8c2 Binary files /dev/null and b/基础类库/HuizhongLibrary/UsingDll/Interop.RTXSAPILib.dll differ diff --git a/基础类库/HuizhongLibrary/UsingDll/Interop.RTXServerApi.dll b/基础类库/HuizhongLibrary/UsingDll/Interop.RTXServerApi.dll new file mode 100644 index 0000000..e9a4afc Binary files /dev/null and b/基础类库/HuizhongLibrary/UsingDll/Interop.RTXServerApi.dll differ diff --git a/基础类库/HuizhongLibrary/UsingDll/Ionic.Zip.dll b/基础类库/HuizhongLibrary/UsingDll/Ionic.Zip.dll new file mode 100644 index 0000000..7b11577 Binary files /dev/null and b/基础类库/HuizhongLibrary/UsingDll/Ionic.Zip.dll differ diff --git a/基础类库/HuizhongLibrary/UsingDll/LEDSender.dll b/基础类库/HuizhongLibrary/UsingDll/LEDSender.dll new file mode 100644 index 0000000..cf35f94 Binary files /dev/null and b/基础类库/HuizhongLibrary/UsingDll/LEDSender.dll differ diff --git a/基础类库/HuizhongLibrary/UsingDll/LitJson.dll b/基础类库/HuizhongLibrary/UsingDll/LitJson.dll new file mode 100644 index 0000000..d83411a Binary files /dev/null and b/基础类库/HuizhongLibrary/UsingDll/LitJson.dll differ diff --git a/基础类库/HuizhongLibrary/UsingDll/MySql.Data.dll b/基础类库/HuizhongLibrary/UsingDll/MySql.Data.dll new file mode 100644 index 0000000..b732da4 Binary files /dev/null and b/基础类库/HuizhongLibrary/UsingDll/MySql.Data.dll differ diff --git a/基础类库/HuizhongLibrary/UsingDll/NPOI.OOXML.dll b/基础类库/HuizhongLibrary/UsingDll/NPOI.OOXML.dll new file mode 100644 index 0000000..bf6320e Binary files /dev/null and b/基础类库/HuizhongLibrary/UsingDll/NPOI.OOXML.dll differ diff --git a/基础类库/HuizhongLibrary/UsingDll/NPOI.OpenXml4Net.dll b/基础类库/HuizhongLibrary/UsingDll/NPOI.OpenXml4Net.dll new file mode 100644 index 0000000..720a5b2 Binary files /dev/null and b/基础类库/HuizhongLibrary/UsingDll/NPOI.OpenXml4Net.dll differ diff --git a/基础类库/HuizhongLibrary/UsingDll/NPOI.OpenXmlFormats.dll b/基础类库/HuizhongLibrary/UsingDll/NPOI.OpenXmlFormats.dll new file mode 100644 index 0000000..181a257 Binary files /dev/null and b/基础类库/HuizhongLibrary/UsingDll/NPOI.OpenXmlFormats.dll differ diff --git a/基础类库/HuizhongLibrary/UsingDll/NPOI.dll b/基础类库/HuizhongLibrary/UsingDll/NPOI.dll new file mode 100644 index 0000000..cb5ba17 Binary files /dev/null and b/基础类库/HuizhongLibrary/UsingDll/NPOI.dll differ diff --git a/基础类库/HuizhongLibrary/UsingDll/Newtonsoft.Json.dll b/基础类库/HuizhongLibrary/UsingDll/Newtonsoft.Json.dll new file mode 100644 index 0000000..71ba702 Binary files /dev/null and b/基础类库/HuizhongLibrary/UsingDll/Newtonsoft.Json.dll differ diff --git a/基础类库/HuizhongLibrary/UsingDll/O2S.Components.PDF4NET.dll b/基础类库/HuizhongLibrary/UsingDll/O2S.Components.PDF4NET.dll new file mode 100644 index 0000000..5809ea9 Binary files /dev/null and b/基础类库/HuizhongLibrary/UsingDll/O2S.Components.PDF4NET.dll differ diff --git a/基础类库/HuizhongLibrary/UsingDll/O2S.Components.PDFRender4NET.dll b/基础类库/HuizhongLibrary/UsingDll/O2S.Components.PDFRender4NET.dll new file mode 100644 index 0000000..5051fd6 Binary files /dev/null and b/基础类库/HuizhongLibrary/UsingDll/O2S.Components.PDFRender4NET.dll differ diff --git a/基础类库/HuizhongLibrary/UsingDll/OraOps11w.dll b/基础类库/HuizhongLibrary/UsingDll/OraOps11w.dll new file mode 100644 index 0000000..3003c67 Binary files /dev/null and b/基础类库/HuizhongLibrary/UsingDll/OraOps11w.dll differ diff --git a/基础类库/HuizhongLibrary/UsingDll/Oracle.ManagedDataAccess.dll b/基础类库/HuizhongLibrary/UsingDll/Oracle.ManagedDataAccess.dll new file mode 100644 index 0000000..560b5fa Binary files /dev/null and b/基础类库/HuizhongLibrary/UsingDll/Oracle.ManagedDataAccess.dll differ diff --git a/基础类库/HuizhongLibrary/UsingDll/RTXAX.dll b/基础类库/HuizhongLibrary/UsingDll/RTXAX.dll new file mode 100644 index 0000000..d7bde1a Binary files /dev/null and b/基础类库/HuizhongLibrary/UsingDll/RTXAX.dll differ diff --git a/基础类库/HuizhongLibrary/UsingDll/RTXCAPI.dll b/基础类库/HuizhongLibrary/UsingDll/RTXCAPI.dll new file mode 100644 index 0000000..81a2be1 Binary files /dev/null and b/基础类库/HuizhongLibrary/UsingDll/RTXCAPI.dll differ diff --git a/基础类库/HuizhongLibrary/UsingDll/SDKAPI.dll b/基础类库/HuizhongLibrary/UsingDll/SDKAPI.dll new file mode 100644 index 0000000..9c6769a Binary files /dev/null and b/基础类库/HuizhongLibrary/UsingDll/SDKAPI.dll differ diff --git a/基础类库/HuizhongLibrary/UsingDll/Spire.Doc.dll b/基础类库/HuizhongLibrary/UsingDll/Spire.Doc.dll new file mode 100644 index 0000000..c5969d5 Binary files /dev/null and b/基础类库/HuizhongLibrary/UsingDll/Spire.Doc.dll differ diff --git a/基础类库/HuizhongLibrary/UsingDll/Spire.License.dll b/基础类库/HuizhongLibrary/UsingDll/Spire.License.dll new file mode 100644 index 0000000..fbd5c96 Binary files /dev/null and b/基础类库/HuizhongLibrary/UsingDll/Spire.License.dll differ diff --git a/基础类库/HuizhongLibrary/UsingDll/Spire.Pdf.dll b/基础类库/HuizhongLibrary/UsingDll/Spire.Pdf.dll new file mode 100644 index 0000000..b9bf26f Binary files /dev/null and b/基础类库/HuizhongLibrary/UsingDll/Spire.Pdf.dll differ diff --git a/基础类库/HuizhongLibrary/UsingDll/System.Speech.dll b/基础类库/HuizhongLibrary/UsingDll/System.Speech.dll new file mode 100644 index 0000000..9cc1795 Binary files /dev/null and b/基础类库/HuizhongLibrary/UsingDll/System.Speech.dll differ diff --git a/基础类库/HuizhongLibrary/UsingDll/ThoughtWorks.QRCode.dll b/基础类库/HuizhongLibrary/UsingDll/ThoughtWorks.QRCode.dll new file mode 100644 index 0000000..83fed0f Binary files /dev/null and b/基础类库/HuizhongLibrary/UsingDll/ThoughtWorks.QRCode.dll differ diff --git a/基础类库/HuizhongLibrary/UsingDll/YaPin.Framework.Utility.dll b/基础类库/HuizhongLibrary/UsingDll/YaPin.Framework.Utility.dll new file mode 100644 index 0000000..674c76b Binary files /dev/null and b/基础类库/HuizhongLibrary/UsingDll/YaPin.Framework.Utility.dll differ diff --git a/基础类库/HuizhongLibrary/UsingDll/bouncycastle.crypto.dll b/基础类库/HuizhongLibrary/UsingDll/bouncycastle.crypto.dll new file mode 100644 index 0000000..8531f7f Binary files /dev/null and b/基础类库/HuizhongLibrary/UsingDll/bouncycastle.crypto.dll differ diff --git a/基础类库/HuizhongLibrary/UsingDll/dm.dll b/基础类库/HuizhongLibrary/UsingDll/dm.dll new file mode 100644 index 0000000..39bb241 Binary files /dev/null and b/基础类库/HuizhongLibrary/UsingDll/dm.dll differ diff --git a/基础类库/HuizhongLibrary/UsingDll/dmc.dll b/基础类库/HuizhongLibrary/UsingDll/dmc.dll new file mode 100644 index 0000000..867776a Binary files /dev/null and b/基础类库/HuizhongLibrary/UsingDll/dmc.dll differ diff --git a/基础类库/HuizhongLibrary/UsingDll/oci.dll b/基础类库/HuizhongLibrary/UsingDll/oci.dll new file mode 100644 index 0000000..ca54c6d Binary files /dev/null and b/基础类库/HuizhongLibrary/UsingDll/oci.dll differ diff --git a/基础类库/HuizhongLibrary/UsingDll/orannzsbb11.dll b/基础类库/HuizhongLibrary/UsingDll/orannzsbb11.dll new file mode 100644 index 0000000..964f56a Binary files /dev/null and b/基础类库/HuizhongLibrary/UsingDll/orannzsbb11.dll differ diff --git a/基础类库/HuizhongLibrary/UsingDll/oraociei11.dll b/基础类库/HuizhongLibrary/UsingDll/oraociei11.dll new file mode 100644 index 0000000..186f46f Binary files /dev/null and b/基础类库/HuizhongLibrary/UsingDll/oraociei11.dll differ diff --git a/基础类库/HuizhongLibrary/UsingDll/websocket-sharp.dll b/基础类库/HuizhongLibrary/UsingDll/websocket-sharp.dll new file mode 100644 index 0000000..75b4bf3 Binary files /dev/null and b/基础类库/HuizhongLibrary/UsingDll/websocket-sharp.dll differ diff --git a/基础类库/HuizhongLibrary/UsingDll/zxing.ce2.0.dll b/基础类库/HuizhongLibrary/UsingDll/zxing.ce2.0.dll new file mode 100644 index 0000000..889065a Binary files /dev/null and b/基础类库/HuizhongLibrary/UsingDll/zxing.ce2.0.dll differ diff --git a/基础类库/HuizhongLibrary/VoicePortSound.cs b/基础类库/HuizhongLibrary/VoicePortSound.cs new file mode 100644 index 0000000..0e72e77 --- /dev/null +++ b/基础类库/HuizhongLibrary/VoicePortSound.cs @@ -0,0 +1,439 @@ +using HuizhongLibrary.Network; +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO.Ports; +using System.Linq; +using System.Media; +using System.Text; +using System.Threading; +using System.Speech.Synthesis; +using System.Runtime.InteropServices; +using System.Text.RegularExpressions; +using HuizhongLibrary.Log; + +namespace HuizhongLibrary +{ + public class VoicePortSound + { + SerialPortService ser = new SerialPortService(); + SpeechSynthesizer synth = new SpeechSynthesizer(); + + public string PortName { get; set; } + public int BaudRate { get; set; } + public int DataBits { get; set; } + /// + /// 0不使用语音呼叫1使用微软语音呼叫2使用精灵SmartRead语音3使用外置串口语音呼叫 + /// + public int SoundType { get; set; } + public int SendSleep = 500; + Queue ListVoice = new Queue(); + + public PlayState Status; + + private AutoResetEvent AutoReset = new AutoResetEvent(false); + private bool IsRun = false; + public VoicePortSound() + { + this.BaudRate = 9600; + this.DataBits = 8; + ser.MaxSendNumber = 1; + ser.RefshSecond = 60; + ser.ReceiveData += ser_ReceiveData; + ser.OverMaxSend += new Action(ser_OverMaxSend); + //this.HardwareInit(); + } + #region 启动监控 + public void Start() + { + if (SoundType == 0) return; + if (SoundType == 1) + { + var list = synth.GetInstalledVoices(); + if (list.Count > 0) + { + foreach (InstalledVoice item in list) + { + if (item.VoiceInfo.Name == "Microsoft Huihui Desktop") synth.SelectVoice("Microsoft Huihui Desktop"); + if (item.VoiceInfo.Name == "Microsoft Huihui") synth.SelectVoice("Microsoft Huihui"); + if (item.VoiceInfo.Name == "Microsoft Lili Desktop") synth.SelectVoice("Microsoft Lili Desktop"); + if (item.VoiceInfo.Name == "Microsoft Lili") synth.SelectVoice("Microsoft Lili"); + ErrorFollow.TraceWrite("语音库名称", "", item.VoiceInfo.Name); + } + } + else + { + synth.SelectVoice("Microsoft Lili"); + } + } + if (SoundType == 2) + { + //SmartReadSDK.SmartRead_InitialAuth(0, 0, 0, 0, "support@smartysoft.com", "88888888", "111-111-111-111"); + } + if (SoundType == 3) + { + ser.Start(PortName, this.BaudRate, this.DataBits, Parity.None, StopBits.One); + } + else + { + Thread t = new Thread(this.OnStart); + t.Start(); + } + if (SoundType == 4) synth.SelectVoice("Microsoft Lili"); + } + #endregion + #region 停止 + public void Stop() + { + IsRun = false; + AutoReset.Set(); + ser.Stop(); + } + #endregion + + #region 超出最大发送次数 + void ser_OverMaxSend(SocketMessage obj) + { + ser.ListMessage.Clear(); + } + #endregion + #region 读取数据 + void ser_ReceiveData(SerialPort model) + { + switch (ser.Data[0]) + { + case 0x4A: + //PlaySound._HardwareSuccessful = true; + break; + case 0x41: + Status = PlayState.RecvCorrectCommand; + //ser.EndFirstMsg(); + break; + case 0x45: + Status = PlayState.RecvErrorCommand; + break; + case 0x4E: + Status = PlayState.Busy; + break; + case 0x4F: + Status = PlayState.Idle; + ser.EndFirstMsg(); + break; + default: + break; + } + + } + #endregion + #region 停止正在播放的语音 + public void HardwareStop() + { + if (SoundType == 3) + { + byte[] b = new byte[4]; + b[0] = 0xFD; + b[1] = 0x00; + b[2] = 0x01; + b[3] = 0x02; + ser.Send(b); + } + if (SoundType == 1 || SoundType == 4) synth.Pause(); + //if (SoundType == 2) SmartReadSDK.SmartRead_Stop(); + } + #endregion + #region 暂停语音 + public void HardwarePause() + { + if (SoundType == 3) + { + byte[] b = new byte[4]; + b[0] = 0xFD; + b[1] = 0x00; + b[2] = 0x01; + b[3] = 0x03; + ser.Send(b); + } + if (SoundType == 1 || SoundType == 4) synth.Pause(); + //if (SoundType == 2) SmartReadSDK.SmartRead_PauseORContinue(); + } + #endregion + #region 恢复暂停的语音 + public void HardwareResume() + { + if (SoundType == 3) + { + byte[] b = new byte[4]; + b[0] = 0xFD; + b[1] = 0x00; + b[2] = 0x01; + b[3] = 0x04; + ser.Send(b); + } + if (SoundType == 1 || SoundType == 4) synth.Resume(); + //if (SoundType == 2) SmartReadSDK.SmartRead_PauseORContinue(); + } + #endregion + #region 读取状态 + public void HardwareStatus() + { + byte[] b = new byte[4]; + b[0] = 0xFD; + b[1] = 0x00; + b[2] = 0x01; + b[3] = 0x04; + ser.Send(b); + } + #endregion + + #region 播放语音 + public void HardwareSpeak(string text) + { + Regex reg = new Regex(@"\[@暂停=\d+\]", RegexOptions.Multiline); + MatchCollection matches = reg.Matches(text); + if (matches.Count == 0) + { + if (SoundType == 3) + { + byte[] b = Encoding.GetEncoding("gb2312").GetBytes(text); + byte[] bytes = new byte[b.Length + 5]; + Int16 len = (Int16)(b.Length + 2); + bytes[0] = 0xFD; + bytes[1] = (byte)(len >> 8 & 0xFF); + bytes[2] = (byte)(len & 0xFF); + bytes[3] = 0x01; + bytes[4] = 0x00; + Array.Copy(b, 0, bytes, 5, b.Length); + SocketMessage msg = new SocketMessage(); + msg.Bytes = bytes; + msg.SendLength = msg.Bytes.Length; + msg.IsRevert = true; + msg.SequenceID = "4F"; + msg.FunNo = "4F"; + msg.IsLock = true; + ser.ListMessage.Add(msg); + } + else + { + lock (ListVoice) + { + TtsVoice m = new TtsVoice(); + m.VoiceText = text; + ListVoice.Enqueue(m); + } + } + } + else + { + string[] ss = reg.Split(text); + int index = 0; + int sleep = 0; + int len2 = ss.Length - 1; + foreach (string s in ss) + { + if (index < len2) sleep = Convert.ToInt32(matches[index].Value.Substring(5, matches[index].Value.Length - 6)); + if (SoundType == 3) + { + byte[] b = Encoding.GetEncoding("gb2312").GetBytes(s); + byte[] bytes = new byte[b.Length + 5]; + Int16 len = (Int16)(b.Length + 2); + bytes[0] = 0xFD; + bytes[1] = (byte)(len >> 8 & 0xFF); + bytes[2] = (byte)(len & 0xFF); + bytes[3] = 0x01; + bytes[4] = 0x00; + Array.Copy(b, 0, bytes, 5, b.Length); + + SocketMessage msg = new SocketMessage(); + msg.Bytes = bytes; + msg.SendLength = msg.Bytes.Length; + msg.IsRevert = true; + msg.SequenceID = "4F"; + msg.FunNo = "4F"; + msg.IsLock = true; + ser.ListMessage.Add(msg); + } + else + { + TtsVoice m = new TtsVoice(); + m.VoiceText = s; + m.SendSleep = sleep; + ListVoice.Enqueue(m); + } + sleep = 0; + index++; + } + } + } + #endregion + + #region 清除语音队列 + public void Clear() + { + if (SoundType == 3) + { + ser.ListMessage.Clear(); + } + else + { + lock (ListVoice) + { + ListVoice.Clear(); + } + } + } + #endregion + #region 读取语音 + TtsVoice CheckOut() + { + lock (ListVoice) + { + if (ListVoice.Count == 0) return null; + return ListVoice.Dequeue(); + } + } + #endregion + #region 语音朗读 + void PlayVoice(string text) + { + if (SoundType == 1 || SoundType == 4) synth.Speak(text); + if (SoundType == 2) + { + //SmartReadSDK.SmartRead_Speak(text, "", 1, 13, 50, 100, 1, -1, "http://www.smartysoft.com/cn/"); + } + } + #endregion + #region 播放线程 + void OnStart() + { + IsRun = true; + while (IsRun == true) + { + TtsVoice model = CheckOut(); + if (model != null) PlayVoice(model.VoiceText); + if (model == null || model.SendSleep == 0) { AutoReset.WaitOne(this.SendSleep, false); } + else { AutoReset.WaitOne(model.SendSleep, false); } + } + } + #endregion + } + + + public enum PlayState + { + InitializationSuccessful, + RecvCorrectCommand, + RecvErrorCommand, + Busy, + Idle + } + + public class TtsVoice + { + public string VoiceText = ""; + public int SendSleep = 0; + } + + #region SmartReadSDK + public class SmartReadSDK + { + ////初始化认证函数,使用语音功能前必须首先调用,进行认证。 + //[DllImport("smartread7.dll", EntryPoint = "SmartRead_InitialAuth")] + //public static extern int SmartRead_InitialAuth(int hwndEditText, int hwndMessage, int hwndProgress, int hwndToShow, string chMailBox, string chPassword, string chValidateCode); + + ////关闭函数,推出程序前必须调用 + //[DllImport("smartread7.dll", EntryPoint = "SmartRead_Close")] + //public static extern int SmartRead_Close(); + + ////朗读函数 + //[DllImport("smartread7.dll", EntryPoint = "SmartRead_Speak")] + //public static extern int SmartRead_Speak(string lpStr, string lpToShow, int iStyle, int iSpeech, int iRate, int iVolume, int iPunctuation, int iSelVoiceDevice, string lpLink); + + ////打开语音设置对话框,用于改变中英文语音,音量,语速,可自定义下载连接 + //[DllImport("smartread7.dll", EntryPoint = "SmartRead_SetDialog")] + //public static extern int SmartRead_SetDialog(int hwndFather, string lpDownPage); + + ////停止朗读函数 + //[DllImport("smartread7.dll", EntryPoint = "SmartRead_Stop")] + //public static extern int SmartRead_Stop(); + + ////将文本朗读到WAVE文件的函数,可设置输出的文件 + //[DllImport("smartread7.dll", EntryPoint = "SmartRead_SpeakToWave")] + //public static extern int SmartRead_SpeakToWave(string lpStr, string lpToShow, string lpWaveFile, int iStyle, int iSpeech, int iRate, int iVolume, int iFormat, int iPunctuation, string lpLink); + + ////获得朗读的位置 + //[DllImport("smartread7.dll", EntryPoint = "SmartRead_GetLocationInfo")] + //public static extern int SmartRead_GetLocationInfo(ref int iLocationInfo); + + ////在朗读过程中,改变音量,范围在0-100之间,100为最高音. + //[DllImport("smartread7.dll", EntryPoint = "SmartRead_SetVolume")] + //public static extern int SmartRead_SetVolume(int iVolume); + + ////在朗读过程中,改变语速,范围在0-100直接,100为最快速度. + //[DllImport("smartread7.dll", EntryPoint = "SmartRead_SetSpeed")] + //public static extern int SmartRead_SetSpeed(int iRate); + + ////在朗读过程中,获得音量,范围在0-100之间,100为最高音. + //[DllImport("smartread7.dll", EntryPoint = "SmartRead_GetVolume")] + //public static extern int SmartRead_GetVolume(ref int iVolume); + + ////在朗读过程中,获得语速,范围在0-100直接,100为最快速度. + //[DllImport("smartread7.dll", EntryPoint = "SmartRead_GetSpeed")] + //public static extern int SmartRead_GetSpeed(ref int iRate); + + ////在朗读过程中,实现暂停/继续功能. + //[DllImport("smartread7.dll", EntryPoint = "SmartRead_PauseORContinue")] + //public static extern int SmartRead_PauseORContinue(); + + ////返回值为本台电脑上声卡的数目 + //[DllImport("smartread7.dll", EntryPoint = "SmartRead_GetVoiceDeviceNum")] + //public static extern int SmartRead_GetVoiceDeviceNum(ref int iDeviceNum); + + ////语音开发包版本信息,开在任何时候调用 + //[DllImport("smartread7.dll", EntryPoint = "SmartRead_Version")] + //public static extern int SmartRead_Version(ref int iMaxVer, ref int iMinVer, ref int iYear, ref int iMonth, ref int iDay); + + ////朗读模式设置函数 + //[DllImport("smartread7.dll", EntryPoint = "SmartRead_SetMode")] + //public static extern int SmartRead_SetMode(int iMode); + + ////返回错误代码函数 + //[DllImport("smartread7.dll", EntryPoint = "SmartRead_GetErrCode")] + //public static extern int SmartRead_GetErrCode(); + + ////返回错误信息函数 + //[DllImport("smartread7.dll", EntryPoint = "SmartRead_GetErrMsg")] + //public static extern int SmartRead_GetErrMsg(StringBuilder szErrMsg); + + ////队列播放,获得已经朗读/总朗读文本信息数 + //[DllImport("smartread7.dll", EntryPoint = "SmartRead_QueueStatistics")] + //public static extern int SmartRead_QueueStatistics(ref int iReaded, ref int iTotal); + + ////队列播放,朗读下一条函数 + //[DllImport("smartread7.dll", EntryPoint = "SmartRead_QueueNext")] + //public static extern int SmartRead_QueueNext(); + + ////隐藏消息对话框 + //[DllImport("smartread7.dll", EntryPoint = "SmartRead_HideMessageBox")] + //public static extern int SmartRead_HideMessageBox(); + + ////参数设置函数 + //[DllImport("smartread7.dll", EntryPoint = "SmartRead_SetParameter")] + //public static extern int SmartRead_SetParameter(int iParaName, int iParaNum); + + + ////打开跟踪功能函数 + //[DllImport("smartread7.dll", EntryPoint = "SmartRead_Trace_ON")] + //public static extern int SmartRead_Trace_ON(); + + + ////关闭跟踪功能函数 + //[DllImport("smartread7.dll", EntryPoint = "SmartRead_Trace_OFF")] + //public static extern int SmartRead_Trace_OFF(); + + + //public static int SmartRead_iMultiReadTimes = 0;//重复或者多次朗读的次数 + //public static int SmartRead_iMultiRead = 0; //是否是重复或者多次朗读 + } + #endregion + +} diff --git a/基础类库/HuizhongLibrary/Web References/US/FileModel.datasource b/基础类库/HuizhongLibrary/Web References/US/FileModel.datasource new file mode 100644 index 0000000..e7b7e23 --- /dev/null +++ b/基础类库/HuizhongLibrary/Web References/US/FileModel.datasource @@ -0,0 +1,10 @@ + + + + HuizhongLibrary.US.FileModel, Web References.US.Reference.cs.dll, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null + \ No newline at end of file diff --git a/基础类库/HuizhongLibrary/Web References/US/Reference.cs b/基础类库/HuizhongLibrary/Web References/US/Reference.cs new file mode 100644 index 0000000..d811451 --- /dev/null +++ b/基础类库/HuizhongLibrary/Web References/US/Reference.cs @@ -0,0 +1,894 @@ +//------------------------------------------------------------------------------ +// +// 此代码由工具生成。 +// 运行时版本:4.0.30319.42000 +// +// 对此文件的更改可能会导致不正确的行为,并且如果 +// 重新生成代码,这些更改将会丢失。 +// +//------------------------------------------------------------------------------ + +// +// 此源代码是由 Microsoft.VSDesigner 4.0.30319.42000 版自动生成。 +// +#pragma warning disable 1591 + +namespace HuizhongLibrary.US { + using System; + using System.Web.Services; + using System.Diagnostics; + using System.Web.Services.Protocols; + using System.Xml.Serialization; + using System.ComponentModel; + + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.8.4084.0")] + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.ComponentModel.DesignerCategoryAttribute("code")] + [System.Web.Services.WebServiceBindingAttribute(Name="UpdateServiceSoap", Namespace="http://tempuri.org/")] + public partial class UpdateService : System.Web.Services.Protocols.SoapHttpClientProtocol { + + private System.Threading.SendOrPostCallback CheckVerOperationCompleted; + + private System.Threading.SendOrPostCallback CheckVersionOperationCompleted; + + private System.Threading.SendOrPostCallback UpdateCompleteOperationCompleted; + + private System.Threading.SendOrPostCallback GetFileByteOperationCompleted; + + private System.Threading.SendOrPostCallback CreateFileOperationCompleted; + + private System.Threading.SendOrPostCallback UploadFileOperationCompleted; + + private System.Threading.SendOrPostCallback DeleteBackTimeOutOperationCompleted; + + private System.Threading.SendOrPostCallback DeleteTempFileOperationCompleted; + + private System.Threading.SendOrPostCallback CancelUploadOperationCompleted; + + private System.Threading.SendOrPostCallback GetLogoNameOperationCompleted; + + private System.Threading.SendOrPostCallback GetLogoImageOperationCompleted; + + private System.Threading.SendOrPostCallback RegisterOperationCompleted; + + private System.Threading.SendOrPostCallback LoginOperationCompleted; + + private System.Threading.SendOrPostCallback UpdatePassWordOperationCompleted; + + private bool useDefaultCredentialsSetExplicitly; + + /// + public UpdateService() { + this.Url = global::HuizhongLibrary.Properties.Settings.Default.HuizhongLibrary_US_UpdateService; + if ((this.IsLocalFileSystemWebService(this.Url) == true)) { + this.UseDefaultCredentials = true; + this.useDefaultCredentialsSetExplicitly = false; + } + else { + this.useDefaultCredentialsSetExplicitly = true; + } + } + + public new string Url { + get { + return base.Url; + } + set { + if ((((this.IsLocalFileSystemWebService(base.Url) == true) + && (this.useDefaultCredentialsSetExplicitly == false)) + && (this.IsLocalFileSystemWebService(value) == false))) { + base.UseDefaultCredentials = false; + } + base.Url = value; + } + } + + public new bool UseDefaultCredentials { + get { + return base.UseDefaultCredentials; + } + set { + base.UseDefaultCredentials = value; + this.useDefaultCredentialsSetExplicitly = true; + } + } + + /// + public event CheckVerCompletedEventHandler CheckVerCompleted; + + /// + public event CheckVersionCompletedEventHandler CheckVersionCompleted; + + /// + public event UpdateCompleteCompletedEventHandler UpdateCompleteCompleted; + + /// + public event GetFileByteCompletedEventHandler GetFileByteCompleted; + + /// + public event CreateFileCompletedEventHandler CreateFileCompleted; + + /// + public event UploadFileCompletedEventHandler UploadFileCompleted; + + /// + public event DeleteBackTimeOutCompletedEventHandler DeleteBackTimeOutCompleted; + + /// + public event DeleteTempFileCompletedEventHandler DeleteTempFileCompleted; + + /// + public event CancelUploadCompletedEventHandler CancelUploadCompleted; + + /// + public event GetLogoNameCompletedEventHandler GetLogoNameCompleted; + + /// + public event GetLogoImageCompletedEventHandler GetLogoImageCompleted; + + /// + public event RegisterCompletedEventHandler RegisterCompleted; + + /// + public event LoginCompletedEventHandler LoginCompleted; + + /// + public event UpdatePassWordCompletedEventHandler UpdatePassWordCompleted; + + /// + [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/CheckVer", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] + public bool CheckVer(string CilentName, string DirectoryName, decimal CurrentVersion) { + object[] results = this.Invoke("CheckVer", new object[] { + CilentName, + DirectoryName, + CurrentVersion}); + return ((bool)(results[0])); + } + + /// + public void CheckVerAsync(string CilentName, string DirectoryName, decimal CurrentVersion) { + this.CheckVerAsync(CilentName, DirectoryName, CurrentVersion, null); + } + + /// + public void CheckVerAsync(string CilentName, string DirectoryName, decimal CurrentVersion, object userState) { + if ((this.CheckVerOperationCompleted == null)) { + this.CheckVerOperationCompleted = new System.Threading.SendOrPostCallback(this.OnCheckVerOperationCompleted); + } + this.InvokeAsync("CheckVer", new object[] { + CilentName, + DirectoryName, + CurrentVersion}, this.CheckVerOperationCompleted, userState); + } + + private void OnCheckVerOperationCompleted(object arg) { + if ((this.CheckVerCompleted != null)) { + System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); + this.CheckVerCompleted(this, new CheckVerCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); + } + } + + /// + [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/CheckVersion", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] + public FileModel[] CheckVersion(string CilentName, string DirectoryName, decimal CurrentVersion, out decimal NewVersion) { + object[] results = this.Invoke("CheckVersion", new object[] { + CilentName, + DirectoryName, + CurrentVersion}); + NewVersion = ((decimal)(results[1])); + return ((FileModel[])(results[0])); + } + + /// + public void CheckVersionAsync(string CilentName, string DirectoryName, decimal CurrentVersion) { + this.CheckVersionAsync(CilentName, DirectoryName, CurrentVersion, null); + } + + /// + public void CheckVersionAsync(string CilentName, string DirectoryName, decimal CurrentVersion, object userState) { + if ((this.CheckVersionOperationCompleted == null)) { + this.CheckVersionOperationCompleted = new System.Threading.SendOrPostCallback(this.OnCheckVersionOperationCompleted); + } + this.InvokeAsync("CheckVersion", new object[] { + CilentName, + DirectoryName, + CurrentVersion}, this.CheckVersionOperationCompleted, userState); + } + + private void OnCheckVersionOperationCompleted(object arg) { + if ((this.CheckVersionCompleted != null)) { + System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); + this.CheckVersionCompleted(this, new CheckVersionCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); + } + } + + /// + [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/UpdateComplete", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] + public void UpdateComplete(string CilentName, string DirectoryName, string Msg) { + this.Invoke("UpdateComplete", new object[] { + CilentName, + DirectoryName, + Msg}); + } + + /// + public void UpdateCompleteAsync(string CilentName, string DirectoryName, string Msg) { + this.UpdateCompleteAsync(CilentName, DirectoryName, Msg, null); + } + + /// + public void UpdateCompleteAsync(string CilentName, string DirectoryName, string Msg, object userState) { + if ((this.UpdateCompleteOperationCompleted == null)) { + this.UpdateCompleteOperationCompleted = new System.Threading.SendOrPostCallback(this.OnUpdateCompleteOperationCompleted); + } + this.InvokeAsync("UpdateComplete", new object[] { + CilentName, + DirectoryName, + Msg}, this.UpdateCompleteOperationCompleted, userState); + } + + private void OnUpdateCompleteOperationCompleted(object arg) { + if ((this.UpdateCompleteCompleted != null)) { + System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); + this.UpdateCompleteCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); + } + } + + /// + [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/GetFileByte", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] + [return: System.Xml.Serialization.XmlElementAttribute(DataType="base64Binary")] + public byte[] GetFileByte(string FilePath, long StartIndex, long Length) { + object[] results = this.Invoke("GetFileByte", new object[] { + FilePath, + StartIndex, + Length}); + return ((byte[])(results[0])); + } + + /// + public void GetFileByteAsync(string FilePath, long StartIndex, long Length) { + this.GetFileByteAsync(FilePath, StartIndex, Length, null); + } + + /// + public void GetFileByteAsync(string FilePath, long StartIndex, long Length, object userState) { + if ((this.GetFileByteOperationCompleted == null)) { + this.GetFileByteOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetFileByteOperationCompleted); + } + this.InvokeAsync("GetFileByte", new object[] { + FilePath, + StartIndex, + Length}, this.GetFileByteOperationCompleted, userState); + } + + private void OnGetFileByteOperationCompleted(object arg) { + if ((this.GetFileByteCompleted != null)) { + System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); + this.GetFileByteCompleted(this, new GetFileByteCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); + } + } + + /// + [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/CreateFile", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] + public void CreateFile(string fileName, long StreamLenth) { + this.Invoke("CreateFile", new object[] { + fileName, + StreamLenth}); + } + + /// + public void CreateFileAsync(string fileName, long StreamLenth) { + this.CreateFileAsync(fileName, StreamLenth, null); + } + + /// + public void CreateFileAsync(string fileName, long StreamLenth, object userState) { + if ((this.CreateFileOperationCompleted == null)) { + this.CreateFileOperationCompleted = new System.Threading.SendOrPostCallback(this.OnCreateFileOperationCompleted); + } + this.InvokeAsync("CreateFile", new object[] { + fileName, + StreamLenth}, this.CreateFileOperationCompleted, userState); + } + + private void OnCreateFileOperationCompleted(object arg) { + if ((this.CreateFileCompleted != null)) { + System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); + this.CreateFileCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); + } + } + + /// + [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/UploadFile", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] + public void UploadFile(string fileName, [System.Xml.Serialization.XmlElementAttribute(DataType="base64Binary")] byte[] data, int dataLength, long SeekLength) { + this.Invoke("UploadFile", new object[] { + fileName, + data, + dataLength, + SeekLength}); + } + + /// + public void UploadFileAsync(string fileName, byte[] data, int dataLength, long SeekLength) { + this.UploadFileAsync(fileName, data, dataLength, SeekLength, null); + } + + /// + public void UploadFileAsync(string fileName, byte[] data, int dataLength, long SeekLength, object userState) { + if ((this.UploadFileOperationCompleted == null)) { + this.UploadFileOperationCompleted = new System.Threading.SendOrPostCallback(this.OnUploadFileOperationCompleted); + } + this.InvokeAsync("UploadFile", new object[] { + fileName, + data, + dataLength, + SeekLength}, this.UploadFileOperationCompleted, userState); + } + + private void OnUploadFileOperationCompleted(object arg) { + if ((this.UploadFileCompleted != null)) { + System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); + this.UploadFileCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); + } + } + + /// + [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/DeleteBackTimeOut", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] + public void DeleteBackTimeOut(string DirectoryName, int BackFileNumber) { + this.Invoke("DeleteBackTimeOut", new object[] { + DirectoryName, + BackFileNumber}); + } + + /// + public void DeleteBackTimeOutAsync(string DirectoryName, int BackFileNumber) { + this.DeleteBackTimeOutAsync(DirectoryName, BackFileNumber, null); + } + + /// + public void DeleteBackTimeOutAsync(string DirectoryName, int BackFileNumber, object userState) { + if ((this.DeleteBackTimeOutOperationCompleted == null)) { + this.DeleteBackTimeOutOperationCompleted = new System.Threading.SendOrPostCallback(this.OnDeleteBackTimeOutOperationCompleted); + } + this.InvokeAsync("DeleteBackTimeOut", new object[] { + DirectoryName, + BackFileNumber}, this.DeleteBackTimeOutOperationCompleted, userState); + } + + private void OnDeleteBackTimeOutOperationCompleted(object arg) { + if ((this.DeleteBackTimeOutCompleted != null)) { + System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); + this.DeleteBackTimeOutCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); + } + } + + /// + [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/DeleteTempFile", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] + public void DeleteTempFile(string fileName) { + this.Invoke("DeleteTempFile", new object[] { + fileName}); + } + + /// + public void DeleteTempFileAsync(string fileName) { + this.DeleteTempFileAsync(fileName, null); + } + + /// + public void DeleteTempFileAsync(string fileName, object userState) { + if ((this.DeleteTempFileOperationCompleted == null)) { + this.DeleteTempFileOperationCompleted = new System.Threading.SendOrPostCallback(this.OnDeleteTempFileOperationCompleted); + } + this.InvokeAsync("DeleteTempFile", new object[] { + fileName}, this.DeleteTempFileOperationCompleted, userState); + } + + private void OnDeleteTempFileOperationCompleted(object arg) { + if ((this.DeleteTempFileCompleted != null)) { + System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); + this.DeleteTempFileCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); + } + } + + /// + [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/CancelUpload", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] + public void CancelUpload(string fileName) { + this.Invoke("CancelUpload", new object[] { + fileName}); + } + + /// + public void CancelUploadAsync(string fileName) { + this.CancelUploadAsync(fileName, null); + } + + /// + public void CancelUploadAsync(string fileName, object userState) { + if ((this.CancelUploadOperationCompleted == null)) { + this.CancelUploadOperationCompleted = new System.Threading.SendOrPostCallback(this.OnCancelUploadOperationCompleted); + } + this.InvokeAsync("CancelUpload", new object[] { + fileName}, this.CancelUploadOperationCompleted, userState); + } + + private void OnCancelUploadOperationCompleted(object arg) { + if ((this.CancelUploadCompleted != null)) { + System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); + this.CancelUploadCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); + } + } + + /// + [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/GetLogoName", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] + public string GetLogoName(string UserName, string CompanyDeviceCode) { + object[] results = this.Invoke("GetLogoName", new object[] { + UserName, + CompanyDeviceCode}); + return ((string)(results[0])); + } + + /// + public void GetLogoNameAsync(string UserName, string CompanyDeviceCode) { + this.GetLogoNameAsync(UserName, CompanyDeviceCode, null); + } + + /// + public void GetLogoNameAsync(string UserName, string CompanyDeviceCode, object userState) { + if ((this.GetLogoNameOperationCompleted == null)) { + this.GetLogoNameOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetLogoNameOperationCompleted); + } + this.InvokeAsync("GetLogoName", new object[] { + UserName, + CompanyDeviceCode}, this.GetLogoNameOperationCompleted, userState); + } + + private void OnGetLogoNameOperationCompleted(object arg) { + if ((this.GetLogoNameCompleted != null)) { + System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); + this.GetLogoNameCompleted(this, new GetLogoNameCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); + } + } + + /// + [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/GetLogoImage", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] + [return: System.Xml.Serialization.XmlElementAttribute(DataType="base64Binary")] + public byte[] GetLogoImage(string UserName, string CompanyDeviceCode) { + object[] results = this.Invoke("GetLogoImage", new object[] { + UserName, + CompanyDeviceCode}); + return ((byte[])(results[0])); + } + + /// + public void GetLogoImageAsync(string UserName, string CompanyDeviceCode) { + this.GetLogoImageAsync(UserName, CompanyDeviceCode, null); + } + + /// + public void GetLogoImageAsync(string UserName, string CompanyDeviceCode, object userState) { + if ((this.GetLogoImageOperationCompleted == null)) { + this.GetLogoImageOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetLogoImageOperationCompleted); + } + this.InvokeAsync("GetLogoImage", new object[] { + UserName, + CompanyDeviceCode}, this.GetLogoImageOperationCompleted, userState); + } + + private void OnGetLogoImageOperationCompleted(object arg) { + if ((this.GetLogoImageCompleted != null)) { + System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); + this.GetLogoImageCompleted(this, new GetLogoImageCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); + } + } + + /// + [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/Register", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] + public string Register(string ProgramName, string CompanyName, string CompanyDeviceCode, string UserName, string PassWord) { + object[] results = this.Invoke("Register", new object[] { + ProgramName, + CompanyName, + CompanyDeviceCode, + UserName, + PassWord}); + return ((string)(results[0])); + } + + /// + public void RegisterAsync(string ProgramName, string CompanyName, string CompanyDeviceCode, string UserName, string PassWord) { + this.RegisterAsync(ProgramName, CompanyName, CompanyDeviceCode, UserName, PassWord, null); + } + + /// + public void RegisterAsync(string ProgramName, string CompanyName, string CompanyDeviceCode, string UserName, string PassWord, object userState) { + if ((this.RegisterOperationCompleted == null)) { + this.RegisterOperationCompleted = new System.Threading.SendOrPostCallback(this.OnRegisterOperationCompleted); + } + this.InvokeAsync("Register", new object[] { + ProgramName, + CompanyName, + CompanyDeviceCode, + UserName, + PassWord}, this.RegisterOperationCompleted, userState); + } + + private void OnRegisterOperationCompleted(object arg) { + if ((this.RegisterCompleted != null)) { + System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); + this.RegisterCompleted(this, new RegisterCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); + } + } + + /// + [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/Login", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] + public bool Login(string UserName, string PassWord, string CompanyDeviceCode) { + object[] results = this.Invoke("Login", new object[] { + UserName, + PassWord, + CompanyDeviceCode}); + return ((bool)(results[0])); + } + + /// + public void LoginAsync(string UserName, string PassWord, string CompanyDeviceCode) { + this.LoginAsync(UserName, PassWord, CompanyDeviceCode, null); + } + + /// + public void LoginAsync(string UserName, string PassWord, string CompanyDeviceCode, object userState) { + if ((this.LoginOperationCompleted == null)) { + this.LoginOperationCompleted = new System.Threading.SendOrPostCallback(this.OnLoginOperationCompleted); + } + this.InvokeAsync("Login", new object[] { + UserName, + PassWord, + CompanyDeviceCode}, this.LoginOperationCompleted, userState); + } + + private void OnLoginOperationCompleted(object arg) { + if ((this.LoginCompleted != null)) { + System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); + this.LoginCompleted(this, new LoginCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); + } + } + + /// + [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/UpdatePassWord", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] + public bool UpdatePassWord(string UserName, string OldPassWord, string NewPassWord) { + object[] results = this.Invoke("UpdatePassWord", new object[] { + UserName, + OldPassWord, + NewPassWord}); + return ((bool)(results[0])); + } + + /// + public void UpdatePassWordAsync(string UserName, string OldPassWord, string NewPassWord) { + this.UpdatePassWordAsync(UserName, OldPassWord, NewPassWord, null); + } + + /// + public void UpdatePassWordAsync(string UserName, string OldPassWord, string NewPassWord, object userState) { + if ((this.UpdatePassWordOperationCompleted == null)) { + this.UpdatePassWordOperationCompleted = new System.Threading.SendOrPostCallback(this.OnUpdatePassWordOperationCompleted); + } + this.InvokeAsync("UpdatePassWord", new object[] { + UserName, + OldPassWord, + NewPassWord}, this.UpdatePassWordOperationCompleted, userState); + } + + private void OnUpdatePassWordOperationCompleted(object arg) { + if ((this.UpdatePassWordCompleted != null)) { + System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); + this.UpdatePassWordCompleted(this, new UpdatePassWordCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); + } + } + + /// + public new void CancelAsync(object userState) { + base.CancelAsync(userState); + } + + private bool IsLocalFileSystemWebService(string url) { + if (((url == null) + || (url == string.Empty))) { + return false; + } + System.Uri wsUri = new System.Uri(url); + if (((wsUri.Port >= 1024) + && (string.Compare(wsUri.Host, "localHost", System.StringComparison.OrdinalIgnoreCase) == 0))) { + return true; + } + return false; + } + } + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.8.4084.0")] + [System.SerializableAttribute()] + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.ComponentModel.DesignerCategoryAttribute("code")] + [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://tempuri.org/")] + public partial class FileModel { + + private string fileNameField; + + private long fileSizeField; + + private string fileUrlField; + + /// + public string FileName { + get { + return this.fileNameField; + } + set { + this.fileNameField = value; + } + } + + /// + public long FileSize { + get { + return this.fileSizeField; + } + set { + this.fileSizeField = value; + } + } + + /// + public string FileUrl { + get { + return this.fileUrlField; + } + set { + this.fileUrlField = value; + } + } + } + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.8.4084.0")] + public delegate void CheckVerCompletedEventHandler(object sender, CheckVerCompletedEventArgs e); + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.8.4084.0")] + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.ComponentModel.DesignerCategoryAttribute("code")] + public partial class CheckVerCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { + + private object[] results; + + internal CheckVerCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) { + this.results = results; + } + + /// + public bool Result { + get { + this.RaiseExceptionIfNecessary(); + return ((bool)(this.results[0])); + } + } + } + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.8.4084.0")] + public delegate void CheckVersionCompletedEventHandler(object sender, CheckVersionCompletedEventArgs e); + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.8.4084.0")] + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.ComponentModel.DesignerCategoryAttribute("code")] + public partial class CheckVersionCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { + + private object[] results; + + internal CheckVersionCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) { + this.results = results; + } + + /// + public FileModel[] Result { + get { + this.RaiseExceptionIfNecessary(); + return ((FileModel[])(this.results[0])); + } + } + + /// + public decimal NewVersion { + get { + this.RaiseExceptionIfNecessary(); + return ((decimal)(this.results[1])); + } + } + } + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.8.4084.0")] + public delegate void UpdateCompleteCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e); + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.8.4084.0")] + public delegate void GetFileByteCompletedEventHandler(object sender, GetFileByteCompletedEventArgs e); + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.8.4084.0")] + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.ComponentModel.DesignerCategoryAttribute("code")] + public partial class GetFileByteCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { + + private object[] results; + + internal GetFileByteCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) { + this.results = results; + } + + /// + public byte[] Result { + get { + this.RaiseExceptionIfNecessary(); + return ((byte[])(this.results[0])); + } + } + } + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.8.4084.0")] + public delegate void CreateFileCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e); + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.8.4084.0")] + public delegate void UploadFileCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e); + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.8.4084.0")] + public delegate void DeleteBackTimeOutCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e); + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.8.4084.0")] + public delegate void DeleteTempFileCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e); + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.8.4084.0")] + public delegate void CancelUploadCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e); + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.8.4084.0")] + public delegate void GetLogoNameCompletedEventHandler(object sender, GetLogoNameCompletedEventArgs e); + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.8.4084.0")] + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.ComponentModel.DesignerCategoryAttribute("code")] + public partial class GetLogoNameCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { + + private object[] results; + + internal GetLogoNameCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) { + this.results = results; + } + + /// + public string Result { + get { + this.RaiseExceptionIfNecessary(); + return ((string)(this.results[0])); + } + } + } + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.8.4084.0")] + public delegate void GetLogoImageCompletedEventHandler(object sender, GetLogoImageCompletedEventArgs e); + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.8.4084.0")] + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.ComponentModel.DesignerCategoryAttribute("code")] + public partial class GetLogoImageCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { + + private object[] results; + + internal GetLogoImageCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) { + this.results = results; + } + + /// + public byte[] Result { + get { + this.RaiseExceptionIfNecessary(); + return ((byte[])(this.results[0])); + } + } + } + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.8.4084.0")] + public delegate void RegisterCompletedEventHandler(object sender, RegisterCompletedEventArgs e); + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.8.4084.0")] + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.ComponentModel.DesignerCategoryAttribute("code")] + public partial class RegisterCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { + + private object[] results; + + internal RegisterCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) { + this.results = results; + } + + /// + public string Result { + get { + this.RaiseExceptionIfNecessary(); + return ((string)(this.results[0])); + } + } + } + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.8.4084.0")] + public delegate void LoginCompletedEventHandler(object sender, LoginCompletedEventArgs e); + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.8.4084.0")] + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.ComponentModel.DesignerCategoryAttribute("code")] + public partial class LoginCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { + + private object[] results; + + internal LoginCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) { + this.results = results; + } + + /// + public bool Result { + get { + this.RaiseExceptionIfNecessary(); + return ((bool)(this.results[0])); + } + } + } + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.8.4084.0")] + public delegate void UpdatePassWordCompletedEventHandler(object sender, UpdatePassWordCompletedEventArgs e); + + /// + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Web.Services", "4.8.4084.0")] + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.ComponentModel.DesignerCategoryAttribute("code")] + public partial class UpdatePassWordCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { + + private object[] results; + + internal UpdatePassWordCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : + base(exception, cancelled, userState) { + this.results = results; + } + + /// + public bool Result { + get { + this.RaiseExceptionIfNecessary(); + return ((bool)(this.results[0])); + } + } + } +} + +#pragma warning restore 1591 \ No newline at end of file diff --git a/基础类库/HuizhongLibrary/Web References/US/Reference.map b/基础类库/HuizhongLibrary/Web References/US/Reference.map new file mode 100644 index 0000000..bcd27a0 --- /dev/null +++ b/基础类库/HuizhongLibrary/Web References/US/Reference.map @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/基础类库/HuizhongLibrary/Web References/US/UpdateService.disco b/基础类库/HuizhongLibrary/Web References/US/UpdateService.disco new file mode 100644 index 0000000..bb2928c --- /dev/null +++ b/基础类库/HuizhongLibrary/Web References/US/UpdateService.disco @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/基础类库/HuizhongLibrary/Web References/US/UpdateService.wsdl b/基础类库/HuizhongLibrary/Web References/US/UpdateService.wsdl new file mode 100644 index 0000000..5f70940 --- /dev/null +++ b/基础类库/HuizhongLibrary/Web References/US/UpdateService.wsdl @@ -0,0 +1,623 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/基础类库/HuizhongLibrary/Weixin/WeixinDepartMent.cs b/基础类库/HuizhongLibrary/Weixin/WeixinDepartMent.cs new file mode 100644 index 0000000..b1407bb --- /dev/null +++ b/基础类库/HuizhongLibrary/Weixin/WeixinDepartMent.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace HuizhongLibrary.Weixin +{ + public class WeixinDepartMent + { + public string name { get; set; } + public int parentid { get; set; } + public int order { get; set; } + public int id { get; set; } + + public string ToJsonString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("{"); + sb.Append("\"name\":\"" + this.name + "\","); + sb.Append("\"parentid\":" + this.parentid +","); + sb.Append("\"order\":" + this.order + ","); + sb.Append("\"id\":" + this.id); + sb.Append("}"); + return sb.ToString(); + } + } +} diff --git a/基础类库/HuizhongLibrary/Weixin/WeixinMenu.cs b/基础类库/HuizhongLibrary/Weixin/WeixinMenu.cs new file mode 100644 index 0000000..1941609 --- /dev/null +++ b/基础类库/HuizhongLibrary/Weixin/WeixinMenu.cs @@ -0,0 +1,202 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace HuizhongLibrary.Weixin +{ + public class WeixinMenu + { + public List button { get; set; } + + public WeixinMenu() + { + button = new List(); + } + + + public string ToJsonString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("{"); + sb.Append("\"button\":"); + sb.Append("["); + foreach (var item in button) + { + sb.Append(item.ToJsonString()); + int index = button.IndexOf(item); + if (index < button.Count-1) sb.Append(","); + } + sb.Append("]"); + sb.Append("}"); + return sb.ToString(); + } + } + + public class WeixinMainButton + { + public string type { get; set; } + public string name { get; set; } + public string key { get; set; } + public string url { get; set; } + public string media_id { get; set; } + public List sub_button { get;set;} + + public WeixinMainButton() + { + sub_button = new List(); + type = ""; + name = ""; + key = ""; + url = ""; + media_id = ""; + } + + public WeixinMainButton(string type,string name,string key, string url) + { + sub_button = new List(); + this.type = type; + this.name = name; + this.key = key; + this.url = url; + this.media_id = ""; + } + + + + public string ToJsonString() + { + + StringBuilder sb = new StringBuilder(); + sb.Append("{"); + if (type!="") sb.Append("\"type\":\""+this.type+"\","); + sb.Append("\"name\":\"" + this.name + "\""); + if (key != "") sb.Append(",\"key\":\"" + this.key + "\""); + if (url != "") sb.Append(",\"url\":\"" + this.url + "\""); + if (media_id!="") sb.Append(",\"media_id\":\"" + this.media_id + "\""); + if (sub_button.Count > 0) + { + sb.Append(",\"sub_button\":["); + foreach (var item in sub_button) + { + sb.Append(item.ToJsonString()); + int index = sub_button.IndexOf(item); + if (index < sub_button.Count-1) sb.Append(","); + } + sb.Append("]"); + } + sb.Append("}"); + return sb.ToString(); + } + } + + public class WeixinChildButton + { + public string type { get; set; } + public string name { get; set; } + public string key { get; set; } + public string url { get; set; } + public string media_id { get; set; } + + + public WeixinChildButton(string type, string name, string key,string url) + { + this.type = type; + this.name = name; + this.key = key; + this.url = url; + this.media_id = ""; + } + + public string ToJsonString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("{"); + if (type != "") sb.Append("\"type\":\"" + this.type + "\","); + sb.Append("\"name\":\"" + this.name + "\""); + if (key != "") sb.Append(",\"key\":\"" + this.key + "\""); + if (url != "") sb.Append(",\"url\":\"" + this.url + "\""); + if (media_id != "") sb.Append(",\"media_id\":\"" + this.media_id + "\""); + sb.Append("}"); + return sb.ToString(); + } + } + + public class WeixinResult + { + public int errcode { get; set; } + public string errmsg { get; set; } + } + + public class WeixinResult2 + { + public int errcode { get; set; } + public string errmsg { get; set; } + public string access_token { get; set; } + public int expires_in { get; set; } + } + + public class WeixinArticleMessageResult + { + public string type { get; set; } + public string media_id { get; set; } + } + + public class WeixinJsSgin + { + public int errcode { get; set; } + public string errmsg { get; set; } + public string ticket { get; set; } + public int expires_in { get; set; } + } + + public class WeixinAccessToken + { + public string access_token { get; set; } + public int expires_in { get; set; } + } + + public class WeixinAccessToken2: WeixinAccessToken + { + public string refresh_token { get; set; } + public string openid { get; set; } + public string scope { get; set; } + } + + public class WeixinResult_media + { + public string type { get; set; } + public string media_id { get; set; } + } + + public class ShakeInfo + { + public ShakeData data { get; set; } + public int errcode { get; set; } + public string errmsg { get; set; } + } + + + public class ShakeData + { + public int page_id { get; set; } + public beacon_info beacon_info { get; set; } + public string openid { get; set; } + //public int poi_id { get; set; } + } + + public class beacon_info + { + public double distance { get; set; } + public int major { get; set; } + public int minor { get; set; } + public string uuid { get; set; } + } + + public class ShakeTicket + { + public int need_poi { get; set; } + public string ticket { get; set; } + } + +} diff --git a/基础类库/HuizhongLibrary/Weixin/WeixinMessage.cs b/基础类库/HuizhongLibrary/Weixin/WeixinMessage.cs new file mode 100644 index 0000000..966639a --- /dev/null +++ b/基础类库/HuizhongLibrary/Weixin/WeixinMessage.cs @@ -0,0 +1,184 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace HuizhongLibrary.Weixin +{ + public class WeixinMessage + { + public string touser { get; set; } + public string template_id { get; set; } + public string url { get; set; } + public List data { get; set; } + + public WeixinMessage() + { + data = new List(); + } + + public string ToJsonString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("{"); + sb.Append("\"touser\":\"" + this.touser + "\","); + sb.Append("\"template_id\":\"" + this.template_id + "\","); + sb.Append("\"url\":\"" + this.url + "\","); + sb.Append("\"data\":{"); + foreach (var item in data) + { + sb.Append(item.ToJsonString()); + int index = data.IndexOf(item); + if (index < data.Count-1) sb.Append(","); + } + sb.Append("}"); + sb.Append("}"); + return sb.ToString(); + } + } + + public class WeixinMessageData + { + public string Name { get; set; } + public string value { get; set; } + public string color { get; set; } + + public WeixinMessageData(string Name,string value) + { + this.Name = Name; + this.value = value; + this.color = ""; + } + + public WeixinMessageData(string Name, string value,string color) + { + this.Name = Name; + this.value = value; + this.color = color; + } + + public string ToJsonString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("\""+this.Name+"\":{"); + sb.Append("\"value\":\"" + this.value + "\","); + sb.Append("\"color\":\"" + this.color + "\""); + sb.Append("}"); + return sb.ToString(); + } + } + + public class WeixinEnterpriseMessage + { + public string touser { get; set; } + public string toparty { get; set; } + public string totag { get; set; } + public string msgtype { get; set; } + public int agentid { get; set; } + public string content { get; set; } + public int safe { get; set; } + public List articles { get; set; } + + public WeixinEnterpriseMessage() + { + touser = "@all"; + agentid = 3; + msgtype = "news"; + safe = 0; + articles = new List(); + } + + public string ToJsonString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("{"); + if (string.IsNullOrEmpty(touser) == false) sb.Append("\"touser\":\"" + this.touser + "\","); + if (string.IsNullOrEmpty(toparty) == false) sb.Append("\"toparty\":\"" + this.toparty + "\","); + if (string.IsNullOrEmpty(totag) == false) sb.Append("\"totag\":\"" + this.totag + "\","); + sb.Append("\"msgtype\":\"" + this.msgtype + "\","); + sb.Append("\"agentid\":" + this.agentid + ","); + if (msgtype == "text") + { + sb.Append("\"text\":{"); + sb.Append("\"content\":\"" + this.content + "\","); + sb.Append("},"); + } + if (msgtype == "news") + { + sb.Append("\"news\":{"); + sb.Append("\"articles\":["); + foreach (var item in articles) + { + sb.Append(item.ToJsonString()); + int index = articles.IndexOf(item); + if (index < articles.Count-1) sb.Append(","); + } + sb.Append("]"); + sb.Append("},"); + } + if (msgtype == "textcard") + { + sb.Append("\"textcard\":"); + sb.Append(articles[0].ToJsonString()); + sb.Append(","); + } + sb.Append("\"safe\":" + this.safe); + sb.Append("}"); + return sb.ToString(); + } + } + + public class WeixinEnterpriseArticle + { + public string title { get; set; } + public string description { get; set; } + public string url { get; set; } + public string btntxt { get; set; } + + public WeixinEnterpriseArticle() + { + btntxt = "更多"; + } + + public string ToJsonString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("{"); + sb.Append("\"title\":\"" + this.title + "\","); + sb.Append("\"description\":\"" + this.description + "\","); + sb.Append("\"url\":\"" + this.url + "\","); + sb.Append("\"btntxt\":\"" + this.btntxt + "\""); + sb.Append("}"); + return sb.ToString(); + } + } + + + public class WeixinArticleMessage + { + public string thumb_media_id { get; set; } + public string author { get; set; } + public string title { get; set; } + public string content_source_url { get; set; } + public string content { get; set; } + public int show_cover_pic { get; set; } + + public string ToJsonString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("{"); + sb.Append("\"articles\":[{"); + sb.Append("\"thumb_media_id\":\"" + this.thumb_media_id + "\","); + sb.Append("\"author\":\"" + this.author + "\","); + sb.Append("\"title\":\"" + this.title + "\","); + sb.Append("\"content_source_url\":\"" + this.content_source_url + "\","); + sb.Append("\"content\":\"" + this.content + "\","); + sb.Append("\"show_cover_pic\":" + this.show_cover_pic); + sb.Append("}"); + sb.Append("]"); + sb.Append("}"); + return sb.ToString(); + } + } + +} diff --git a/基础类库/HuizhongLibrary/Weixin/WeixinService.cs b/基础类库/HuizhongLibrary/Weixin/WeixinService.cs new file mode 100644 index 0000000..0bbd014 --- /dev/null +++ b/基础类库/HuizhongLibrary/Weixin/WeixinService.cs @@ -0,0 +1,621 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Text; +using System.Web.Script.Serialization; +using HuizhongLibrary.Log; +using HuizhongLibrary.Models; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; + +namespace HuizhongLibrary.Weixin +{ + public class WeixinService + { + #region 微信公众号 + #region 获取网页授权AccessToken + public static WeixinAccessToken2 WeixinWebAccessToken(string Appid, string Secret, string code, out string ErrorMessage) + { + string url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + Appid + "&secret=" + Secret + "&code=" + code + "&grant_type=authorization_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; + if (XmlContent.IndexOf("errcode") == -1) + { + WeixinAccessToken2 model2 = JsonConvert.Deserialize(XmlContent); + return model2; + } + else + { + WeixinResult model2 = JsonConvert.Deserialize(XmlContent); + ErrorMessage = model2.errmsg; + return null; + } + } + #endregion + + #region 获取授权 ShakeInfo + public static ShakeInfo GetWeixinShakeInfo(string AccessToken, ShakeTicket model, out string ErrorMessage) + { + string url = "https://api.weixin.qq.com/shakearound/user/getshakeinfo?access_token=" + AccessToken; + JavaScriptSerializer JsonConvert = new JavaScriptSerializer(); + //string postmessage = JsonConvert.Serialize(model); + string postmessage = model.ToJsonString(); + ErrorFollow.TraceWrite("ShakeTikect", "", postmessage); + 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; + ErrorFollow.TraceWrite("ShakeInfo", "", XmlContent); + ShakeInfo model2 = JsonConvert.Deserialize(XmlContent); + return model2; + + } + #endregion + + + + #region 获取AccessToken + public static string WeixinAccessToken(string Appid, string Secret, out string ErrorMessage) + { + string url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + Appid + "&secret=" + 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 ""; + if (XmlContent.IndexOf("errcode") == -1) + { + WeixinAccessToken model2 = JsonConvert.Deserialize(XmlContent); + //ErrorFollow.TraceWrite("AccessToken_expires_in", "", model2.expires_in.ToString()); + return model2.access_token; + } + else + { + WeixinResult model2 = JsonConvert.Deserialize(XmlContent); + ErrorMessage = model2.errmsg; + } + return ""; + } + #endregion + #region 根据code获取用户ID + public static WeixinUserResult2 GetWeixinUserResult(string AccessToken, string openid, out string ErrorMessage) + { + //ErrorFollow.TraceWrite("code:", "", code); + //ErrorFollow.TraceWrite("AccessToken:", "", AccessToken); + string url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + AccessToken + "&openid="+ openid + "&lang=zh_CN"; + 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; + ErrorFollow.TraceWrite("微信读取用户信息", "", XmlContent); + WeixinUserResult2 model2 = JsonConvert.Deserialize(XmlContent); + if (model2.errcode != 0) + { + ErrorMessage = XmlContent; + } + return model2; + } + #endregion + #region 自定义菜单创建接口 + public static void WeixinMenuDown(string AccessToken, WeixinMenu model, out string ErrorMessage) + { + string url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + AccessToken; + JavaScriptSerializer JsonConvert = new JavaScriptSerializer(); + //string postmessage = JsonConvert.Serialize(model); + string postmessage = model.ToJsonString(); + ErrorFollow.TraceWrite("创建菜单", "", postmessage); + 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; + WeixinResult model2 = JsonConvert.Deserialize(XmlContent); + if (model2.errcode == 0) return; + ErrorMessage = model2.errmsg; + } + #endregion + #region 删除菜单接口 + public static void WeixinMenuDelete(string AccessToken, out string ErrorMessage) + { + string url = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=" + AccessToken; + 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; + WeixinResult model2 = JsonConvert.Deserialize(XmlContent); + if (model2.errcode == 0) return; + ErrorMessage = model2.errmsg; + } + #endregion + #region 发送模板消息接口 + public static void WeixinTemplateMessage(string AccessToken, WeixinMessage model, out string ErrorMessage) + { + string url = "https://api.weixin.qq.com/cgi-bin/message/template/send?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; + WeixinResult model2 = JsonConvert.Deserialize(XmlContent); + if (model2.errcode == 0) return; + ErrorMessage = model2.errmsg; + } + #endregion + #region 发送模板消息接口 + public static void WeixinTemplateMessage(string AccessToken, string msg, out string ErrorMessage) + { + string url = "https://api.weixin.qq.com/cgi-bin/message/template/send?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; + WeixinResult model2 = JsonConvert.Deserialize(XmlContent); + if (model2.errcode == 0) return; + ErrorMessage = model2.errmsg; + } + #endregion + #region 发送微信文章消息接口 + public static string WeixinArticleMessage(string AccessToken, WeixinArticleMessage model, out string ErrorMessage) + { + string url = "https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=" + AccessToken; + JavaScriptSerializer JsonConvert = new JavaScriptSerializer(); + string postmessage = model.ToJsonString(); + //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 ""; + if (XmlContent.IndexOf("errcode") >=0) + { + WeixinResult modelerror = JsonConvert.Deserialize(XmlContent); + ErrorMessage = modelerror.errmsg; + return ""; + } + WeixinArticleMessageResult model2 = JsonConvert.Deserialize(XmlContent); + return model2.media_id; + } + #endregion + #region 发送微信文章消息接口 + public static void WeixinSendArticle(string AccessToken, string media_id, out string ErrorMessage) + { + string url = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token=" + AccessToken; + JavaScriptSerializer JsonConvert = new JavaScriptSerializer(); + //string postmessage = JsonConvert.Serialize(model); + string postmessage = "{\"filter\":{\"is_to_all\":true},\"mpnews\":{\"media_id\":\"" + media_id+ "\"}, \"msgtype\":\"mpnews\", \"send_ignore_reprint\":0}"; + //string postmessage = "{\"touser\":{\"oYOKQw-3CeQHiEw4AOJWXVFmlSHc\"},\"mpnews\":{\"media_id\":\"" + media_id + "\"}, \"msgtype\":\"mpnews\", \"send_ignore_reprint\":0}"; + 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; + if (XmlContent.IndexOf("errcode") >=0) + { + WeixinResult modelerror = JsonConvert.Deserialize(XmlContent); + ErrorMessage = modelerror.errmsg; + return; + } + WeixinResult model2 = JsonConvert.Deserialize(XmlContent); + if (model2.errcode == 0) return; + ErrorMessage = model2.errmsg; + } + #endregion + #region 新增临时素材 + + #endregion + #region jssdk签名 + public static String Getjssdk_Ticket(string AccessToken, out string ErrorMessage) + { + string url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + AccessToken + "&type=jsapi"; + string XmlContent = CustomIO.HttpRequest(url, "POST", "text/json", null, HttpVersion.Version10, null, out ErrorMessage); + JavaScriptSerializer JsonConvert = new JavaScriptSerializer(); + WeixinJsSgin model2 = JsonConvert.Deserialize(XmlContent); + //ErrorFollow.TraceWrite("Ticket_expires_in", "", model2.expires_in.ToString()); + if (model2.errcode == 0) return model2.ticket; + ErrorMessage = model2.errmsg; + return null; + } + #endregion + #endregion + #region 微信企业号 + #region 根据code获取用户ID + public static WeixinUserResult GetWeixinEnterpriseUserResult(string AccessToken,string code, out string ErrorMessage) + { + //ErrorFollow.TraceWrite("code:", "", code); + //ErrorFollow.TraceWrite("AccessToken:", "", AccessToken); + string url = "https://qyapi.weixin.qq.com/cgi-bin/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; + ErrorFollow.TraceWrite("企业号读取用户信息", "", XmlContent); + WeixinUserResult model2 = JsonConvert.Deserialize(XmlContent); + if (model2.errcode != 0) + { + ErrorMessage = XmlContent; + } + return model2; + } + #endregion + #region 获取AccessToken + public static string WeixinEnterpriseAccessToken(string corpid, string corpsecret, out string ErrorMessage) + { + string url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpid + "&corpsecret=" + corpsecret; + 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 ""; + WeixinResult2 model2 = JsonConvert.Deserialize(XmlContent); + if (model2.errcode != 0) ErrorMessage = model2.errmsg; + return model2.access_token; + } + #endregion + #region 自定义菜单创建接口 + public static void WeixinEnterpriseMenuDown(string AccessToken, string Agentid, WeixinMenu model, out string ErrorMessage) + { + string url = "https://qyapi.weixin.qq.com/cgi-bin/menu/create?access_token=" + AccessToken + "&agentid=" + Agentid; + 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; + WeixinResult model2 = JsonConvert.Deserialize(XmlContent); + if (model2.errcode == 0) return; + ErrorMessage = model2.errmsg; + } + #endregion + #region 删除菜单接口 + public static void WeixinEnterpriseMenuDelete(string AccessToken, string Agentid, out string ErrorMessage) + { + string url = "https://qyapi.weixin.qq.com/cgi-bin/menu/delete?access_token=" + AccessToken + "&agentid=" + Agentid; + 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; + WeixinResult model2 = JsonConvert.Deserialize(XmlContent); + if (model2.errcode == 0) return; + ErrorMessage = model2.errmsg; + } + #endregion + #region 发送企业消息接口 + public static void WeixinEnterpriseMessage(string AccessToken, WeixinEnterpriseMessage model, out string ErrorMessage) + { + string url = " https://qyapi.weixin.qq.com/cgi-bin/message/send?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; + WeixinResult model2 = JsonConvert.Deserialize(XmlContent); + if (model2.errcode == 0) return; + ErrorMessage = model2.errmsg; + } + #endregion + #region 发送企业消息接口 + public static void WeixinEnterpriseMessage(string AccessToken, string msg, out string ErrorMessage) + { + string url = " https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + AccessToken; + JavaScriptSerializer JsonConvert = new JavaScriptSerializer(); + 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; + WeixinResult model2 = JsonConvert.Deserialize(XmlContent); + if (model2.errcode == 0) return; + ErrorMessage = model2.errmsg; + } + #endregion + #region 创建部门接口 + public static void WeixinDepartMentCreate(string AccessToken, WeixinDepartMent model, out string ErrorMessage) + { + string url = "https://qyapi.weixin.qq.com/cgi-bin/department/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; + WeixinResult model2 = JsonConvert.Deserialize(XmlContent); + if (model2.errcode == 0) return; + ErrorMessage = model2.errmsg; + } + #endregion + #region 创建部门接口 + public static void WeixinDepartMentCreate(string AccessToken, string msg, out string ErrorMessage) + { + string url = "https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token=" + AccessToken; + JavaScriptSerializer JsonConvert = new JavaScriptSerializer(); + 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; + WeixinResult model2 = JsonConvert.Deserialize(XmlContent); + if (model2.errcode == 0) return; + ErrorMessage = model2.errmsg; + } + #endregion + #region 修改部门接口 + public static void WeixinDepartMentUpdate(string AccessToken, WeixinDepartMent model, out string ErrorMessage) + { + string + url = "https://qyapi.weixin.qq.com/cgi-bin/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; + WeixinResult model2 = JsonConvert.Deserialize(XmlContent); + if (model2.errcode == 0) return; + ErrorMessage = model2.errmsg; + } + #endregion + #region 修改部门接口 + public static void WeixinDepartMentUpdate(string AccessToken, string msg, out string ErrorMessage) + { + string + url = "https://qyapi.weixin.qq.com/cgi-bin/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; + WeixinResult model2 = JsonConvert.Deserialize(XmlContent); + if (model2.errcode == 0) return; + ErrorMessage = model2.errmsg; + } + #endregion + #region 删除部门接口 + public static void WeixinDepartMentDelete(string AccessToken, string DeptID, out string ErrorMessage) + { + string url = "https://qyapi.weixin.qq.com/cgi-bin/department/delete?access_token=" + AccessToken + "&id=" + DeptID; + 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; + WeixinResult model2 = JsonConvert.Deserialize(XmlContent); + if (model2.errcode == 0) return; + ErrorMessage = model2.errmsg; + } + #endregion + #region 创建员工接口 + public static void WeixinUserCreate(string AccessToken, WeixinUser model, out string ErrorMessage) + { + string url = "https://qyapi.weixin.qq.com/cgi-bin/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; + WeixinResult model2 = JsonConvert.Deserialize(XmlContent); + if (model2.errcode == 0) return; + ErrorMessage = model2.errmsg; + } + #endregion + #region 创建员工接口 + public static void WeixinUserCreate(string AccessToken, string msg, out string ErrorMessage) + { + string url = "https://qyapi.weixin.qq.com/cgi-bin/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; + WeixinResult model2 = JsonConvert.Deserialize(XmlContent); + if (model2.errcode == 0) return; + ErrorMessage = model2.errmsg; + } + #endregion + #region 修改员工接口 + public static void WeixinUserUpdate(string AccessToken, WeixinUser model, out string ErrorMessage) + { + string url = "https://qyapi.weixin.qq.com/cgi-bin/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; + WeixinResult model2 = JsonConvert.Deserialize(XmlContent); + if (model2.errcode == 0) return; + ErrorMessage = model2.errmsg; + } + #endregion + #region 修改员工接口 + public static void WeixinUserUpdate(string AccessToken, string msg, out string ErrorMessage) + { + string url = "https://qyapi.weixin.qq.com/cgi-bin/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; + WeixinResult model2 = JsonConvert.Deserialize(XmlContent); + if (model2.errcode == 0) return; + ErrorMessage = model2.errmsg; + } + #endregion + #region 删除员工接口 + public static void WeixinUserDelete(string AccessToken, string UserID, out string ErrorMessage) + { + string url = "https://qyapi.weixin.qq.com/cgi-bin/user/delete?access_token=" + AccessToken + "&userid=" + UserID; + 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; + WeixinResult model2 = JsonConvert.Deserialize(XmlContent); + if (model2.errcode == 0) return; + ErrorMessage = model2.errmsg; + } + #endregion + #region 批量删除员工接口 + public static void WeixinUserDeleteList(string AccessToken, List useridlist, out string ErrorMessage) + { + string url = "https://qyapi.weixin.qq.com/cgi-bin/user/batchdelete?access_token=" + AccessToken; + JavaScriptSerializer JsonConvert = new JavaScriptSerializer(); + StringBuilder sb = new StringBuilder(); + sb.Append("{"); + sb.Append("\"useridlist\":"); + sb.Append("["); + foreach (var item in useridlist) + { + sb.Append("\"" + item + "\""); + int index = useridlist.IndexOf(item); + if (index < useridlist.Count) sb.Append(","); + } + sb.Append("]"); + sb.Append("}"); + string postmessage = sb.ToString(); + 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; + WeixinResult model2 = JsonConvert.Deserialize(XmlContent); + if (model2.errcode == 0) return; + ErrorMessage = model2.errmsg; + } + #endregion + #region 上传临时素材接口 + public static string WeixinUploadTempFile(string AccessToken, string HeadImagePath, out string ErrorMessage) + { + List ListModel = new List(); + ListModel.Add(new PostDateClass() { Key = "media", Value = HeadImagePath, Type = 1 }); + string url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=" + AccessToken + "&type=image"; + string XmlContent = CustomIO.HttpFileRequest(url, ListModel, out ErrorMessage); + if (string.IsNullOrEmpty(ErrorMessage) == false) return ""; + JavaScriptSerializer JsonConvert = new JavaScriptSerializer(); + if (XmlContent.IndexOf("errcode") >= 0) + { + WeixinResult modelerror = JsonConvert.Deserialize(XmlContent); + ErrorMessage = modelerror.errmsg; + return ""; + } + WeixinResult_media model2 = JsonConvert.Deserialize(XmlContent); + return model2.media_id; + } + #endregion + #endregion + #region 微信小程序 + #region 根据code获取用户ID + public static string GetWeixinAppletOpenID(string appid, string secret,string code,out string ErrorMessage) + { + string url = "https://api.weixin.qq.com/sns/jscode2session?appid="+ appid + "&secret="+ secret + "&js_code="+ code + "&grant_type=authorization_code"; + string result = CustomIO.HttpRequest(url, "GET", "", null, HttpVersion.Version10, null, out ErrorMessage); + if (string.IsNullOrEmpty(ErrorMessage) == false) + { + ErrorFollow.TraceWrite("微信小程序读取用户信息(错误)", "", ErrorMessage); + return ""; + } + ErrorFollow.TraceWrite("微信小程序读取用户信息返回", "", result); + var joRoot = (JObject)JsonConvert.DeserializeObject(result); + int errcode = joRoot.Value("errcode"); + if (errcode == 0) + { + var openid = joRoot.Value("openid"); + return openid; + } + else + { + ErrorMessage = joRoot.Value("errmsg"); + } + return ""; + } + #endregion + #endregion + #region 统一下单接口 + public static WeixinPayOddResult GetWeixinPayOdd(string appid,string secret, string mchid,string description, string out_trade_no,string attach,string notify_url, int total,string openid,string serial_no) + { + string url = "https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi"; + var model = new WeixinPayOddResult(); + model.timeStamp = CustomIO.GetTimeStamp(DateTime.Now, "TotalSeconds").ToString(); + model.nonceStr = CustomIO.GetRandomString(32, true, false, true, false, ""); + + JObject obj = new JObject(); + obj.Add("appid", appid); + obj.Add("mchid", mchid); + obj.Add("description", description); + obj.Add("out_trade_no", out_trade_no); + obj.Add("attach", attach); + obj.Add("notify_url", notify_url); + JObject amount = new JObject(); + amount.Add("total", total); + amount.Add("currency", "CNY"); + obj.Add("amount", amount); + JObject payer = new JObject(); + payer.Add("openid", openid); + obj.Add("payer", payer); + string json = obj.ToString(Formatting.None); + + + var sb = new StringBuilder(); + sb.Append("POST" + "\n"); + sb.Append("/v3/pay/transactions/jsapi" + "\n"); + sb.Append(model.timeStamp + "\n"); + sb.Append(model.nonceStr + "\n"); + sb.Append(json + "\n"); + String signStr = sb.ToString(); + string key = System.IO.File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "zjzs.pem"); + var signature = CustomIO.Sign_RSA(signStr, key); + + var ListHader = new List(); + ListHader.Add("Authorization: WECHATPAY2-SHA256-RSA2048 mchid=\"" + mchid + "\",nonce_str=\""+ model.nonceStr + "\",signature=\""+ signature + "\",timestamp=\""+ model.timeStamp + "\",serial_no=\""+ serial_no + "\""); + + ErrorFollow.TraceWrite("微信小程序统一下单接口签名", signStr, ListHader[0]); + ErrorFollow.TraceWrite("微信小程序统一下单接口提交", url, json); + //UTF8Encoding encoding = new UTF8Encoding(); + byte[] data = Encoding.UTF8.GetBytes(json); + string ErrorMessage = ""; + string result = CustomIO.HttpRequest(url, "POST", "application/json;charset=UTF-8", ListHader, HttpVersion.Version10, data, out ErrorMessage, "application/json"); + if (string.IsNullOrEmpty(ErrorMessage) == false) + { + ErrorFollow.TraceWrite("微信小程序统一下单接口返回", "", ErrorMessage); + model.error = ErrorMessage; + return model; + } + ErrorFollow.TraceWrite("微信小程序统一下单接口返回", "", result); + try + { + var joRoot = (JObject)JsonConvert.DeserializeObject(result); + model.package = "prepay_id=" + joRoot.Value("prepay_id"); + sb.Clear(); + sb.Append(appid + "\n"); + sb.Append(model.timeStamp + "\n"); + sb.Append(model.nonceStr + "\n"); + sb.Append(model.package + "\n"); + signStr = sb.ToString(); + model.paySign = CustomIO.Sign_RSA(signStr, key); + ErrorFollow.TraceWrite("微信小程序接口签名返回", signStr, model.ToJsonString()); + return model; + } + catch (Exception ex) + { + ErrorFollow.TraceWrite("微信小程序统一下单接口错误", ex.StackTrace, ex.Message); + model.error = ex.Message; + return model; + } + } + #endregion + + } +} diff --git a/基础类库/HuizhongLibrary/Weixin/WeixinUser.cs b/基础类库/HuizhongLibrary/Weixin/WeixinUser.cs new file mode 100644 index 0000000..5c6002c --- /dev/null +++ b/基础类库/HuizhongLibrary/Weixin/WeixinUser.cs @@ -0,0 +1,127 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace HuizhongLibrary.Weixin +{ + public class WeixinUser + { + public string userid { get; set; } + public string name { get; set; } + public List department { get; set; } + public string position { get; set; } + public string mobile { get; set; } + public string gender { get; set; } + public string email { get; set; } + public string weixinid { get; set; } + public string avatar_mediaid { get; set; } + public int enable { get; set; } + public List extattr { get; set; } + + public WeixinUser() + { + department = new List(); + extattr = new List(); + enable = -1; + } + + + public string ToJsonString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("{"); + sb.Append("\"userid\":\"" + this.userid + "\","); + if (string.IsNullOrEmpty(name)==false) sb.Append("\"name\":\"" + this.name + "\","); + if (department.Count > 0) + { + sb.Append("\"department\":["); + foreach (int item in department) + { + sb.Append(item); + int index = department.IndexOf(item); + if (index < department.Count-1) sb.Append(","); + } + sb.Append("],"); + } + if (string.IsNullOrEmpty(position) == false) sb.Append("\"position\":\"" + this.position + "\","); + if (string.IsNullOrEmpty(mobile) == false) sb.Append("\"mobile\":\"" + this.mobile + "\","); + if (string.IsNullOrEmpty(gender) == false) sb.Append("\"gender\":\"" + this.gender + "\","); + if (string.IsNullOrEmpty(email) == false) sb.Append("\"email\":\"" + this.email + "\","); + if (string.IsNullOrEmpty(weixinid) == false) sb.Append("\"weixinid\":\"" + this.weixinid + "\","); + if (this.enable>=0) sb.Append("\"enable\":" + this.enable + ","); + if (string.IsNullOrEmpty(avatar_mediaid) == false) sb.Append("\"avatar_mediaid\":\"" + this.avatar_mediaid + "\","); + if (extattr.Count > 0) + { + sb.Append("\"extattr\": {\"attrs\":"); + sb.Append("["); + foreach (var item in extattr) + { + sb.Append(item.ToJsonString()); + int index = extattr.IndexOf(item); + if (index < extattr.Count-1) sb.Append(","); + } + sb.Append("]"); + sb.Append("}"); + sb.Append("}"); + return sb.ToString(); + } + else + { + string s = sb.ToString(); + s = s.Remove(s.Length-1); + s += "}"; + return s; + } + } + } + public class WeixinAttr + { + public string name { get; set; } + public string value { get; set; } + public string ToJsonString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("{"); + sb.Append("\"name\":\"" + this.name + "\","); + sb.Append("\"value\":\"" + this.value + "\""); + sb.Append("}"); + return sb.ToString(); + } + } + + public class WeixinUserResult : WeixinResult + { + public string UserId { get; set; } + public string DeviceId { get; set; } + public string OpenId { get; set; } + public string user_ticket { get; set; } + public string expires_in { get; set; } + + } + + public class WeixinUserResult2 + { + public string openid { get; set; } + public string sex { get; set; } + public string nickname { get; set; } + public string province { get; set; } + public string city { get; set; } + public string country { get; set; } + public string unionid { get; set; } + public string headimgurl { get; set; } + public int errcode { get; set; } + public string errmsg { get; set; } + } + + public class WeixinPayOddResult + { + public string error { get; set; } + public string timeStamp { get; set; } + public string nonceStr { get; set; } + public string package { get; set; } + public string paySign { get; set; } + } + + +} diff --git a/基础类库/HuizhongLibrary/app.config b/基础类库/HuizhongLibrary/app.config new file mode 100644 index 0000000..5fac541 --- /dev/null +++ b/基础类库/HuizhongLibrary/app.config @@ -0,0 +1,15 @@ + + + + +
+ + + + + + http://47.114.82.162:7000/UpdateService.asmx + + + + \ No newline at end of file diff --git a/基础类库/HuizhongLibrary/packages.config b/基础类库/HuizhongLibrary/packages.config new file mode 100644 index 0000000..b232e15 --- /dev/null +++ b/基础类库/HuizhongLibrary/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file