C#点击load在指定位置创建TXT文件,并把读取的内容生成到TXT文件(已实现读取数据库内容)

代码如下,求帮忙
namespace LDD__Generator
{
public partial class LDD : Form
{
public LDD()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
GetData();

}

private void GetData()
{
    try
    {
        DataTable dtMAT_NR = SQLUtility.Select("Select MAT_NR From ADE_LOS Where LOS_NR = '" + txtLOS_NR.Text.Trim() + "'", null);

        DataTable dtPANELID = SQLUtility.Select("Select PANELID From FCBDB.dbo.PANELTAB Where LOSID ='" + txtLOS_NR.Text.Trim() + "'", null);

    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        return;
    }
}

private void txtLOS_NR_KeyPress(object sender, KeyPressEventArgs e)
{
    GetData();
}

}
图片说明
图片说明
图片说明
这个是需要的结果图
图片说明
求指教怎么写

3个回答

         private void GetData()
        {
            try
            {
                DataTable dtMAT_NR = SQLUtility.Select("Select MAT_NR From ADE_LOS Where LOS_NR = '" + txtLOS_NR.Text.Trim() + "'", null);

                DataTable dtPANELID = SQLUtility.Select("Select PANELID From FCBDB.dbo.PANELTAB Where LOSID ='" + txtLOS_NR.Text.Trim() + "'", null);

                //遍历2个表格组合好字符串调用IO写入记事本不就好了
                string s="";
                foreach (DataRow dr in dtMAT_NR) s += "MAT_NR=" + dr[0].ToString() + "\r\n";
                foreach (DataRow dr in dtPANELID) s += "PAN=" + dr[0].ToString() + "\r\n";
                //记得修改第一个参数为你需要制定的位置
                System.IO.File.WriteAllText(@"c:\xxx.txt",s,System.Text.Encoding.UTF8);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
        }
showbo
支付宝加好友偷能量挖 回复浅诺回忆: good。。忘记遍历的是Rows了,嘿嘿。。。
大约 4 年之前 回复
zjamal
浅诺回忆 还有一些小问题需要改一下不过已经解决了谢谢你,大神! 一些细节修改foreach (DataRow dr in dtMAT_NR.Rows)
大约 4 年之前 回复
zjamal
浅诺回忆 还有一些小问题需要改一下不过已经解决了谢谢你,大神! 一些细节修改foreach (DataRow dr in dtMAT_NR.Rows)
大约 4 年之前 回复
zjamal
浅诺回忆 string s = "";
大约 4 年之前 回复
zjamal
浅诺回忆 string s = "";
大约 4 年之前 回复
zjamal
浅诺回忆 string s = "";
大约 4 年之前 回复
zjamal
浅诺回忆 string s = "";
大约 4 年之前 回复
caozhy
每个人都有一个梦才不会孤单的说话就有天堂 赞一个
大约 4 年之前 回复

就是两个操作,说白了就是一个文件操作问题。File之类的,你看下

private void GetData()
{
try
{
DataTable dtMAT_NR = SQLUtility.Select("Select MAT_NR From ADE_LOS Where LOS_NR = '" + txtLOS_NR.Text.Trim() + "'", null);

            DataTable dtPANELID = SQLUtility.Select("Select PANELID From FCBDB.dbo.PANELTAB Where LOSID ='" + txtLOS_NR.Text.Trim() + "'", null);

            string s = "";
            foreach (DataRow dr in dtMAT_NR.Rows)
            {
                s += "MAT_NR=" + dr[0].ToString() + "\r\n";
            }
            foreach (DataRow dr in dtPANELID.Rows)
            {
                s += "PAN=" + dr[0].ToString() + "\r\n";
            }
            System.IO.File.WriteAllText(@"D:\A.txt", s, System.Text.Encoding.UTF8);

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            return;
        }
    }
            根据大神答案进行一些细节修改已经能完成运行,留给需要的人看看
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
C#点击load读取数据库数据现需要同时在指定位置创建TXT文件,并把读取的内容生成到TXT文件内部
详细如下 ![图片说明](https://img-ask.csdn.net/upload/201602/18/1455776540_450263.jpg) ![图片说明](https://img-ask.csdn.net/upload/201602/18/1455776557_941529.png) ![图片说明](https://img-ask.csdn.net/upload/201602/18/1455776568_369505.png) 这是获取的数据把第一个的B39000-T4061-P810-S09中的P8改成BC,并在前面添加一些东西这是txt结果图。 ![图片说明](https://img-ask.csdn.net/upload/201602/18/1455776578_723172.png) 这是部分代码 namespace LDD__Generator { public partial class LDD : Form { public LDD() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { GetData(); } private void GetData() { try { DataTable dtMAT_NR = SQLUtility.Select("Select MAT_NR From ADE_LOS Where LOS_NR = '" + txtLOS_NR.Text.Trim() + "'", null); DataTable dtPANELID = SQLUtility.Select("Select PANELID From FCBDB.dbo.PANELTAB Where LOSID ='" + txtLOS_NR.Text.Trim() + "'", null); } catch (Exception ex) { MessageBox.Show(ex.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } private void txtLOS_NR_KeyPress(object sender, KeyPressEventArgs e) { GetData(); } } }
C#读取xml文件 获取路径问题。
string path = @"record\test01.txt"; XmlDocument xmldocument = new XmlDocument(); xmldocument.Load(path); 对于固定路径的读取,可以按照上面的代码来, 如果txt文档的名字是动态的, txt文档的名字是 str+".txt",str是随着条件变化的,这时候这个路径该怎么写?
C#写串口通信程序接收数据没有反应是怎么回事啊??
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO.Ports; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ChuanKou2 { public partial class Form1 : Form { SerialPort sp = null; //声明串口类 bool isOpen = false; //打开串口标志 bool isSetProperty = false; //属性设置标志 bool isHex = false; //十六进制显示标志位 public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { this.MaximumSize = this.Size; this.MinimumSize = this.Size; this.MaximizeBox = false; for (int i=0;i<10;i++) { cbxCOMPort.Items.Add("COM" + (i + 1).ToString()); } } private void btnCheckCOM_Click(object sender, EventArgs e) //检测有哪串口 { bool comExistence = false; //是否有可用的串口 cbxCOMPort.Items.Clear(); //清除当前串口号中的所有串口名称 for(int i=0;i<10;i++) { try { SerialPort sp = new SerialPort("COM" + (i + 1).ToString()); sp.Open(); sp.Close(); cbxCOMPort.Items.Add("COM" + (i + 1).ToString()); comExistence = true; } catch (Exception) { continue; } } if (comExistence) { cbxCOMPort.SelectedIndex = 0;//使ListBox显示第一个添加的索引 } else { MessageBox.Show("没有找到可用串口!","错误提示"); } } private bool CheckPortSetting() //串口是否设置 { if (cbxCOMPort.Text.Trim() == "") return false; if (cbxBaudRate.Text.Trim() == "") return false; if (cbxDataBits.Text.Trim() == "") return false; if (cbxParitv.Text.Trim() == "") return false; if (cbxStopBits.Text.Trim() == "") return false; return true; } private bool CheckSendData() { if (tbxSendData.Text.Trim() == "") return false; return true; } private void SetPortProPerty() //设置串口属性 { sp = new SerialPort(); sp.PortName = cbxCOMPort.Text.Trim(); //串口名 sp.BaudRate = Convert.ToInt32(cbxBaudRate.Text.Trim());//波特率 float f = Convert.ToSingle(cbxStopBits.Text.Trim());//停止位 if (f == 0) { sp.StopBits = StopBits.None; } else if (f == 1.5) { sp.StopBits = StopBits.OnePointFive; } else if (f == 1) { sp.StopBits = StopBits.One; } else if (f == 2) { sp.StopBits = StopBits.Two; } else { sp.StopBits = StopBits.One; } sp.DataBits = Convert.ToInt16(cbxDataBits.Text.Trim());//数据位 string s = cbxParitv.Text.Trim(); //校验位 if (s.CompareTo("无") == 0) { sp.Parity = Parity.None; } else if (s.CompareTo("奇校验") == 0) { sp.Parity = Parity.Odd; } else if (s.CompareTo("偶校验") == 0) { sp.Parity = Parity.Even; } else { sp.Parity = Parity.None; } sp.ReadTimeout = -1; //设置超时读取时间 sp.RtsEnable = true; //定义DataReceived事件,当串口收到数据后触发事件 sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived); if (rbnHex.Checked) { isHex = true; } else { isHex = false; } } private void sp_DataReceived(object sender,SerialDataReceivedEventArgs e) { System.Threading.Thread.Sleep(100); //延时100ms等待接收数据 //this.Invoke 跨线程访问ui的方法 this.Invoke((EventHandler)(delegate { if (isHex == false) { tbxRecvData.Text += sp.ReadLine(); } else { Byte[] ReceivedData = new Byte[sp.BytesToRead]; sp.Read(ReceivedData, 0, ReceivedData.Length); String RecvDataText = null; for(int i = 0; i < ReceivedData.Length - 1; i++) { RecvDataText += ("0x" + ReceivedData[i].ToString("X2") + ""); } tbxRecvData.Text += RecvDataText; } sp.DiscardInBuffer(); //丢弃接收缓冲区数据 })); } private void btnSend_Click(object sender, EventArgs e) //发送数据 { if (isOpen) { try { sp.WriteLine(tbxSendData.Text); } catch(Exception) { MessageBox.Show("发送数据时发生错误!", "错误提示"); return; } } else { MessageBox.Show("串口未打开", "错误提示"); return; } if (!CheckSendData()) { MessageBox.Show("请输入要发送的数据!", "错误提示"); return; } } private void btnOpenCom_Click(object sender, EventArgs e) { if (isOpen == false) { if (!CheckPortSetting()) //检测串口设置 { MessageBox.Show("串口未设置!", "错误提示"); return; } if (!isSetProperty) //串口未设置则设置串口 { SetPortProPerty(); isSetProperty = true; } try { sp.Open(); isOpen = true; btnOpenCom.Text = "关闭串口"; //串口打开后则相关串口设置按钮便不可再用 cbxCOMPort.Enabled = false; cbxBaudRate.Enabled = false; cbxDataBits.Enabled = false; cbxParitv.Enabled = false; cbxStopBits.Enabled = false; rbnChar.Enabled = false; rbnHex.Enabled = false; } catch (Exception) { //打开串口失败后,相应标志位取消 isSetProperty = false; isOpen = false; MessageBox.Show("串口无效或已被占用!", "错误提示"); } } else { try //关闭串口 { sp.Close(); isOpen = false; btnOpenCom.Text = "打开串口"; //关闭串口后,串口设置选项可以继续使用 cbxCOMPort.Enabled = true; cbxBaudRate.Enabled = true; cbxDataBits.Enabled = true; cbxParitv.Enabled = true; cbxStopBits.Enabled = true; rbnChar.Enabled = true; rbnHex.Enabled = true; } catch (Exception) { MessageBox.Show("关闭串口时发生错误!", "错误提示"); } } } private void btnCleanData_Click(object sender, EventArgs e) { tbxRecvData.Text = ""; tbxSendData.Text = ""; } } }
C#stream文件文本读取的问题
我这个是书上的例子,但这例子应该是印错了,在ButtonAdd的事件那,TextNewItem都没有申明是啥,我新手,想问问,TextNewItem应该怎么申明才能让这个读取文件内容到程序里的例子顺利运行 ``` 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; using System.IO; namespace steamwriter { public partial class Form1 : Form { public Form1() { InitializeComponent(); } void FillItems() { ComboItems.Items.Clear(); StreamReader sr = new StreamReader("Items.txt", Encoding.Default); try { while (!sr.EndOfStream) { string NewItem = sr.ReadLine(); if (NewItem != "") { ComboItems.Items.Add(NewItem); } } } finally { sr.Close(); } ComboItems.Text = ComboItems.Items[0].ToString(); } private void Form1_Load(object sender, EventArgs e) { this.Text = "文本文件的读写"; FillItems(); } private void ButtonAdd_Click(object sender, EventArgs e) { StreamWriter sw = new StreamWriter("item.txt ", true, Encoding.UTF8); if (TextNewItem.text != "") { sw.WriteLine(TextNewItem.text); } else { MessageBox.Show("不能添加空选项", "操作失败", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } sw.Close(); FillItems(); MessageBox.Show("选项添加成功!", "操作完成", MessageBoxButtons.OK, MessageBoxIcon.Information); } } } ```
关于C#菜单程序的问题
这里是一个带历史信息的菜单的程序,程序里面获取索引值为什么要 -2 ? 另外,能简约的介绍下DropDownItems的作用么? 小弟不才,望大神指导 private void Form1_Load(object sender, EventArgs e) { if (File.Exists("Menu.ini"))//判断文件是否存在 { StreamReader sr = new StreamReader("Menu.ini");//创建文件流 int i = this.文件ToolStripMenuItem.DropDownItems.Count - 2;//获取索引项 while (sr.Peek() >= 0)//读取文件流 { //将读取的信息创建菜单项 ToolStripMenuItem menuitem = new ToolStripMenuItem(sr.ReadLine()); //将菜单项添加到指定位置 this.文件ToolStripMenuItem.DropDownItems.Insert(i, menuitem); i++; } sr.Close();//关闭流 } } private void 打开ToolStripMenuItem_Click(object sender, EventArgs e) { openFileDialog1.FileName = ""; this.openFileDialog1.ShowDialog();//打开对话框 StreamWriter s = new StreamWriter("Menu.ini", true);//创建流 s.WriteLine(openFileDialog1.FileName);//流写入文件 s.Flush(); s.Close(); }
关于c#wimform中使用load data local infile报错
在wimform中使用load data local infile 导入sql文件到表里,此时执行,报Fatal error encountered attempting to read the resultset,查询控制台说未能找到文件“D:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\xxx.sql",但是我已经指定了local ,完整语句是 load data local infile'D:\\xxx.sql' into table T_NAME.这句话在mysq运行时l _可以读的到D盘下的xxx.sql文件,但是在程序里就无法读取,只会查找那个vs根目录,一旦把xxx.sql放到“D:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\xxx.sql"就能够读取,这是怎么回事,怎么指定这个目录问题。
C#通过SerialPort读取电子天平数据时第一次操作无法获取数据,必须进行第二次操作才能获取当前数据?
C#通过SerialPort读取电子天平数据时,连接串口成功后,通过发送命令方式第一次操作无法获取数据,无任何数据返回,必须进行第二次操作才能获取当前数据。并且更新电子天平负载后,单击读取数据按钮,通过串口获得的数据为上一次读数,必须再单击一次才能获取更新的数据。一直卡到这里,不知道怎么解决,求大神帮忙看看!暂无积分,抱歉! 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; using System.IO.Ports; using System.Text.RegularExpressions; namespace 读天平 { public partial class Form1 : Form { SerialPort mySerialPort = null; string receiveing; string read_data; int count_read; int row_no; int column_no; DataGridView dgv; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { mySerialPort = new SerialPort("COM5", 9600, Parity.None, 8, StopBits.One); mySerialPort.Handshake = Handshake.None; // 四种都可以使用 mySerialPort.Open(); mySerialPort.DataReceived += new SerialDataReceivedEventHandler(mySerialPort_DataReceivedHandler); mySerialPort.DtrEnable = true; // 加上此属性接收事件可被触发 mySerialPort.ReceivedBytesThreshold = 1; if (mySerialPort.IsOpen == true) { MessageBox.Show("串口打开成功", "提示", MessageBoxButtons.OK); } else { MessageBox.Show("串口打开失败", "提示", MessageBoxButtons.OK); } } private void mySerialPort_DataReceivedHandler(object sender, SerialDataReceivedEventArgs e) // SerialPort.DataReceived事件运行比较特殊,其运行在辅线程,不能与主线程中的显示数据控件直接进行数据传输,必须用间接的方式实现 {//接收数据 SerialPort sp = (SerialPort)sender; read_data = sp.ReadExisting(); this.Invoke((EventHandler)(delegate { receiveing = read_data.Trim().TrimStart('+').TrimStart('-').TrimEnd('g').Trim(); })); mySerialPort.DiscardInBuffer(); // 清除接收缓存 } private void dataGridView1_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e) { byte[] send = { 0x1B, 0x70 }; // 十六进制ASCII码 mySerialPort.Write(send, 0, send.Length); row_no = e.RowIndex; column_no = e.ColumnIndex; dgv = dataGridView1; dgv.Rows[row_no].Cells[column_no].Value = receiveing; } private void dataGridView2_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e) { byte[] send = { 0x1B, 0x70 }; // 十六进制ASCII码 mySerialPort.Write(send, 0, send.Length); row_no = e.RowIndex; column_no = e.ColumnIndex; dgv = dataGridView2; dgv.Rows[row_no].Cells[column_no].Value = receiveing; } } }
openpyxl.load__workbook(filename)报错ValueError: Max value is 52
openpyxl.load__workbook(filename)报错ValueError: Max value is 52,但是只有个别表格会出现报错,什么原因? ``` import openpyxl filename="测试2.xlsx"#读取excel workbook=openpyxl.load_workbook(filename,data_only=True) worksheet=workbook.get_sheet_by_name("Sheet1") ``` 报错信息如下: ``` File "C:\Users\mayn\AppData\Local\Programs\Python\Python36\lib\site-packages\openpyxl\reader\excel.py", line 314, in load_workbook reader.read() File "C:\Users\mayn\AppData\Local\Programs\Python\Python36\lib\site-packages\openpyxl\reader\excel.py", line 279, in read self.read_worksheets() File "C:\Users\mayn\AppData\Local\Programs\Python\Python36\lib\site-packages\openpyxl\reader\excel.py", line 254, in read_worksheets charts, images = find_images(self.archive, rel.target) File "C:\Users\mayn\AppData\Local\Programs\Python\Python36\lib\site-packages\openpyxl\reader\drawings.py", line 27, in find_images drawing = SpreadsheetDrawing.from_tree(tree) File "C:\Users\mayn\AppData\Local\Programs\Python\Python36\lib\site-packages\openpyxl\descriptors\serialisable.py", line 87, in from_tree obj = desc.expected_type.from_tree(el) File "C:\Users\mayn\AppData\Local\Programs\Python\Python36\lib\site-packages\openpyxl\descriptors\serialisable.py", line 87, in from_tree obj = desc.expected_type.from_tree(el) File "C:\Users\mayn\AppData\Local\Programs\Python\Python36\lib\site-packages\openpyxl\descriptors\serialisable.py", line 87, in from_tree obj = desc.expected_type.from_tree(el) [Previous line repeated 3 more times] File "C:\Users\mayn\AppData\Local\Programs\Python\Python36\lib\site-packages\openpyxl\descriptors\serialisable.py", line 103, in from_tree return cls(**attrib) File "C:\Users\mayn\AppData\Local\Programs\Python\Python36\lib\site-packages\openpyxl\drawing\text.py", line 115, in __init__ self.pitchFamily = pitchFamily File "C:\Users\mayn\AppData\Local\Programs\Python\Python36\lib\site-packages\openpyxl\descriptors\base.py", line 108, in __set__ super(Min, self).__set__(instance, value) File "C:\Users\mayn\AppData\Local\Programs\Python\Python36\lib\site-packages\openpyxl\descriptors\base.py", line 87, in __set__ raise ValueError('Max value is {0}'.format(self.max)) ValueError: Max value is 52 ```
c# APP.config的读取保存配置问题
public Form1() { InitializeComponent(); config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); } public void AddAppSetting(string key, string value) { config.AppSettings.Settings.Add(key, value); config.Save(); } /// <summary> /// //修改键值 /// </summary> /// <param name="key"></param> /// <param name="value"></param> public void SaveAppSetting(string key, string value) { config.AppSettings.Settings.Remove(key); config.AppSettings.Settings.Add(key, value); config.Save(); } /// <summary> /// //获得键值 /// </summary> /// <param name="key"></param> /// <returns></returns> public void GetAppSetting() { //return config.AppSettings.Settings[key].Value; String str = ConfigurationManager.AppSettings["Text1"]; Console.WriteLine(str); textBox1.Text = str; } /// <summary> /// //移除键值 /// </summary> /// <param name="key"></param> public void DelAppSetting(string key) { config.AppSettings.Settings.Remove(key); config.Save(); } public void initdata() { string nb1 = "Text1"; } public ArrayList GetXmlElements(string strElem) { ArrayList list = new ArrayList(); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config"); XmlNodeList listNode = xmlDoc.SelectNodes(strElem); foreach (XmlElement el in listNode) { list.Add(el.InnerText); } return list; } private void Form1_Load(object sender, EventArgs e) { } private void button2_Click(object sender, EventArgs e) { AddAppSetting("waeawe","1"); } private void button1_Click(object sender, EventArgs e) { GetAppSetting(); } private void button3_Click(object sender, EventArgs e) { SaveAppSetting("Text1", "46546"); } 代码中button1读取配置。button修改配置,第一次点击Button1的时候可以正常读取配置,点击button2以后修改值。再点button1不能读取修改后的值,只能读取修改之前的值。程序关闭以后才能读取为什么?
C# 引用C++ dll的奇怪问题,相当奇怪
项目是做视频监控的,外购的高清摄像头,并提供了C++的dll,项目使用C#做管理平台。 其中dll中有个函数 **VCAInitSdk** 做初始化用的,即每次打开管理程序,都要调用这个初始化函数。 起初,在WinForm中调用该函数,都可以正常的执行。 当这个函数在 **windows service 和控制台应用程序** 中运行后报错:【尝试读取或写入受保护的内存。这通常指示其他内存已损坏】 **也就是说,这个函数在winform中可以使用,但是在windows service和控制台应用中却使用不了。** 在winform中,该函数式在Load事件中运行,而服务,是在OnStart中运行,控制台则是在Main函数中运行。 是否是因为主线程和子线程的原因的。我在winform Load中, **新开一个线程** 来运行这个函数,发现也报错,其错误跟windows service和控制台的错误是一样的,我就想,是不是其他2个都是在子线程上运行的这个函数呢。如果是这样,那么我在windows service中该怎么做,如果不是这样,还请赐教!
C#的WinForms的简单查询
是实现从数据库查询数据的。。 请看代码 public partial class Form2 : Form { private DataSet ds; //声明Dataset private SqlDataAdapter bs; //声明读取年级信息的数据适配器 string saih = "Data Source=.;Initial Catalog=ri;Integrated Security=True"; public Form2() { InitializeComponent(); } private void Form2_Load(object sender, EventArgs e) { //调用方法 searchstudent(); } public void searchstudent() { //创建数据库链接 SqlConnection conn = new SqlConnection(saih); try { //查询年级的SQL语句 StringBuilder sb = new StringBuilder(); sb.Append("select id,name,sex,birthday"); sb.Append(" from grade"); if (Convert.ToInt32(this.cbo.SelectedValue) != -1) { sb.AppendFormat(" where id={0}",Convert.ToInt32(this.cbo.SelectedValue)); } sb.Append(" order by [id]"); bs = new SqlDataAdapter(); //填充Dataset SqlCommand comm = new SqlCommand(sb.ToString(),conn); bs.SelectCommand = comm; //填充钱,清空原有的数据 if (ds.Tables["grade"] != null) { ds.Tables["grade"].Clear(); } bs.Fill(ds, "grade"); } catch (Exception ex) { MessageBox.Show(ex.Message,"异常提示",MessageBoxButtons.OK,MessageBoxIcon.Warning); } finally { conn.Close(); } } private void btnselect_Click(object sender, EventArgs e) { searchstudent(); } } } 结果显示:未将对象引用设置到对象的实例 我们现在学的还是些简单的基础东西。。这些代码我是按照书本上敲的。过程没有报错什么的。但是运行就是没效果。请各位帮帮忙
c#编写的串口助手打开串口32单片机立刻黑屏,急求
using Microsoft.Win32; using System; using System.IO.Ports; using System.Windows.Forms; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; namespace WindowsFormsApp { public partial class Form1 : Form { //SerialPort sp = null;//声明一个串口类 bool isOpen = false;//打开串口标志位 bool isSetProperty = false;//属性设置标志位 bool isHex = false;//十六进制显示标志位 public Form1() { InitializeComponent(); System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;//设置该属性为false } //我们在form载入时,扫描识别存在的串口。 private void Form1_Load(object sender, EventArgs e) { this.MaximumSize = this.Size; this.MinimumSize = this.Size; this.MaximizeBox = false; RegistryKey keyCom = Registry.LocalMachine.OpenSubKey("Hardware\\DeviceMap\\SerialComm"); if (keyCom != null) { string[] sSubKeys = keyCom.GetValueNames(); cbxCOMPort.Items.Clear(); foreach (string sName in sSubKeys) { string sValue = (string)keyCom.GetValue(sName); cbxCOMPort.Items.Add(sValue); } if (cbxCOMPort.Items.Count > 0) cbxCOMPort.SelectedIndex = 0; else { cbxCOMPort.Text = ""; MessageBox.Show("没有找到可用串口!", "错误提示"); } } cbxBaudRate.SelectedIndex = 4; cbxStopBits.SelectedIndex = 1; cbxDataBits.SelectedIndex = 0; cbxParity.SelectedIndex = 0; rbnChar.Checked = true; } private void btnCheckCOM_Click(object sender, EventArgs e)//检测哪些串口可用 { RegistryKey keyCom = Registry.LocalMachine.OpenSubKey("Hardware\\DeviceMap\\SerialComm"); if (keyCom != null) { string[] sSubKeys = keyCom.GetValueNames(); cbxCOMPort.Items.Clear(); foreach (string sName in sSubKeys) { string sValue = (string)keyCom.GetValue(sName); cbxCOMPort.Items.Add(sValue); } if (cbxCOMPort.Items.Count > 0) cbxCOMPort.SelectedIndex = 0; else { cbxCOMPort.Text =""; MessageBox.Show("没有找到可用串口!", "错误提示"); } } } private bool CheckPortSetting()//检查串口是否设置 { if (cbxCOMPort.Text.Trim() == "") return false; if (cbxBaudRate.Text.Trim() == "") return false; if (cbxDataBits.Text.Trim() == "") return false; if (cbxParity.Text.Trim() == "") return false; if (cbxStopBits.Text.Trim() == "") return false; return true; } private bool CheckSendData() { if (tbxSendData.Text.Trim() == "") return false; return true; } private void SetPortProperty()//设置串口的属性 { serialPort.PortName = cbxCOMPort.Text.Trim();//设置串口名 serialPort.BaudRate = Convert.ToInt32(cbxBaudRate.Text.Trim());//设置串口的波特率 float f = Convert.ToSingle(cbxStopBits.Text.Trim());//设置停止位 if (f == 0) { serialPort.StopBits = StopBits.None; } else if (f == 1.5) { serialPort.StopBits = StopBits.OnePointFive; } else if (f == 1) { serialPort.StopBits = StopBits.One; } else if (f == 2) { serialPort.StopBits = StopBits.Two; } else { serialPort.StopBits = StopBits.One; } serialPort.DataBits = Convert.ToInt16(cbxDataBits.Text.Trim());//设置数据位 string s = cbxParity.Text.Trim(); //设置奇偶校验位 if (s.CompareTo("无") == 0) { serialPort.Parity = Parity.None; } else if (s.CompareTo("奇校验") == 0) { serialPort.Parity = Parity.Odd; } else if (s.CompareTo("偶校验") == 0) { serialPort.Parity = Parity.Even; } else { serialPort.Parity = Parity.None; } serialPort.ReadTimeout = -1;//设置超时读取时间 serialPort.RtsEnable = true; //定义DataReceived 事件,当串口收到数据后触发事件 serialPort.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived); if (rbnHex.Checked) { isHex = true; } else { isHex = false; } } private void btnOpenCom_Click(object sender, EventArgs e) { if (!isOpen) { if (!CheckPortSetting())//检测串口设置 { MessageBox.Show("串口未设置!", "错误提示"); return; } if (!isSetProperty)//串口未设置则设置串口 { SetPortProperty(); isSetProperty = true; } try { serialPort.Open(); //打开串口 btnOpenCom.Text = "关闭串口"; cbxCOMPort.Enabled = false;//关闭使能 cbxBaudRate.Enabled = false; cbxStopBits.Enabled = false; cbxParity.Enabled = false; cbxDataBits.Enabled = false; rbnChar.Enabled = false; rbnHex.Enabled = false; isOpen = true; serialPort.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);//串口接收处理函数 } catch { MessageBox.Show("串口打开失败!"); } } else { try { serialPort.Close(); //关闭串口 btnOpenCom.Text = "打开串口"; cbxCOMPort.Enabled = true;//打开使能 cbxBaudRate.Enabled = true; isOpen = false; } catch { MessageBox.Show("串口关闭失败!"); } } } //private void sp_DataReceived(object sender, SerialDataReceivedEventArgs e) //{ // string str = serialPort.ReadExisting();//字符串方式读 // tbxRecvData.Text = "";//先清除上一次的数据 // tbxRecvData.Text += str; //} private void sp_DataReceived(object sender, SerialDataReceivedEventArgs e) { System.Threading.Thread.Sleep(100);//延时 100ms 等待接收完数据 //this.Invoke 就是跨线程访问 ui 的方法,也是本文的范例 this.Invoke((EventHandler)(delegate { if (isHex == false) { tbxRecvData.Text += serialPort.ReadLine(); } else { Byte[] ReceivedData = new Byte[serialPort.BytesToRead]; //创建接收字节数组 serialPort.Read(ReceivedData, 0, ReceivedData.Length); //读取所接收到的数据 String RecvDataText = null; for (int i = 0; i < ReceivedData.Length - 1; i++) { RecvDataText += ("0x" + ReceivedData[i].ToString("X2") + " "); } tbxRecvData.Text += RecvDataText; } serialPort.DiscardInBuffer();//丢弃接收缓冲区数据 })); } private void btnSend_Click(object sender, EventArgs e) { //发送数据 if (serialPort.IsOpen) {//如果串口开启 if (tbxSendData.Text.Trim() != "")//如果框内不为空则 { serialPort.Write(tbxSendData.Text.Trim());//写数据 } else { MessageBox.Show("发送框没有数据"); } } else { MessageBox.Show("串口未打开"); } } private void btnCleanData_Click(object sender, EventArgs e) { tbxRecvData.Text = ""; tbxSendData.Text = ""; } } } 打开串口没有提示失败,但是单片机就不运行了。
C# 为什么ReportViewer做的报表个别电脑出现不显示的情况?
在阜阳现场调试的时候,有一个电脑出现的打开报表时显示找不到方法“Void Microsoft.Reporting.PreviewItemContext.setbpath(System string,System string,Microsoft.Reporting.DefinitionSoure)”。 同一个安装包,只有一个电脑出现这个问题,怀疑是那台电脑缺少什么动态链接库,尴尬的是我不知道缺的什么。 对方电脑系统是Win7 代码编译器VS2005, 代码不是我敲的,前前前辈写的,我维护一下。 ``` using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; using System.Data.SqlClient; namespace ConcreteApp.report { public partial class MRSGMXBB : Form { private System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(); //-----配置数据库专用变量 private string ServerName = ""; private string DBName = ""; private string SqlName = ""; private string SqlPWD = ""; private string UID1; private string sqlstr = "select QDDH 强度代号 from t_QDDH "; public MRSGMXBB() { InitializeComponent(); } private void MRSGMXBB_Load(object sender, EventArgs e) { // TODO: 这行代码将数据加载到表“cDB_TEMPDataSet.t_shengchanrenwu”中。您可以根据需要移动或移除它。 this.t_shengchanrenwuTableAdapter1.Fill(this.cDB_TEMPDataSet.t_shengchanrenwu); // TODO: 这行代码将数据加载到表“cDBDataSetIP.t_shengchanrenwu”中。您可以根据需要移动或移除它。 this.t_shengchanrenwuTableAdapter.Fill(this.cDBDataSetIP.t_shengchanrenwu); this.reportViewer1.RefreshReport(); this.date1ToolStripTextBox.Text = DateTime.Now.ToShortDateString(); this.date2ToolStripTextBox.Text = DateTime.Now.AddDays(1).ToShortDateString(); string[] tmpcodeA; UID1 = ""; try { //读取配置文件 using (StreamReader sr = new StreamReader(Application.StartupPath + "/config.ini")) { try { tmpcodeA = sr.ReadLine().Split('|'); this.ServerName = tmpcodeA[0].ToString(); this.DBName = tmpcodeA[1].ToString(); this.SqlName = tmpcodeA[2].ToString(); this.SqlPWD = tmpcodeA[3].ToString(); } catch (Exception ex) { MessageBox.Show("读取配置文件失败!请检查程序目录下的config.ini文件。" + ex.ToString(), "提示"); } } //验证登陆 con.ConnectionString = ("SERVER=" + ServerName + ";UID=" + SqlName + ";PWD=" + SqlPWD + ";DATABASE=" + DBName + ""); con.Open(); SqlDataAdapter da = new SqlDataAdapter(sqlstr, con); DataSet ds = new DataSet(); da.Fill(ds); con.Close(); for (int i = 0; i < ds.Tables[0].Rows.Count; i++) CBpz.Items.Add(ds.Tables[0].Rows[i][0].ToString()); } catch (Exception ex) { MessageBox.Show("数据库连接失败!请重新配置" + ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } } private void fillBy1ToolStripButton_Click(object sender, EventArgs e) { if (CBpz.Text == "") { try { this.t_shengchanrenwuTableAdapter.FillBy(this.cDBDataSetIP.t_shengchanrenwu, date1ToolStripTextBox.Text, date2ToolStripTextBox.Text); this.reportViewer1.RefreshReport(); } catch (System.Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } } else { try { this.t_shengchanrenwuTableAdapter.FillBy1(this.cDBDataSetIP.t_shengchanrenwu, date1ToolStripTextBox.Text, date2ToolStripTextBox.Text,CBpz.Text); this.reportViewer1.RefreshReport(); } catch (System.Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } } } } } ```
基于springmvc+mybatis的登录表单提交后404
前端填写正确的用户名和密码后,提交登录,浏览器显示404,前端提交的地址是/userlogin,后端对接的/user/userlogin也是对的,浏览器f12里显示请求的确成功传给了后端,但是不知道为什么404。用的是tomcat8.5,java版本1.8,phpstudy最新版,mysql5.7.26。 ## 这是所用到的包: ![图片说明](https://img-ask.csdn.net/upload/202002/01/1580567617_880785.jpg) ## 这是目录结构: ![图片说明](https://img-ask.csdn.net/upload/202002/01/1580567511_223692.jpg) ## 这是web.xml: ```xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>springmvc_test</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- 配置spring监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 加载spring配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:config/context-config.xml</param-value> </context-param> <!-- 配置前端控制器 --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <!-- DispatcherServlet在初始化方法里面会读取该初始化参数的值来获得 spring配置文件的位置 ,然后启动spring容器。 --> <param-name>contextConfigLocation</param-name> <param-value>classpath*:config/springmvc-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 配置字符编码 --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> ``` ## 这是context-config.xml: ```xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 扫描service包下的注解 --> <context:component-scan base-package="com.test.service"></context:component-scan> <!-- 配置数据库 --> <!-- 加载配置文件 --> <!-- <context:property-placeholder location="classpath:jdbc.properties"/> --> <bean id="dateSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driver" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql://localhost:3306/Eday_Test"></property> <property name="username" value="root"></property> <property name="password" value="123456"></property> </bean> <!-- 配置Sqlsessionfactory并将数据源注入 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 引入数据源 --> <property name="dateSource" ref="dateSource"></property> <!-- 载入mybatis配置文件 --> <property name="configLocation" value="classpath:mybatis-config.xml"></property> <!-- 载入配置mapper映射的xml --> <property name="mapperLocations" value="classpath:com/test/mapper/*.xml"></property> </bean> <!-- 配置扫描mapper接口 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackge" value="com.test.mapper"></property> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dateSource" ref="dateSource"></property> </bean> <tx:annotation-driven transaction-manager="transactionManager"/> </beans> ``` ## 这是mybatis-config.xml: ```xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <typeAliases> <!-- 配置别名 --> <typeAlias alias="User" type="com.test.pojo.User"/> </typeAliases> </configuration> ``` ## 这是springmvc-config.xml: ```xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 扫描controller包下的注解 --> <context:component-scan base-package="com.test.controller"></context:component-scan> <!-- 开启注解 --> <mvc:annotation-driven></mvc:annotation-driven> <!-- 静态资源访问 --> <mvc:default-servlet-handler/> <!-- 视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 配置试图解析的默认路径,即配置页面的根路径 --> <property name="prefix" value="/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans> ``` ## 这是UserController.java: ```java package com.test.controller; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.test.pojo.User; import com.test.service.UserService; //声明控制器 @Controller //设置bean的scope属性为多例(prototype) @Scope("prototype") //设置请求映射,当客户端请求/user时,转到该控制器处理 @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @RequestMapping(value="/userlogin") public ModelAndView login(String user_Name,String user_pwd,ModelAndView mv,HttpSession session){ //调用userService中的login方法处理user实体类对象 User user = userService.login(user_Name,user_pwd); //登录的逻辑判断,判断条件是返回结果不为空 if(user!=null){ //登陆成功,将user对象设置到HttpSession作用范围域中,相当于服务端的cookie,有效时间默认30分钟 //在程序运行期间,在任意页面都可以提取它的值。 session.setAttribute("user",user); //转发到main请求 //登录成功,跳转页面 mv.setViewName("login/login-success"); }else{ //登录失败,向前端传递失败信息 mv.addObject("message","用户名或密码错误,请重新输入!"); //登录失败,跳转到登录页面 mv.setViewName("login"); } return mv; } //跳转到用户注册界面 @RequestMapping(value="/userregister"/*,method=RequestMethod.POST*/) public String register(User user){ String user_Name = user.getUser_Name(); //如果数据库中没有该用户,可以注册,否则跳转页面 if(userService.findByUserName(user_Name)==null){ //添加用户 userService.register(user); //注册成功,跳转到主页面 return "index"; }else{ //注册失败,跳转到错误页面 return "error"; } } } ``` ## 这是UserMapper.java: ```java package com.test.mapper; import org.apache.ibatis.annotations.Param; import com.test.pojo.User; public interface UserMapper { //根据用户名和密码查找,mybatis中有多个参数时,需要使用@Param注解 User findByUserNameAndPassword(@Param("user_Name")String user_Name,@Param("user_Pwd")String user_Pwd); //增加用户 void addUser(User user); //根据用户名查询 User findByUserName(String user_Name); } ``` ## 这是UserMapper.xml: ```xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.tes.mapper.UserMapper"> <!-- 根据用户名和密码查询 --> <select id="findByUserNameAndPasssword" resultType="User"> select * from user where user_Name=#{user_Name} and user_Pwd=#{user_Pwd} </select> <!-- 增加用户 --> <insert id="addUser" parameterType="User"> insert into user (user_Name,user_Pwd,user_Email,user_NickName,user_Birth,user_Phone,user_InvitationCode) values(#{user_Name},#{user_Pwd},#{user_Email},#{user_NickName},#{user_Birth},#{user_Phone},#{user_InvitationCode}) </insert> <!-- 根据用户名查询 --> <select id="findByUserName" resultType="User"> select * from user where user_Name=#{user_Name} </select> </mapper> ``` ## 这是User.java: ```java package com.test.pojo; import java.sql.Timestamp; public class User { private int user_Id; private String user_Name; private int user_Pwd; private String user_Email; private String user_NickName; private Timestamp user_Time; private String user_Birth; private int user_Fans; private int user_Follow; private int user_Score; private String user_HeadImgAddr; private int user_Phone; private String user_InvitationCode; public int getUser_Id() { return user_Id; } public void setUser_Id(int user_Id) { this.user_Id = user_Id; } public String getUser_Name() { return user_Name; } public void setUser_Name(String user_Name) { this.user_Name = user_Name; } public int getUser_Pwd() { return user_Pwd; } public void setUser_Pwd(int user_Pwd) { this.user_Pwd = user_Pwd; } public String getUser_Email() { return user_Email; } public void setUser_Email(String user_Email) { this.user_Email = user_Email; } public String getUser_NickName() { return user_NickName; } public void setUser_NickName(String user_NickName) { this.user_NickName = user_NickName; } public Timestamp getUser_Time() { return user_Time; } public void setUser_Time(Timestamp user_Time) { this.user_Time = user_Time; } public String getUser_Birth() { return user_Birth; } public void setUser_Birth(String user_Birth) { this.user_Birth = user_Birth; } public int getUser_Fans() { return user_Fans; } public void setUser_Fans(int user_Fans) { this.user_Fans = user_Fans; } public int getUser_Follow() { return user_Follow; } public void setUser_Follow(int user_Follow) { this.user_Follow = user_Follow; } public int getUser_Score() { return user_Score; } public void setUser_Score(int user_Score) { this.user_Score = user_Score; } public String getUser_HeadImgAddr() { return user_HeadImgAddr; } public void setUser_HeadImgAddr(String user_HeadImgAddr) { this.user_HeadImgAddr = user_HeadImgAddr; } public int getUser_Phone() { return user_Phone; } public void setUser_Phone(int user_Phone) { this.user_Phone = user_Phone; } public String getUser_InvitationCode() { return user_InvitationCode; } public void setUser_InvitationCode(String user_InvitationCode) { this.user_InvitationCode = user_InvitationCode; } @Override public String toString() { return "User [user_Id=" + user_Id + ", user_Name=" + user_Name + ", user_Pwd=" + user_Pwd + ", user_Email=" + user_Email + ", user_NickName=" + user_NickName + ", user_Time=" + user_Time + ", user_Birth=" + user_Birth + ", user_Fans=" + user_Fans + ", user_Follow=" + user_Follow + ", user_Score=" + user_Score + ", user_HeadImgAddr=" + user_HeadImgAddr + ", user_Phone=" + user_Phone + ", user_InvitationCode=" + user_InvitationCode + "]"; } } ``` ## 这是UserService.java: ```java package com.test.service; import com.test.pojo.User; public interface UserService { //通过用户名及密码核查用户登录 User login(String user_Name,String user_Pwd); //增加用户 void register(User user); //根据用户名查询 User findByUserName(String user); } ``` ## 这是UserServiceImpl.java: ```java package com.test.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.test.mapper.UserMapper; import com.test.pojo.User; import com.test.service.UserService; @Service @Transactional public class UserServiceImpl implements UserService { //注入UserMapper接口 @Autowired private UserMapper userMapper; //登录,根据用户名和密码进行查询 @Override public User login(String user_Name,String user_Pwd){ return userMapper.findByUserNameAndPassword(user_Name,user_Pwd); } //注册,增加用户 @Override public void register(User user){ userMapper.addUser(user); } //根据用户名查询 @Override public User findByUserName(String user_Name){ return userMapper.findByUserName(user_Name); } } ``` ##这是login.jsp ```jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel="stylesheet" type="text/css" href="../css/login.css" /> <title>登录</title> </head> <body> <!--导航栏--> <nav class="nav"> <ul> <li class="logo"><a href="#">Eday</a></li> <li class="shouye"><a href="../index.jsp" class="neirong">首页</a></li> <li class="fgx">|</li> <li><a href="#" class="neirong">文章列表</a></li> <li class="fgx">|</li> <li><a href="#" class="neirong">留言板</a></li> <li class="fgx">|</li> <li><a href="#" class="neirong">更新日志</a></li> </ul> </nav> <!--登录板块--> <header class="header"> <p class="logintitle"> <b>登录</b> </p> <form action="${pageContext.request.contextPath }/user/userlogin" method="post" class=login-form> <p class= login-username-p> <label for="username" class="login-username-text">用户名:</label> <input type=text name="user_Name" class="login-username-input"> <br><a href="register.jsp" class=login-register>注册</a> </p> <p class="login-psw-p"> <label for="psw" class="login-psw-text">密码:</label> <input type=password name="user_Pwd" class="login-psw-input"> <br><a href="#" class=login-forget>忘记密码</a> </p> <div class=login-button-div> <label for=button></label> <button type=sublim class=login-button>登录</button> </div> </form> </header> </body> </html> ``` ## 这是login-success.jsp: ```jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>登录成功,请等待跳转...</title> <script type="text/javascript"> onload=function(){ setInterval(go, 1000); }; var x=3; //利用了全局变量来执行 function go(){ x--; if(x>0){ document.getElementById("sp").innerHTML=x; //每次设置的x的值都不一样了。 }else{ location.href='../index.jsp'; } } </script> </head> <body> <!--导航栏--> <nav class="nav"> <ul> <li class="logo"><a href="#">Eday</a></li> <li class="shouye"><a href="../index.jsp" class="neirong">首页</a></li> <li class="fgx">|</li> <li><a href="#" class="neirong">文章列表</a></li> <li class="fgx">|</li> <li><a href="#" class="neirong">留言板</a></li> <li class="fgx">|</li> <li><a href="#" class="neirong">更新日志</a></li> </ul> </nav> <header> <div> <p>登录成功!页面将在3秒后自动跳转,请稍等...</p> </div> </header> </body> </html> ``` ## 这是数据库: ![图片说明](https://img-ask.csdn.net/upload/202002/01/1580568589_694404.jpg)
读取文件夹中的所有图片文件
我第一次读取的时候没有问题。在删除图片后再读取图片会读取错误,以下是我的代码各位帮忙看一下。 后台代码 ``` using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.IO; using System.Data; public partial class admin_netshopper_DHweihu_makepage_addhuandeng : System.Web.UI.UserControl { public string SlideFolderPath = myConfig.webimgshijiurl + "/kuaigou/huandeng/"; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { if (!System.IO.Directory.Exists(SlideFolderPath)) { System.IO.Directory.CreateDirectory(SlideFolderPath); } bind(); } } public void bind() { string Images = ""; string[] Dir = System.IO.Directory.GetFiles(SlideFolderPath); foreach (string file in Dir) { System.IO.FileInfo FI = new System.IO.FileInfo(file); if (FI.Extension == ".jpg") { string name = FI.Name.Substring(0, FI.Name.Length - 4);// 获取文件名 string URL = myConfig.webimgurl + "/kuaigou/huandeng/" + FI.Name;// 组装图片路径 Images += URL + "," + name + ","; } } DataTable table = new DataTable();// 创建一个表 table.Columns.Add("URL");// 创建字段 table.Columns.Add("id"); string str = Images; if (str.Length > 0) { str = str.Substring(0, str.Length - 1); } string[] ss = str.Split(','); DataRow row = table.NewRow(); for (int i = 0; i < ss.Length; i++)// 为表插入数据 { if (i % 2 == 0) row = table.NewRow(); row[i % 2] = ss[i]; if ((i + 1) % 2 == 0) table.Rows.Add(row); } LblNumber.Text = table.Rows.Count.ToString(); if (table.Rows.Count > 0) { GV.DataSource = table; GV.DataBind(); divNumber.Style.Add("display", "block"); } else { GV.DataSource = null; GV.DataBind(); divNumber.Style.Add("display", "none"); } if (GV.Rows.Count == 1) { Button BtnDelete = (Button)GV.Rows[0].Cells[1].FindControl("BtnDelete"); BtnDelete.Enabled = false; } } protected void BtnDtal_Click(object sender, EventArgs e) { int Number = 0; string[] Dir = System.IO.Directory.GetFiles(SlideFolderPath); foreach (string file in Dir) { System.IO.FileInfo FI = new System.IO.FileInfo(file); if (FI.Extension == ".jpg")// 统计一共有多少个后缀为*.jpg的图片文件 { Number++; } } if (FUDtal.PostedFile.FileName == "") { Page.ClientScript.RegisterStartupScript(GetType(), "rsnn14", "<script>alert('请选择图片');</script>"); return; } if (Number == 0) { Number = 1; } else if (Number > 0) { Number = Number + 1; } string name = FUDtal.PostedFile.FileName;//获取文件名称 int index = name.LastIndexOf("."); string lastName = name.Substring(index, name.Length - index);//文件后缀 string Newname = Number.ToString() + lastName;//文件名 // || lastName == ".bmp" || lastName == ".gif" || lastName == ".png" if (lastName == ".jpg") { System.Drawing.Image image = System.Drawing.Image.FromStream(FUDtal.PostedFile.InputStream); int height = image.Height; int width = image.Width; if (height == 481 && width == 1920) { string path = SlideFolderPath + Newname; FUDtal.PostedFile.SaveAs(path);//保存到服务器上 Page.ClientScript.RegisterStartupScript(GetType(), "rsnn2", "<script>alert('图片上传成功');</script>"); bind(); } else { Page.ClientScript.RegisterStartupScript(GetType(), "rsnn12", "<script>alert('图片尺寸错误');</script>"); return; } } else { Page.ClientScript.RegisterStartupScript(GetType(), "rsnn17", "<script>alert('图片后缀错误!');</script>"); return; } } protected void BtnDelete_Click(object sender, EventArgs e) { int row = ((GridViewRow)((Button)sender).NamingContainer).RowIndex; HiddenField HFid = (HiddenField)GV.Rows[row].Cells[0].FindControl("HFid"); string Route = SlideFolderPath + HFid.Value + ".jpg"; FileInfo file = new FileInfo(Route);//指定文件路径 if (file.Exists)//判断文件是否存在 { file.Attributes = FileAttributes.Normal;//将文件属性设置为普通,比方说只读文件设置为普通 file.Delete();//删除文件 if (file.Exists == false) { Page.ClientScript.RegisterStartupScript(GetType(), "rsnn3", "<script>alert('图片删除成功');</script>"); bindReset(); bind(); } else { Page.ClientScript.RegisterStartupScript(GetType(), "rsnn16", "<script>alert('图片删除失败');</script>"); return; } } } public void bindReset()// 重新命名图片 { string Images = ""; string[] Dir = System.IO.Directory.GetFiles(SlideFolderPath); foreach (string file in Dir) { System.IO.FileInfo FI = new System.IO.FileInfo(file); if (FI.Extension == ".jpg") { string name = FI.Name.Substring(0, FI.Name.Length - 4);// 获取文件名 Images += name + ","; } } DataTable table = new DataTable();// 创建一个表 table.Columns.Add("id");// 创建字段 string str = Images; if (str.Length > 0) { str = str.Substring(0, str.Length - 1); } string[] ss = str.Split(','); DataRow row = table.NewRow(); for (int i = 0; i < ss.Length; i++)// 为表插入数据 { if (i % 1 == 0) row = table.NewRow(); row[i % 1] = ss[i]; if ((i + 1) % 1 == 0) table.Rows.Add(row); } for (int i = 0; i < table.Rows.Count; i++) { string id = table.Rows[i]["id"].ToString(); string srcFileName = SlideFolderPath + id + ".jpg"; string destFileName = SlideFolderPath + (i + 1) + ".jpg"; if (System.IO.File.Exists(srcFileName)) { System.IO.File.Move(srcFileName, destFileName);// 重新命名图片 } } } } ``` 前台代码 ``` <%@ Control Language="C#" AutoEventWireup="true" CodeFile="addhuandeng.ascx.cs" Inherits="admin_netshopper_DHweihu_makepage_addhuandeng" %> <div style="width: 1024px; -moz-box-shadow: 0px 0px 10px #BFBFBF; -webkit-box-shadow: 0px 0px 10px #BFBFBF; box-shadow: 0px 0px 10px #BFBFBF; padding: 20px 5px; margin: 50px auto"> <div style="width: 98%; margin-left: auto; margin-right: auto;"> <asp:FileUpload ID="FUDtal" runat="server" /> <asp:Button ID="BtnDtal" runat="server" Text="上传" Height="30px" OnClick="BtnDtal_Click" /> 后缀: *.jpg(注:图片格式为宽:1920px、高:481px) </div> <div style="width: 98%; margin: 20px auto 0px auto;"> <div id="divNumber" runat="server" style="width: 100%; text-align: left; display: block; margin-bottom: 5px;"> 当前共有<asp:Label ID="LblNumber" runat="server"></asp:Label>张图片 </div> <asp:GridView ID="GV" runat="server" Width="100%" CellPadding="4" ForeColor="#333333" GridLines="None" AutoGenerateColumns="False"> <Columns> <asp:TemplateField HeaderText="图片"> <ItemTemplate> <asp:Image ID="Images" runat="server" Width="900px" ImageUrl='<%# Eval("URL") %>' /> <asp:HiddenField ID="HFid" runat="server" Value='<%# Eval("id") %>' /> </ItemTemplate> <HeaderStyle HorizontalAlign="Center" /> <ItemStyle HorizontalAlign="Center" /> </asp:TemplateField> <asp:TemplateField HeaderText="操作"> <ItemTemplate> <asp:Button ID="BtnDelete" runat="server" Text="删除" Width="40px" Height="30px" OnClick="BtnDelete_Click" /> </ItemTemplate> <HeaderStyle HorizontalAlign="Center" /> <ItemStyle HorizontalAlign="Center" /> </asp:TemplateField> </Columns> <AlternatingRowStyle BackColor="White" /> <EditRowStyle BackColor="#2461BF" /> <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /> <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /> <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" /> <RowStyle BackColor="#EFF3FB" /> <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" /> <SortedAscendingCellStyle BackColor="#F5F7FB" /> <SortedAscendingHeaderStyle BackColor="#6D95E1" /> <SortedDescendingCellStyle BackColor="#E9EBEF" /> <SortedDescendingHeaderStyle BackColor="#4870BE" /> </asp:GridView> </div> </div> ```
jsvalidation用法,小白提问!!
1、使用jsvalidation没效果,点击表单提交没验证直接到了下一页,按F12显示 HTTP404: 找不到 - 服务器尚未找到与请求的 URI (统一资源标识符)匹配的任何内容。 GET - http://localhost:8081/js/validation-framework.js 不知道啥原因,jsvalidation的三个dtd xml 和js代码是老师给的,说是要写一个什么正则表达式,不会改 求解答 2 查过资料 web。xml中没有设置那个什么过滤那个 3下面是framework。js的代码,看不懂 ``/* * JavaScript Validation Framework * * Author: Michael Chen(mechiland) on 2004/03 * This software is on the http://www.cosoft.org.cn/projects/jsvalidation * for update, bugfix, etc, you can goto the homepage and submit your request * and question. * Apache License 2.0 * You should use this software under the terms. * * Please, please keep above words. At least ,please make a note that such as * "This software developed by Michael Chen(http://www.jzchen.net)" . * $Id: validation-framework.js,v 1.7 2004/04/30 05:33:29 jzchen Exp $ */ /** Config Section, Config these fields to make this framework work. **/ // If there is only one config file in your system, use this property. otherwise, use // ValidationFramework.init("configfile") // instead. var ValidationRoot = "/LoginServletProjectFour/js/"; // the field style when validation fails. it aim to provide more beautiful UI and more good // experience to the end-user. // NOTE: this will be buggy. Please report the error to me. var ValidationFailCssStyle = "border:2px solid #FFCC88;"; //Validation function. The entry point of the framework. function doValidate(formRef) { try { var formId = formRef; if (typeof (formRef) == "string") { formId = formRef; } else if (typeof (formRef) == "object") { formId = formRef.getAttribute("id"); } var form = FormFactory.getFormFromId(formId); if (form != null) { return ValidationFramework.validateForm(form); } else { return false; } } catch (e) { ValidationFramework.exception(e.name+":" +e.description); return false; } } /**===================================================================**/ /* * JSValidation Framework Code Started * * Please do not modify the code unless you are very familiar with JavaScript. * The best way to solve problem is report the problem to our project page. * url: http://cosoft.org.cn/projects/jsvalidation */ // The Xml document. To process cross-browser. Thanks Eric. function XmlDocument() {} XmlDocument.create = function () { if (document.implementation && document.implementation.createDocument) { return document.implementation.createDocument("", "", null); } else if (window.ActiveXObject) { try { var prefix = ["MSXML2", "MSXML", "Microsoft", "MSXML3"]; for (var i = 0; i < prefix.length; i++) { //return new ActiveXObject(prefix[i] + ".DomDocument"); var obj = new ActiveXObject(prefix[i] + ".DomDocument"); if (obj == null || typeof(obj) == 'undefined') { continue; } else { return obj; } } } catch (e) { //^_^ throw new Error("My God, What version of IE are you using? IE5&+ is requiered."); } } else throw new Error("Cannot create DOM Document!"); } function ValidationFramework() {} ValidationFramework._validationCache = null; ValidationFramework._currentForm = null; ValidationFramework._userLanguage="auto"; /** * Validate a form. * NOTE: the form is Framework virture form, not the HTML Form. * Html Form can be transform to Virture form by * FormFactory.getFormFromId(htmlFormId); * See the doc for more information. * @param form the virtual form. */ ValidationFramework.validateForm = function(fform) { ValidationFramework._currentForm = fform; var failFields = []; var id = fform.getId(); var showError = fform.getShowError(); var showType = fform.getShowType(); var br = null; if (showError != "alert") { br = "<br />"; } else { br = "\n"; } var errorStrArray = []; var ret = false; var formObj = document.getElementById(id); var fields = fform.getFields(); var rightnum = 0; for (var i = 0; i < fields.length; i++) { var retVal = ValidationFramework.validateField(fields[i]); var fo=formObj[fields[i].getName()]; if (typeof (fo) !='undefined' && fo != null && typeof(fo.type) != "undefined") { fo.style.cssText = ""; } if (retVal != "OK") { errorStrArray[errorStrArray.length] = retVal; failFields[failFields.length] = formObj[fields[i].getName()]; } else { rightnum ++; } } if (rightnum == fields.length) { ret = true; } if (errorStrArray.length > 0) { if (showError == "alert") { if (showType == "first") { alert(errorStrArray[0]); } else { alert(errorStrArray.join(br)); } } else { var errObj = document.getElementById(showError); if (showType == "first") { errObj.innerHTML = errorStrArray[0]; } else { errObj.innerHTML = errorStrArray.join(br); } } if (typeof (failFields[0]) !='undefined' && failFields[0] != null && typeof(failFields[0].type) != "undefined") { failFields[0].focus(); } for (var i = 0; i < failFields.length; i++) { var o = failFields[i]; if ( typeof (o) !='undefined' && o != null && typeof(o.type) != "undefined") { o.style.cssText = ValidationFailCssStyle; } } } return ret; } /** * Validation the field * @param filed the field you want to validate. */ ValidationFramework.validateField = function(field) { var depends = field.getDepends(); var retStr = "OK"; for (var i = 0; i < depends.length; i++) { if (!ValidationFramework.validateDepend(field, depends[i])) { retStr = ValidationFramework.getErrorString(field, depends[i]); return retStr; //Break; } } return retStr; } /** * Validate the field depend. * This function dispatch the various depends into ValidateMethodFactory.validateXXX */ ValidationFramework.validateDepend = function(field, depend) { if (depend.getName() == "required") { return ValidateMethodFactory.validateRequired(field, depend.getParams()); } else if (depend.getName() == "integer") { return ValidateMethodFactory.validateInteger(field, depend.getParams()); } else if (depend.getName() == "double") { return ValidateMethodFactory.validateDouble(field, depend.getParams()); } else if (depend.getName() == "commonChar") { return ValidateMethodFactory.validateCommonChar(field, depend.getParams()); } else if (depend.getName() == "chineseChar") { return ValidateMethodFactory.validateChineseChar(field, depend.getParams()); } else if (depend.getName() == "minLength") { return ValidateMethodFactory.validateMinLength(field, depend.getParams()); } else if (depend.getName() == "maxLength") { return ValidateMethodFactory.validateMaxLength(field, depend.getParams()); } else if (depend.getName() == "email") { return ValidateMethodFactory.validateEmail(field, depend.getParams()); } else if (depend.getName() == "date") { return ValidateMethodFactory.validateDate(field, depend.getParams()); } else if (depend.getName() == "time") { return ValidateMethodFactory.validateTime(field, depend.getParams()); } else if (depend.getName() == "mask") { return ValidateMethodFactory.validateMask(field, depend.getParams()); } else if (depend.getName() == "integerRange") { return ValidateMethodFactory.validateIntegerRange(field, depend.getParams()); } else if (depend.getName() == "doubleRange") { return ValidateMethodFactory.validateDoubleRange(field, depend.getParams()); } else if (depend.getName() == "equalsField") { return ValidateMethodFactory.validateEqualsField(field, depend.getParams()); } else { ValidationFramework.exception("还未实现该依赖: " + depend.getName()); return false; } } // hold the current config file var _validationConfigFile = ""; ValidationFramework.getDocumentElement = function() { if (ValidationFramework._validationCache != null) { return ValidationFramework._validationCache; } var file = ""; if (_validationConfigFile != "") { file = _validationConfigFile; } else { file = ValidationRoot + "validation-config.xml"; } var xmlDoc = XmlDocument.create(); xmlDoc.async = false; // Damn!!! it cost me half an hour to fix it! xmlDoc.load(file); if (xmlDoc.documentElement == null) { ValidationFramework.exception("配置文件读取错误,请检查。"); return null; } // TODO: parse the document if it's a valid document. ValidationFramework._validationCache = xmlDoc.documentElement; var lang=ValidationFramework._validationCache.getAttribute("lang"); ValidationFramework._userLanguage = (lang==null) ? "auto" : lang; return ValidationFramework._validationCache; } ValidationFramework.init = function(configFile) { _validationConfigFile = configFile; ValidationFramework.getDocumentElement(); } ValidationFramework.getAllForms = function() { var vforms = []; var root = ValidationFramework.getDocumentElement(); if (root != null) { var fs = root.childNodes; for (var i = 0;i < fs.length ;i++ ) { vforms[i] = new ValidationForm(fs.item(i)); } } return vforms; } ValidationFramework.getErrorString = function(field, depend) { var stringResource = null; var lang = ValidationFramework._userLanguage.toLowerCase(); //if lang == auto, get the user's browser language. if (lang == "auto") { // different browser has the different method the get the // user's language. so this is a stupid way to detect the // most common browser IE and Mozilla. if (typeof navigator.userLanguage == 'undefined') lang = navigator.language.toLowerCase(); else lang = navigator.userLanguage.toLowerCase(); } // get the language if (typeof ValidationErrorString[lang] != 'object') { stringResource = ValidationErrorString['zh-cn']; } else { stringResource = ValidationErrorString[lang]; } var dep = depend.getName().toLowerCase(); var retStr = stringResource[dep]; //If the specified depend not defined, use the default error string. if (typeof retStr != 'string') { retStr = stringResource["default"]; retStr = retStr.replace("{0}", field.getDisplayName()); return retStr; } retStr = retStr.replace("{0}", field.getDisplayName()); if (dep == "minlength" || dep == "maxlength" || dep == "date" ) { retStr = retStr.replace("{1}", depend.getParams()[0]); } else if ( dep == "equalsfield") { var eqField = field.getForm().findField(depend.getParams()[0]); if (eqField == null) { ValidationFramework.exception("找不到名称为[" + depend.getParams()[0]+"]的域,请检查xml配置文件。"); retStr = "<<配置错误>>"; } else { retStr = retStr.replace("{1}", field.getForm().findField(depend.getParams()[0]).getDisplayName()); } } else if (dep == "integerrange" || dep == "doublerange") { retStr = retStr.replace("{1}", depend.getParams()[0]); retStr = retStr.replace("{2}", depend.getParams()[1]); } return retStr; } ValidationFramework.getWebFormFieldObj = function(field) { var obj = null; if (ValidationFramework._currentForm != null) { var formObj = document.getElementById(ValidationFramework._currentForm.getId()); obj = formObj[field.getName()]; if (typeof(obj) == 'undefined') { obj = null; } } if (obj == null) { ValidationFramework.exception("在配置文件中有需要验证的域,但在实际网页表单中不存在:[name=" + field.getName() + "]。"); } return obj; } ValidationFramework.exception = function(str) { var ex = "JavaScript Validation Framework 运行时错误:\n\n"; ex += str; ex += "\n\n\n任何运行错误都会导致该域验证失败。"; alert(ex); } ValidationFramework.getIntegerValue = function(val) { var intvalue = parseInt(val); if (isNaN(intvalue)) { ValidationFramework.exception("期待一个整型参数。"); } return intvalue; } ValidationFramework.getFloatValue = function(val) { var floatvalue = parseFloat(val); if (isNaN(floatvalue)) { ValidationFramework.exception("期待一个浮点型参数。"); } return floatvalue; } /** * FormFactory * Build virture form from Html Form. */ function FormFactory() {} FormFactory.getFormFromDOM = function(dom) { var form = new ValidationForm(); form.setId(dom.getAttribute("id")); form.setShowError(dom.getAttribute("show-error")); form.setOnFail(dom.getAttribute("onfail")); form.setShowType(dom.getAttribute("show-type")); if (dom.hasChildNodes()) { var f = dom.childNodes; for (var i = 0; i < f.length; i++) { if (f.item(i) == null||typeof(f.item(i).tagName) == 'undefined' || f.item(i).tagName != 'field') { continue; } var field = FieldFactory.getFieldFromDOM(f.item(i)); if (field != null) { form.addField(field); } } } return form; } /// Get the Form from ID FormFactory.getFormFromId = function(id) { var root = ValidationFramework.getDocumentElement(); if ( root == null || (!root.hasChildNodes()) ) return null; var vforms = root.childNodes; for (var i = 0; i < vforms.length; i++) { var f = vforms.item(i); if (typeof(f.tagName) != 'undefined' && f.tagName == 'form' && f.getAttribute("id") == id) { return FormFactory.getFormFromDOM(f); } } return null; } /** * A validation form object. */ function ValidationForm() { this._fields = []; this._id = null; this._showError = null; this._onFail = null; this._showType = null; this.getFields = function() { return this._fields; } this.setFields = function(p0) { this._fields = p0; } this.getId = function() { return this._id; } this.setId = function(p0) { this._id = p0; } this.getShowError = function() { return this._showError; } this.setShowError = function(p0) { this._showError = p0; } this.getShowType = function() { return this._showType; } this.setShowType = function(p0) { this._showType = p0; } this.getOnFail = function() { return this._onFail; } this.setOnFail = function(p0) { this._onFail = p0; } // find field by it's name this.findField = function(p0) { for (var i = 0; i < this._fields.length; i++) { if (this._fields[i].getName() == p0) { return this._fields[i]; } } return null; } this.addField = function(p0) { this._fields[this._fields.length] = p0; p0.setForm(this); } } /** * A form filed. virtual. */ function ValidationField() { this._name = null; this._depends = []; this._displayName = null; this._onFail = null; this._form = null; this.getName = function() { return this._name; } this.setName = function(p0) { this._name = p0; } this.getDepends = function() { return this._depends; } this.setDepends = function(p0) { this._depends = p0; } this.getDisplayName = function() { return this._displayName; } this.setDisplayName = function(p0) { this._displayName = p0; } this.getOnFail = function() { return this._onFail; } this.setOnFail = function(p0) { this._onFail = p0; } this.getForm = function() { return this._form; } this.setForm = function(p0) { this._form = p0; } this.addDepend = function(p0) { this._depends[this._depends.length] = p0; } } ///Factory methods for create Field function FieldFactory() {} FieldFactory.getFieldFromDOM = function(dom) { var field = new ValidationField(); field.setName(dom.getAttribute("name")); field.setDisplayName(dom.getAttribute("display-name")); field.setOnFail(dom.getAttribute("onfail")); if (dom.hasChildNodes()) { var depends = dom.childNodes; for (var i = 0; i < depends.length; i++) { var item = depends.item(i); if (typeof(item.tagName) == 'undefined' || item.tagName != 'depend') { continue; } var dp = new ValidationDepend(); dp.setName(item.getAttribute("name")); dp.addParam(item.getAttribute("param0")); dp.addParam(item.getAttribute("param1")); dp.addParam(item.getAttribute("param2")); dp.addParam(item.getAttribute("param3")); dp.addParam(item.getAttribute("param4")); field.addDepend(dp); } } return field; } function FormFieldUtils() {} FormFieldUtils.findField = function(formName, fieldName) { var formArr = ValidationFramework.getAllForms(); var theForm = null; for (var i = 0; i < formArr.length; i++) { if (formArr[i].getName() == formName) { theForm = formArr[i]; } } if (theForm != null) { return theForm.findField(fieldName); } else { return null; } } /** * A validaton depend. */ function ValidationDepend() { this._name = null; this._params = []; this.getName = function() { return this._name; } this.setName = function(p0) { this._name = p0; } this.getParams = function() { return this._params; } this.setParams = function(p0) { this.params = p0; } this.addParam = function(p0) { this._params[this._params.length] = p0; } } function ValidateMethodFactory() {} ValidateMethodFactory._methods = []; ValidateMethodFactory.validateRequired = function(field, params) { var obj = ValidationFramework.getWebFormFieldObj(field); if (obj == null) return false; if (typeof(obj.type) == "undefined") { var tmp = 0; for (var i = 0; i < obj.length; i++) { if (obj[i].checked) { return true; } } return false; } if (obj.type == "checkbox" || obj.type == "radio") { return (obj.checked); } else { return !(obj.value == ""); } } ValidateMethodFactory.validateInteger = function(field, params) { var obj = ValidationFramework.getWebFormFieldObj(field); if (obj == null) return false; if (obj.value == "") return true; var exp = new RegExp("^-?\\d+$"); return exp.test(obj.value); } ValidateMethodFactory.validateDouble = function(field, params) { var obj = ValidationFramework.getWebFormFieldObj(field); if (obj == null) return false; if (obj.value == "") return true; var exp = new RegExp("^-?\\d+\.\\d+$"); return exp.test(obj.value); } ValidateMethodFactory.validateCommonChar = function(field, params) { var obj = ValidationFramework.getWebFormFieldObj(field); if (obj == null) return false; if (obj.value == "") return true; var exp = new RegExp("^[A-Za-z0-9_]*$"); return exp.test(obj.value); } ValidateMethodFactory.validateChineseChar = function(field, params) { var obj = ValidationFramework.getWebFormFieldObj(field); if (obj == null) return false; if (obj.value == "") return true; var exp = new RegExp("^[\u4E00-\u9FA5\uF900-\uFA2D]*$"); return exp.test(obj.value); } ValidateMethodFactory.validateMinLength = function(field, params) { var obj = ValidationFramework.getWebFormFieldObj(field); if (obj == null) return false; var v = ValidationFramework.getIntegerValue(params[0]); return (obj.value.length >= v); } ValidateMethodFactory.validateMaxLength = function(field, params) { var obj = ValidationFramework.getWebFormFieldObj(field); if (obj == null) return false; var v = ValidationFramework.getIntegerValue(params[0]); return (obj.value.length <= v); } ValidateMethodFactory.validateEmail = function(field, params) { var obj = ValidationFramework.getWebFormFieldObj(field); if (obj == null) return false; return ValidateMethodFactory.__checkEmail(obj.value); } ValidateMethodFactory.validateDate = function(field, params) { var obj = ValidationFramework.getWebFormFieldObj(field); if (obj == null) return false; if (obj.value == "") return true; var value = obj.value; var datePattern = params[0]; var MONTH = "mm"; var DAY = "dd"; var YEAR = "yyyy"; var orderMonth = datePattern.indexOf(MONTH); var orderDay = datePattern.indexOf(DAY); var orderYear = datePattern.indexOf(YEAR); var bValid = true; var dateRegexp = null; if ((orderDay < orderYear && orderDay > orderMonth)) { var iDelim1 = orderMonth + MONTH.length; var iDelim2 = orderDay + DAY.length; var delim1 = datePattern.substring(iDelim1, iDelim1 + 1); var delim2 = datePattern.substring(iDelim2, iDelim2 + 1); if (iDelim1 == orderDay && iDelim2 == orderYear) { dateRegexp = new RegExp("^(\\d{2})(\\d{2})(\\d{4})$"); } else if (iDelim1 == orderDay) { dateRegexp = new RegExp("^(\\d{2})(\\d{2})[" + delim2 + "](\\d{4})$"); } else if (iDelim2 == orderYear) { dateRegexp = new RegExp("^(\\d{2})[" + delim1 + "](\\d{2})(\\d{4})$"); } else { dateRegexp = new RegExp("^(\\d{2})[" + delim1 + "](\\d{2})[" + delim2 + "](\\d{4})$"); } var matched = dateRegexp.exec(value); if(matched != null) { if (!ValidateMethodFactory.__isValidDate(matched[2], matched[1], matched[3])) { bValid = false; } } else { bValid = false; } } else if ((orderMonth < orderYear && orderMonth > orderDay)) { var iDelim1 = orderDay + DAY.length; var iDelim2 = orderMonth + MONTH.length; var delim1 = datePattern.substring(iDelim1, iDelim1 + 1); var delim2 = datePattern.substring(iDelim2, iDelim2 + 1); if (iDelim1 == orderMonth && iDelim2 == orderYear) { dateRegexp = new RegExp("^(\\d{2})(\\d{2})(\\d{4})$"); } else if (iDelim1 == orderMonth) { dateRegexp = new RegExp("^(\\d{2})(\\d{2})[" + delim2 + "](\\d{4})$"); } else if (iDelim2 == orderYear) { dateRegexp = new RegExp("^(\\d{2})[" + delim1 + "](\\d{2})(\\d{4})$"); } else { dateRegexp = new RegExp("^(\\d{2})[" + delim1 + "](\\d{2})[" + delim2 + "](\\d{4})$"); } var matched = dateRegexp.exec(value); if(matched != null) { if (!ValidateMethodFactory.__isValidDate(matched[1], matched[2], matched[3])) { bValid = false; } } else { bValid = false; } } else if ((orderMonth > orderYear && orderMonth < orderDay)) { var iDelim1 = orderYear + YEAR.length; var iDelim2 = orderMonth + MONTH.length; var delim1 = datePattern.substring(iDelim1, iDelim1 + 1); var delim2 = datePattern.substring(iDelim2, iDelim2 + 1); if (iDelim1 == orderMonth && iDelim2 == orderDay) { dateRegexp = new RegExp("^(\\d{4})(\\d{2})(\\d{2})$"); } else if (iDelim1 == orderMonth) { dateRegexp = new RegExp("^(\\d{4})(\\d{2})[" + delim2 + "](\\d{2})$"); } else if (iDelim2 == orderDay) { dateRegexp = new RegExp("^(\\d{4})[" + delim1 + "](\\d{2})(\\d{2})$"); } else { dateRegexp = new RegExp("^(\\d{4})[" + delim1 + "](\\d{2})[" + delim2 + "](\\d{2})$"); } var matched = dateRegexp.exec(value); if(matched != null) { if (!ValidateMethodFactory.__isValidDate(matched[3], matched[2], matched[1])) { bValid = false; } } else { bValid = false; } } else { bValid = false; } return bValid; } ValidateMethodFactory.validateTime = function(field, params) { ////NOT IMPLEMENT YET SINCE IT'S NOT USEFUL. return true; } ValidateMethodFactory.validateMask = function(field, params) { var obj = ValidationFramework.getWebFormFieldObj(field); if (obj == null) return false; if (obj.value == "") return true; var exp = new RegExp(params[0]); //FIXME: this method may be buggy, need more test. return exp.test(obj.value); } ValidateMethodFactory.validateIntegerRange = function(field, params) { var obj = ValidationFramework.getWebFormFieldObj(field); if (obj == null) return false; if (obj.value == "") return true; var p0 = ValidationFramework.getIntegerValue(params[0]); var p1 = ValidationFramework.getIntegerValue(params[1]); if (ValidateMethodFactory.validateInteger(field)) { var v = parseInt(obj.value); return (v >= p0 && v <= p1); } else { return false; } return true; } ValidateMethodFactory.validateDoubleRange = function(field, params) { var obj = ValidationFramework.getWebFormFieldObj(field); if (obj == null) return false; if (obj.value == "") return true; var p0 = ValidationFramework.getFloatValue(params[0]); var p1 = ValidationFramework.getFloatValue(params[1]); if (ValidateMethodFactory.validateInteger(field) || ValidateMethodFactory.validateDouble(field)) { var v = parseFloat(obj.value); return (v >= p0 && v <= p1); } else { return false; } return true; } ValidateMethodFactory.validateEqualsField = function(field, params) { var obj = ValidationFramework.getWebFormFieldObj(field); if (obj == null) return false; var formObj = document.getElementById(ValidationFramework._currentForm.getId()); var eqField = formObj[params[0]]; if (eqField != null) { return (obj.value == eqField.value) } else { return false; } } ValidateMethodFactory.__isValidDate = function(day, month, year) { if (month < 1 || month > 12) return false; if (day < 1 || day > 31) return false; if ((month == 4 || month == 6 || month == 9 || month == 11) &&(day == 31)) return false; if (month == 2) { var leap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)); if (day>29 || (day == 29 && !leap)) return false; } return true; } /** * Reference: Sandeep V. Tamhankar (stamhankar@hotmail.com), * http://javascript.internet.com */ ValidateMethodFactory.__checkEmail = function(emailStr) { if (emailStr.length == 0) { return true; } var emailPat=/^(.+)@(.+)$/; var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"; var validChars="\[^\\s" + specialChars + "\]"; var quotedUser="(\"[^\"]*\")"; var ipDomainPat=/^(\d{1,3})[.](\d{1,3})[.](\d{1,3})[.](\d{1,3})$/; var atom=validChars + '+'; var word="(" + atom + "|" + quotedUser + ")"; var userPat=new RegExp("^" + word + "(\\." + word + ")*$"); var domainPat=new RegExp("^" + atom + "(\\." + atom + ")*$"); var matchArray=emailStr.match(emailPat); if (matchArray == null) { return false; } var user=matchArray[1]; var domain=matchArray[2]; if (user.match(userPat) == null) { return false; } var IPArray = domain.match(ipDomainPat); if (IPArray != null) { for (var i = 1; i <= 4; i++) { if (IPArray[i] > 255) { return false; } } return true; } var domainArray=domain.match(domainPat); if (domainArray == null) { return false; } var atomPat=new RegExp(atom,"g"); var domArr=domain.match(atomPat); var len=domArr.length; if ((domArr[domArr.length-1].length < 2) || (domArr[domArr.length-1].length > 3)) { return false; } if (len < 2) { return false; } return true; } ////Language Definitions var ValidationErrorString = new Object(); ////Simplified Chinese(zh-ch) ValidationErrorString["zh-cn"] = new Object(); ValidationErrorString["zh-cn"]["default"]="域{0}校验失败。"; ValidationErrorString["zh-cn"]["required"]="{0}不能为空。<br/>"; ValidationErrorString["zh-cn"]["integer"]="{0}必须是一个整数。"; ValidationErrorString["zh-cn"]["double"]="{0}必须是一个浮点数(带小数点)。"; ValidationErrorString["zh-cn"]["commonchar"] = "{0}必须是普通英文字符:字母,数字和下划线。<br/>"; ValidationErrorString["zh-cn"]["chinesechar"] = "{0}必须是中文字符。"; ValidationErrorString["zh-cn"]["minlength"]="{0}长度不能小于{1}个字符。"; ValidationErrorString["zh-cn"]["maxlength"]="{0}长度不能大于{1}个字符。" ; ValidationErrorString["zh-cn"]["invalid"]="{0}无效。"; ValidationErrorString["zh-cn"]["date"]="{0}不是一个有效日期,期待格式:{1}。"; ValidationErrorString["zh-cn"]["integerrange"]="{0}必须在整数{1}和{2}之间。"; ValidationErrorString["zh-cn"]["doublerange"]="{0}必须在浮点数{1}和{2}之间。"; ValidationErrorString["zh-cn"]["pid"]="{0}不是一个有效身份证号。"; ValidationErrorString["zh-cn"]["email"]="{0}不是一个有效的Email。"; ValidationErrorString["zh-cn"]["equalsfield"]="{0}必须和{1}一致。"; ////English(en-us) ValidationErrorString["en-us"] = new Object(); ValidationErrorString["en-us"]["default"]="Failed when validating filed {0}."; ValidationErrorString["en-us"]["required"]="{0} is required."; ValidationErrorString["en-us"]["integer"]="{0} must be a integer."; ValidationErrorString["en-us"]["double"]="{0} must be a double value. "; ValidationErrorString["en-us"]["commonchar"] = "{0} should be common ascii characters, A-Z,a-z and undercore. "; ValidationErrorString["en-us"]["chinesechar"] = "{0} must be chinese characters. "; ValidationErrorString["en-us"]["minlength"]="{0} cannot be less then {1}. "; ValidationErrorString["en-us"]["maxlength"]="{0} cannot be more then {1}. "; ValidationErrorString["en-us"]["invalid"]="{0} in invalid. "; ValidationErrorString["en-us"]["date"]="{0} is not an invalid date format: {1}. "; ValidationErrorString["en-us"]["integerrange"]="{0} should be between number {1} and {2}. "; ValidationErrorString["en-us"]["doublerange"]="{0} should be between double {1} and {2}. "; ValidationErrorString["en-us"]["pid"]="{0} is not an valid pid. "; ValidationErrorString["en-us"]["email"]="{0} is not an valid email address. "; ValidationErrorString["en-us"]["equalsfield"]="{0} should be agree with field {1}. "; // preload the validation file. //ValidationFramework.getDocumentElement();` 4xml代码 ``` <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE validation-config SYSTEM "validation-config.dtd"> <validation-config lang="auto"> <form id="form1" show-error="alert" show-type="all"> <field name="name" display-name="姓名" onfail=""> <depend name="required" /> <depend name="commonChar" /> <depend name="minLength" param0="3" /> <depend name="maxLength" param0="20" /> </field> <field name="email" display-name="email邮箱"> <depend name="required" /> <depend name="email" /> </field> <field name="age" display-name="年龄"> <depend name="required" /> </field> <field name="protime" display-name="编程时间"> <depend name="required" /> </field> <field name="os" display-name="使用的操作系统"> <depend name="required" /> </field> <field name="lang" display-name="使用的编程语言"> <depend name="required" /> </field> <field name="editor1" display-name="建议"> <depend name="required" /> </field> </form> </validation-config> ``` 5jsp代码 ``` <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'Login.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <script type='text/javascript' src='ckeditor/ckeditor.js'></script> <script type='text/javascript' src='/js/validation-framework.js'></script> <body> <h1>潜在用户网络调查</h1> <form action='LoginServlet' name='form1' id='form1' method='post' onSubmit="return doValidate(this)"> 姓名:<input type='text' name='name' value='' /><br/> EMAIL:<input type='text' name='email' value=''/><br/> 年纪:<input type='radio' name='age' value='小于18' />小于18 <input type='radio' name='age' value='18-25'/>18-25 <input type='radio' name='age' value='26-40'/>26-40 <input type='radio' name='age' value='大于40'/>大于40<br/> 编程时间:<select name='protime'> <option value='6-12月' >6-12月</option> <option value='12-24月'>12-24月</option> <option value='24月以上'>24月以上</option> </select><br/> 使用操作系统:<select name='os' multiple='multiple' size='6'> <option value='Win XP'>Win XP</option> <option value='Win 2000/2003'>Win 2000/2003</option> <option value='Linux'>Linux</option> <option value='FreeBSD'>FreeBSD</option> <option value='Mac OS'>Mac OS</option> <option value='Other'>Other</option> </select><br/> 使用的编程语言:<input type='checkbox' name='lang' value='C'/>C <input type='checkbox' name='lang' value='C++'/>C++ <input type='checkbox' name='lang' value='C#'/>C# <input type='checkbox' name='lang' value='PYTHON'/>PYTHON <input type='checkbox' name='lang' value='JAVA'/>JAVA <input type='checkbox' name='lang' value='VB'/>VB <input type='checkbox' name='lang' value='DEPHI'/>DEPHI<br/> 建议:<textarea class='ckeditor' cols='50' id='editor1' name='editor1' rows='10'></textarea><br/> <input type='submit' value='提交'> <input type='reset' value='重置'> <input type='hidden' name='ring' value='normal'><br/> <% HttpSession hs=request.getSession(true); hs.setAttribute("write", "yes"); %> </form> </body> </html> ```
c#监听串口是怎么监听不到
![图片说明](https://img-ask.csdn.net/upload/201503/13/1426229159_781487.png) 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; //添加的引用 using System.IO.Ports; using System.Threading; using Microsoft.Win32; namespace JTproject { /*创建时间: *功能:监听串口 *创建作者: ***/ public partial class jianting : Form { public jianting() { InitializeComponent(); } private SerialPort Sp = new SerialPort(); public delegate void HandleInterfaceUpdataDelegate(string text); //委托,此为重点 private HandleInterfaceUpdataDelegate interfaceUpdataHandle; // private bool qiii = false; private void jianting_Load(object sender, EventArgs e) { GetComList(); //txtcomid.Focus(); btnPause.Enabled = false; } private void UpdateTextBox(string text) { txtData.Text = text; } //监听 private void btnENT_Click(object sender, EventArgs e) { //if ((cmID.Text.Trim() != "") && (cmRate.Text != "")) if ((cmID.Text.Trim()!= "") && cmRate.Text!= "") { interfaceUpdataHandle = new HandleInterfaceUpdataDelegate(UpdateTextBox);//实例化委托对象 Sp.PortName = cmID.Text.Trim(); Sp.BaudRate = Convert.ToInt32(cmRate.Text.Trim()); Sp.Parity = Parity.None; Sp.StopBits = StopBits.One; Sp.DataReceived += new SerialDataReceivedEventHandler(Sp_DataReceived); Sp.ReceivedBytesThreshold = 1; try { Sp.Open(); ATCommand3("AT+CLIP=1\r", "OK"); //txtcomid.ReadOnly = true; btnPause.Enabled = true; btnENT.Enabled = false; } catch { MessageBox.Show("端口" + cmID.Text.Trim() + "打开失败!"); } } else { MessageBox.Show("请输入正确的端口号和波特率!"); cmID.Focus(); } } //暂停 private void btnPause_Click(object sender, EventArgs e) { Sp.Close(); btnENT.Enabled = true; btnPause.Enabled = false; //txtcomid.ReadOnly = false; } private void jianting_FormClosing(object sender, FormClosingEventArgs e) { Sp.Close(); } //sp是串口控件 public void Sp_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { string strTemp = ""; double iSecond = 0.5; DateTime dtOld = System.DateTime.Now; DateTime dtNow = System.DateTime.Now; TimeSpan dtInter; dtInter = dtNow - dtOld; int i = Sp.BytesToRead; if (i > 0) { try { strTemp = Sp.ReadExisting(); } catch { } if (strTemp.ToLower().IndexOf("\r") < 0) { i = 0; } else { this.Invoke(interfaceUpdataHandle, strTemp); } } while (dtInter.TotalSeconds < iSecond && i <= 0) { dtNow = System.DateTime.Now; dtInter = dtNow - dtOld; i = Sp.BytesToRead; if (i > 0) { try { strTemp += Sp.ReadExisting(); } catch { } if (strTemp.ToLower().IndexOf("\r") < 0) { i = 0; } else { this.Invoke(interfaceUpdataHandle, strTemp); } } } // do null } /// <summary> /// 执行AT指令并返回 成功失败 /// </summary> /// <param name="ATCmd">AT指令</param> /// <param name="StCmd">AT指令标准结束标识</param> /// <returns></returns> private void ATCommand3(string ATCmd, string StCmd) { string response = ""; response = ATCommand(ATCmd, StCmd); } /// <summary> /// 执行AT指令并返回结果字符 /// </summary> /// <param name="ATCmd">AT指令</param> /// <param name="StCmd">AT指令标准结束标识</param> /// <returns></returns> private string ATCommand(string ATCmd, string StCmd) { string response = ""; int i; if (!ATCmd.EndsWith("\x01a")) { if (!(ATCmd.EndsWith("\r") || ATCmd.EndsWith("\r\n"))) { ATCmd = ATCmd + "\r"; } } Sp.WriteLine(ATCmd); //第一次读响应数据 if (Sp.BytesToRead > 0) { response = Sp.ReadExisting(); //去除前端多可能多读取的字符 if (response.IndexOf(ATCmd) > 0) { response = response.Substring(response.IndexOf(ATCmd)); } else { } if (response == "" || response.IndexOf(StCmd) < 0) { if (response != "") { if (response.Trim() == "ERROR") { //throw vError = new UnknowException("Unknown exception in sending command:" + ATCmd); } if (response.IndexOf("+CMS ERROR") >= 0) { string[] cols = new string[100]; cols = response.Split(';'); if (cols.Length > 1) { string errorCode = cols[1]; } } } } } //读第一次没有读完的响应数据,直到读到特征数据或超时 for (i = 0; i < 3; i++) { Thread.Sleep(1000); response = response + Sp.ReadExisting(); if (response.IndexOf(StCmd) >= 0) { break; } } return response; } /// <summary> /// 从注册表获取系统串口列表 /// </summary> private void GetComList() { RegistryKey keyCom = Registry.LocalMachine.OpenSubKey("Hardware\\DeviceMap\\SerialComm"); if (keyCom != null) { string[] sSubKeys = keyCom.GetValueNames(); this.cmID.Items.Clear(); foreach (string sName in sSubKeys) { string sValue = (string)keyCom.GetValue(sName); this.cmID.Items.Add(sValue); } } } private void cmID_DropDown(object sender, EventArgs e) { GetComList(); } } }
用vb.net(或C#)调用C++编写的DLL时遇到的问题
这部分是在c++中可以正常工作的部分,其声明如下: extern "C" int LHD_Main(unsigned char *pImage, RECT *rcRoi,int w, int h, char *PlateCharacters, RECT *rectPlateLocation, int *PlateReliability, int nMod); 调用如下 //加载图片 IplImage *image = cvLoadImage(file_name,-1); if (image == NULL) { printf("image is not exist!\n"); return -1; } //BGR数据 unsigned char *pRawData = (unsigned char *)malloc(image->width*image->height*image->nChannels); if (NULL == pRawData) { printf("memalloc error\n"); return -1; } int pitch = image->nChannels*image->width; int width = image->width; int height = image->height; //转换成3通道图像 for (int y = 0; y < image->height; y++) { for (int x = 0; x <image->width; x++) { *(pRawData + y*pitch + 3*x) = ((unsigned char *)(image->imageData + image->widthStep*y))[3*x]; *(pRawData + y*pitch + 3*x + 1) = ((unsigned char *)(image->imageData + image->widthStep*y))[3*x+1]; *(pRawData + y*pitch + 3*x + 2) = ((unsigned char *)(image->imageData + image->widthStep*y))[3*x+2]; } } char cFileName[128]; sprintf_s(cFileName,"%s","京"); cProvince[0] = cFileName[0]; cProvince[1] = cFileName[1]; LHD_Init(LPR_WIDTH, LPR_HEIGHT, cProvince); //start license plate recognition module,宽高减少1是图像坐标从0开始 RECT recttROI = {0,0,image->width -1, image->height- 1};//设置区域 RECT rectPlate = {0,0,0,0};//输出定位结果 RECT rectTmp = {0,0,0,0}; int nblePlate = 0;// char HPHM[128] = {'0'};// char mHPHM[128] = {'0'}; int mnblePlate = 0; bool m_bLPR = 0; if(LHD_Main(pRawData,&recttROI,width,height, HPHM, &rectTmp,&nblePlate, i)) 这些代码是可以正常工作的。 下面我在VB.NET中如此声明 <DllImport("LPR.dll", EntryPoint:="LHD_Main", CallingConvention:=CallingConvention.Cdecl)> _ Public Shared Function LHD_Main(ByRef pImage As Byte, ByRef rcRoi As RECT, ByVal w As Int32, ByVal h As Int32, ByRef PlateCharacters As Byte, ByRef rectPlateLocation As RECT, ByRef PlateReliability As Int32, ByVal nMod As Integer) As Int32 End Function Public Structure RECT Dim left As Int32 Dim top As Int32 Dim right As Int32 Dim bottom As Int32 End Structure 调用如下 Dim cProvince(1) As byte cProvince(0) = &HBE cProvince(1) = &HA9 LHD_Init(768, 288, cProvince(0)) Dim path As String = "d:\pic\rtemp.jpg" Dim rImage As IntPtr = Emgu.CV.CvInvoke.cvLoadImage(path, Emgu.CV.CvEnum.LOAD_IMAGE_TYPE.CV_LOAD_IMAGE_COLOR) Dim mImage As Emgu.CV.Structure.MIplImage = CType(System.Runtime.InteropServices.Marshal.PtrToStructure(rImage, GetType(Emgu.CV.Structure.MIplImage)), Emgu.CV.Structure.MIplImage) Dim RawData(mImage.width * mImage.height * mImage.nChannels) Dim TempData(mImage.imageSize) As Byte Marshal.Copy(mImage.imageData, TempData, 0, mImage.imageSize) Dim p = mImage.nChannels * mImage.width Dim w = mImage.width Dim h = mImage.height '转换成3通道图像 For y = 0 To h - 1 For x = 0 To w - 1 RawData(y * p + 3 * x) = TempData(3 * x + mImage.widthStep * y) RawData(y * p + 3 * x + 1) = TempData(3 * x + mImage.widthStep * y + 1) RawData(y * p + 3 * x + 2) = TempData(3 * x + mImage.widthStep * y + 2) Next Next Dim recttROI As New RECT recttROI.left = 0 recttROI.top = 0 recttROI.right = mImage.width - 1 recttROI.bottom = mImage.height - 1 Dim rectPlate As New RECT Dim rectTmp As New RECT Dim mnblePlate As Integer = 0 Dim HPHM(127) As Byte Dim rw As Integer = mImage.width Dim rh As Integer = mImage.height For i = 0 To 8 Dim result As Integer = LHD_Main(RawData(0), recttROI, rw, rh, HPHM(0), rectTmp, mnblePlate, i) 运行后在LHD_Main处报错: **尝试读取或写入受保护的内存。这通常指示其他内存已损坏。** 求问怎么解决!
C# 同时勾send 和 recv ,代码出错在哪里?
下面的代码,同时安装勾子会出错,现在的代码只能勾一个函数 private void Form1_Load(object sender, EventArgs e) { send_Hook.Install("ws2_32.dll", "send", Marshal.GetFunctionPointerForDelegate(new sendCallback(sendProc))); send_Hook.Install("ws2_32.dll", "recv", Marshal.GetFunctionPointerForDelegate(new recvCallback(toProc))); } 怎么才能即可接截Send,也可Recv 这里是完整代码 ``` 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; using System.Collections; using System.Runtime.InteropServices; using api_hook; namespace api_hook_封包学习 { public partial class Form1 : Form { [DllImport("ws2_32.dll")] static extern int send(int s, byte[] buf, int len, int flag); [DllImport("ws2_32.dll")] static extern int recv(int s, byte[] buf, int len, int flag); APIHOOK send_Hook = new APIHOOK(); delegate int sendCallback(int s, IntPtr buf, int len, int flag); delegate int recvCallback(int s, IntPtr buf, int len, int flag); public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { send_Hook.Install("ws2_32.dll", "send", Marshal.GetFunctionPointerForDelegate(new sendCallback(sendProc))); send_Hook.Install("ws2_32.dll", "recv", Marshal.GetFunctionPointerForDelegate(new recvCallback(toProc))); } int sendProc(int s, IntPtr buf, int len, int flag) { byte[] buffer = new byte[len]; Marshal.Copy(buf, buffer, 0, len); //读封包数据,读取后可进行条件修改,拦截,转发等,记得处理后调用发送 send_Hook.Suspend(); //暂停拦截,转交系统调用 int ret = send(s, buffer, len, flag); //发送数据,此处可进行拦截 send_Hook.Continue(); //恢复HOOK return ret; } int toProc(int s, IntPtr buf, int len, int flag) { byte[] buffer = new byte[len]; Marshal.Copy(buf, buffer, 0, len); //读封包数据 send_Hook.Suspend(); //暂停拦截,转交系统调用 int ret = recv(s, buffer, len, flag); //发送数据,此处可对包进行处理操作 send_Hook.Continue(); //恢复HOOK return ret; } private void button1_Click(object sender, EventArgs e)//按下时加载网页进行测试数据 { webBrowser1.Navigate("http://baidu.com"); } } //APIHOOK关键代码类 public class APIHOOK { #region Api声明 [DllImport("Kernel32.dll", EntryPoint = "GetModuleHandleA", CharSet = CharSet.Ansi)] static extern IntPtr GetModuleHandle( string lpModuleName ); [DllImport("Kernel32.dll")] static extern bool VirtualProtect( IntPtr lpAddress, int dwSize, int flNewProtect, ref int lpflOldProtect ); [DllImport("Kernel32.dll", EntryPoint = "lstrcpynA", CharSet = CharSet.Ansi)] static extern IntPtr lstrcpyn( byte[] lpString1, byte[] lpString2, int iMaxLength ); [DllImport("Kernel32.dll")] static extern IntPtr GetProcAddress( IntPtr hModule, string lpProcName ); [DllImport("Kernel32.dll")] static extern bool FreeLibrary( IntPtr hModule ); #endregion #region 常量定义表 const int PAGE_EXECUTE_READWRITE = 0x40; #endregion #region 变量表 IntPtr ProcAddress; int lpflOldProtect = 0; byte[] OldEntry = new byte[5]; byte[] NewEntry = new byte[5]; IntPtr OldAddress; #endregion public APIHOOK() { } public APIHOOK(string ModuleName, string ProcName, IntPtr lpAddress) { Install(ModuleName, ProcName, lpAddress); } public bool Install(string ModuleName, string ProcName, IntPtr lpAddress) { IntPtr hModule = GetModuleHandle(ModuleName); //取模块句柄 if (hModule == IntPtr.Zero) return false; ProcAddress = GetProcAddress(hModule, ProcName); //取入口地址 if (ProcAddress == IntPtr.Zero) return false; if (!VirtualProtect(ProcAddress, 5, PAGE_EXECUTE_READWRITE, ref lpflOldProtect)) return false; //修改内存属性 Marshal.Copy(ProcAddress, OldEntry, 0, 5); //读取前5字节 NewEntry = AddBytes(new byte[1] { 233 }, BitConverter.GetBytes((Int32)((Int32)lpAddress - (Int32)ProcAddress - 5))); //计算新入口跳转 Marshal.Copy(NewEntry, 0, ProcAddress, 5); //写入前5字节 OldEntry = AddBytes(OldEntry, new byte[5] { 233, 0, 0, 0, 0 }); OldAddress = lstrcpyn(OldEntry, OldEntry, 0); //取变量指针 Marshal.Copy(BitConverter.GetBytes((double)((Int32)ProcAddress - (Int32)OldAddress - 5)), 0, (IntPtr)(OldAddress.ToInt32() + 6), 4); //保存JMP FreeLibrary(hModule); //释放模块句柄 return true; } public void Suspend() { Marshal.Copy(OldEntry, 0, ProcAddress, 5); } public void Continue() { Marshal.Copy(NewEntry, 0, ProcAddress, 5); } public bool Uninstall() { if (ProcAddress == IntPtr.Zero) return false; Marshal.Copy(OldEntry, 0, ProcAddress, 5); ProcAddress = IntPtr.Zero; return true; } static byte[] AddBytes(byte[] a, byte[] b) { ArrayList retArray = new ArrayList(); for (int i = 0; i < a.Length; i++) { retArray.Add(a[i]); } for (int i = 0; i < b.Length; i++) { retArray.Add(b[i]); } return (byte[])retArray.ToArray(typeof(byte)); } } } ```
《MySQL 性能优化》之理解 MySQL 体系结构
本文介绍 MySQL 的体系结构,包括物理结构、逻辑结构以及插件式存储引擎。
程序员请照顾好自己,周末病魔差点一套带走我。
程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。
卸载 x 雷某度!GitHub 标星 1.5w+,从此我只用这款全能高速下载工具!
作者 | Rocky0429 来源 | Python空间 大家好,我是 Rocky0429,一个喜欢在网上收集各种资源的蒟蒻… 网上资源眼花缭乱,下载的方式也同样千奇百怪,比如 BT 下载,磁力链接,网盘资源等等等等,下个资源可真不容易,不一样的方式要用不同的下载软件,因此某比较有名的 x 雷和某度网盘成了我经常使用的工具。 作为一个没有钱的穷鬼,某度网盘几十 kb 的下载速度让我...
Python+OpenCV实时图像处理
目录 1、导入库文件 2、设计GUI 3、调用摄像头 4、实时图像处理 4.1、阈值二值化 4.2、边缘检测 4.3、轮廓检测 4.4、高斯滤波 4.5、色彩转换 4.6、调节对比度 5、退出系统 初学OpenCV图像处理的小伙伴肯定对什么高斯函数、滤波处理、阈值二值化等特性非常头疼,这里给各位分享一个小项目,可通过摄像头实时动态查看各类图像处理的特点,也可对各位调参、测试...
2020年一线城市程序员工资大调查
人才需求 一线城市共发布岗位38115个,招聘120827人。 其中 beijing 22805 guangzhou 25081 shanghai 39614 shenzhen 33327 工资分布 2020年中国一线城市程序员的平均工资为16285元,工资中位数为14583元,其中95%的人的工资位于5000到20000元之间。 和往年数据比较: yea...
为什么猝死的都是程序员,基本上不见产品经理猝死呢?
相信大家时不时听到程序员猝死的消息,但是基本上听不到产品经理猝死的消息,这是为什么呢? 我们先百度搜一下:程序员猝死,出现将近700多万条搜索结果: 搜索一下:产品经理猝死,只有400万条的搜索结果,从搜索结果数量上来看,程序员猝死的搜索结果就比产品经理猝死的搜索结果高了一倍,而且从下图可以看到,首页里面的五条搜索结果,其实只有两条才是符合条件。 所以程序员猝死的概率真的比产品经理大,并不是错...
害怕面试被问HashMap?这一篇就搞定了!
声明:本文以jdk1.8为主! 搞定HashMap 作为一个Java从业者,面试的时候肯定会被问到过HashMap,因为对于HashMap来说,可以说是Java集合中的精髓了,如果你觉得自己对它掌握的还不够好,我想今天这篇文章会非常适合你,至少,看了今天这篇文章,以后不怕面试被问HashMap了 其实在我学习HashMap的过程中,我个人觉得HashMap还是挺复杂的,如果真的想把它搞得明明白...
毕业5年,我问遍了身边的大佬,总结了他们的学习方法
我问了身边10个大佬,总结了他们的学习方法,原来成功都是有迹可循的。
python爬取百部电影数据,我分析出了一个残酷的真相
2019年就这么匆匆过去了,就在前几天国家电影局发布了2019年中国电影市场数据,数据显示去年总票房为642.66亿元,同比增长5.4%;国产电影总票房411.75亿元,同比增长8.65%,市场占比 64.07%;城市院线观影人次17.27亿,同比增长0.64%。 看上去似乎是一片大好对不对?不过作为一名严谨求实的数据分析师,我从官方数据中看出了一点端倪:国产票房增幅都已经高达8.65%了,为什...
推荐10个堪称神器的学习网站
每天都会收到很多读者的私信,问我:“二哥,有什么推荐的学习网站吗?最近很浮躁,手头的一些网站都看烦了,想看看二哥这里有什么新鲜货。” 今天一早做了个恶梦,梦到被老板辞退了。虽然说在我们公司,只有我辞退老板的份,没有老板辞退我这一说,但是还是被吓得 4 点多都起来了。(主要是因为我掌握着公司所有的核心源码,哈哈哈) 既然 4 点多起来,就得好好利用起来。于是我就挑选了 10 个堪称神器的学习网站,推...
这些软件太强了,Windows必装!尤其程序员!
Windows可谓是大多数人的生产力工具,集娱乐办公于一体,虽然在程序员这个群体中都说苹果是信仰,但是大部分不都是从Windows过来的,而且现在依然有很多的程序员用Windows。 所以,今天我就把我私藏的Windows必装的软件分享给大家,如果有一个你没有用过甚至没有听过,那你就赚了????,这可都是提升你幸福感的高效率生产力工具哦! 走起!???? NO、1 ScreenToGif 屏幕,摄像头和白板...
阿里面试,面试官没想到一个ArrayList,我都能跟他扯半小时
我是真的没想到,面试官会这样问我ArrayList。
曾经优秀的人,怎么就突然不优秀了。
职场上有很多辛酸事,很多合伙人出局的故事,很多技术骨干被裁员的故事。说来模板都类似,曾经是名校毕业,曾经是优秀员工,曾经被领导表扬,曾经业绩突出,然而突然有一天,因为种种原因,被裁员了,...
大学四年因为知道了这32个网站,我成了别人眼中的大神!
依稀记得,毕业那天,我们导员发给我毕业证的时候对我说“你可是咱们系的风云人物啊”,哎呀,别提当时多开心啦????,嗯,我们导员是所有导员中最帅的一个,真的???? 不过,导员说的是实话,很多人都叫我大神的,为啥,因为我知道这32个网站啊,你说强不强????,这次是绝对的干货,看好啦,走起来! PS:每个网站都是学计算机混互联网必须知道的,真的牛杯,我就不过多介绍了,大家自行探索,觉得没用的,尽管留言吐槽吧???? 社...
良心推荐,我珍藏的一些Chrome插件
上次搬家的时候,发了一个朋友圈,附带的照片中不小心暴露了自己的 Chrome 浏览器插件之多,于是就有小伙伴评论说分享一下我觉得还不错的浏览器插件。 我下面就把我日常工作和学习中经常用到的一些 Chrome 浏览器插件分享给大家,随便一个都能提高你的“生活品质”和工作效率。 Markdown Here Markdown Here 可以让你更愉快的写邮件,由于支持 Markdown 直接转电子邮...
看完这篇HTTP,跟面试官扯皮就没问题了
我是一名程序员,我的主要编程语言是 Java,我更是一名 Web 开发人员,所以我必须要了解 HTTP,所以本篇文章就来带你从 HTTP 入门到进阶,看完让你有一种恍然大悟、醍醐灌顶的感觉。 最初在有网络之前,我们的电脑都是单机的,单机系统是孤立的,我还记得 05 年前那会儿家里有个电脑,想打电脑游戏还得两个人在一个电脑上玩儿,及其不方便。我就想为什么家里人不让上网,我的同学 xxx 家里有网,每...
剑指Offer对答如流系列 - 重建二叉树
面试题6:重建二叉树 题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建出图2.6所示的二叉树并输出它的头结点。二叉树结点的定义如下: class TreeNode{ int val; TreeNode l...
史上最全的IDEA快捷键总结
现在Idea成了主流开发工具,这篇博客对其使用的快捷键做了总结,希望对大家的开发工作有所帮助。
阿里程序员写了一个新手都写不出的低级bug,被骂惨了。
这种新手都不会范的错,居然被一个工作好几年的小伙子写出来,差点被当场开除了。
谁是华为扫地僧?
是的,华为也有扫地僧!2020年2月11-12日,“养在深闺人不知”的华为2012实验室扫地僧们,将在华为开发者大会2020(Cloud)上,和大家见面。到时,你可以和扫地僧们,吃一个洋...
AI 没让人类失业,搞 AI 的人先失业了
最近和几个 AI 领域的大佬闲聊 根据他们讲的消息和段子 改编出下面这个故事 如有雷同 都是巧合 1. 老王创业失败,被限制高消费 “这里写我跑路的消息实在太夸张了。” 王葱葱哼笑一下,把消息分享给群里。 阿杰也看了消息,笑了笑。在座几位也都笑了。 王葱葱是个有名的人物,21岁那年以全额奖学金进入 KMU 攻读人工智能博士,累计发表论文 40 余篇,个人技术博客更是成为深度学习领域内风向标。 ...
2020年,冯唐49岁:我给20、30岁IT职场年轻人的建议
点击“技术领导力”关注∆每天早上8:30推送 作者|Mr.K 编辑| Emma 来源|技术领导力(ID:jishulingdaoli) 前天的推文《冯唐:职场人35岁以后,方法论比经验重要》,收到了不少读者的反馈,觉得挺受启发。其实,冯唐写了不少关于职场方面的文章,都挺不错的。可惜大家只记住了“春风十里不如你”、“如何避免成为油腻腻的中年人”等不那么正经的文章。 本文整理了冯...
一份王者荣耀的英雄数据报告
咪哥杂谈本篇阅读时间约为 6 分钟。1前言前一阵写了关于王者的一些系列文章,从数据的获取到数据清洗,数据落地,都是为了本篇的铺垫。今天来实现一下,看看不同维度得到的结论。2环境准备本次实...
作为一名大学生,如何在B站上快乐的学习?
B站是个宝,谁用谁知道???? 作为一名大学生,你必须掌握的一项能力就是自学能力,很多看起来很牛X的人,你可以了解下,人家私底下一定是花大量的时间自学的,你可能会说,我也想学习啊,可是嘞,该学习啥嘞,不怕告诉你,互联网时代,最不缺的就是学习资源,最宝贵的是啥? 你可能会说是时间,不,不是时间,而是你的注意力,懂了吧! 那么,你说学习资源多,我咋不知道,那今天我就告诉你一个你必须知道的学习的地方,人称...
那些年,我们信了课本里的那些鬼话
教材永远都是有错误的,从小学到大学,我们不断的学习了很多错误知识。 斑羚飞渡 在我们学习的很多小学课文里,有很多是错误文章,或者说是假课文。像《斑羚飞渡》: 随着镰刀头羊的那声吼叫,整个斑羚群迅速分成两拨,老年斑羚为一拨,年轻斑羚为一拨。 就在这时,我看见,从那拨老斑羚里走出一只公斑羚来。公斑羚朝那拨年轻斑羚示意性地咩了一声,一只半大的斑羚应声走了出来。一老一少走到伤心崖,后退了几步,突...
一个程序在计算机中是如何运行的?超级干货!!!
强烈声明:本文很干,请自备茶水!???? 开门见山,咱不说废话! 你有没有想过,你写的程序,是如何在计算机中运行的吗?比如我们搞Java的,肯定写过这段代码 public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } ...
【蘑菇街技术部年会】程序员与女神共舞,鼻血再次没止住。(文末内推)
蘑菇街技术部的年会,别开生面,一样全是美女。
那个在阿里养猪的工程师,5年了……
简介: 在阿里,走过1825天,没有趴下,依旧斗志满满,被称为“五年陈”。他们会被授予一枚戒指,过程就叫做“授戒仪式”。今天,咱们听听阿里的那些“五年陈”们的故事。 下一个五年,猪圈见! 我就是那个在养猪场里敲代码的工程师,一年多前我和20位工程师去了四川的猪场,出发前总架构师慷慨激昂的说:同学们,中国的养猪产业将因为我们而改变。但到了猪场,发现根本不是那么回事:要个WIFI,没有;...
为什么程序猿都不愿意去外包?
分享外包的组织架构,盈利模式,亲身经历,以及根据一些外包朋友的反馈,写了这篇文章 ,希望对正在找工作的老铁有所帮助
Java校招入职华为,半年后我跑路了
何来 我,一个双非本科弟弟,有幸在 19 届的秋招中得到前东家华为(以下简称 hw)的赏识,当时秋招签订就业协议,说是入了某 java bg,之后一系列组织架构调整原因等等让人无法理解的神操作,最终毕业前夕,被通知调往其他 bg 做嵌入式开发(纯 C 语言)。 由于已至于校招末尾,之前拿到的其他 offer 又无法再收回,一时感到无力回天,只得默默接受。 毕业后,直接入职开始了嵌入式苦旅,由于从未...
立即提问