<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>爱人-爱人的大杂烩 &#187; 程序设计</title>
	<atom:link href="http://ai-2.cn/category/programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://ai-2.cn</link>
	<description>一切研究的资料库</description>
	<lastBuildDate>Thu, 09 Sep 2010 06:15:07 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>强大的图片验证码识别代码</title>
		<link>http://ai-2.cn/2010/03/validcodeshibie/</link>
		<comments>http://ai-2.cn/2010/03/validcodeshibie/#comments</comments>
		<pubDate>Mon, 08 Mar 2010 07:55:02 +0000</pubDate>
		<dc:creator>csecong</dc:creator>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[图片验证码]]></category>
		<category><![CDATA[字符识别]]></category>
		<category><![CDATA[验证码识别]]></category>

		<guid isPermaLink="false">http://ai-2.cn/?p=213</guid>
		<description><![CDATA[今天想刷个投票页面，需要识别验证码，网上搜啊，找到一个图片验证码识别类，改动一下用起来很舒服啊^_^ 因为每种类验证码的字符表都不一样，所以需要事先得到此种验证码的字符表 方法呢，就是在调试模式输出一下就看到了 代码如下 UnCodeBase.cs using System; using System.Collections.Generic; using System.Text; using System.Collections; using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices; namespace BallotAiying2 { class UnCodebase { public Bitmap bmpobj; public UnCodebase(Bitmap pic) { // if (pic.PixelFormat == PixelFormat.Format8bppIndexed) bmpobj = new Bitmap(pic); //转换为Format32bppRgb } /// /// 根据RGB，计算灰度值 /// /// Color值 /// 灰度值，整型 private int GetGrayNumColor(System.Drawing.Color posClr) [...]]]></description>
			<content:encoded><![CDATA[<p>今天想刷个投票页面，需要识别验证码，网上搜啊，找到一个图片验证码识别类，改动一下用起来很舒服啊^_^<br />
因为每种类验证码的字符表都不一样，所以需要事先得到此种验证码的字符表<br />
方法呢，就是在调试模式输出一下就看到了<br />
代码如下<br />
UnCodeBase.cs</p>
<pre lang="C#" line="1">using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;

namespace BallotAiying2
{
    class UnCodebase
    {
        public Bitmap bmpobj;
        public UnCodebase(Bitmap pic)
        {
            //       if (pic.PixelFormat == PixelFormat.Format8bppIndexed)
            bmpobj = new Bitmap(pic);    //转换为Format32bppRgb
        }

        ///
<summary>
        /// 根据RGB，计算灰度值
        /// </summary>

        ///
<param name="posClr">Color值</param>
        /// <returns>灰度值，整型</returns>
        private int GetGrayNumColor(System.Drawing.Color posClr)
        {
            return (posClr.R * 19595 + posClr.G * 38469 + posClr.B * 7472) >> 16;
        }

        ///
<summary>
        /// 灰度转换,逐点方式
        /// </summary>

        public void GrayByPixels()
        {
            for (int i = 0; i < bmpobj.Height; i++)
            {
                for (int j = 0; j < bmpobj.Width; j++)
                {
                    int tmpValue = GetGrayNumColor(bmpobj.GetPixel(j, i));
                    bmpobj.SetPixel(j, i, Color.FromArgb(tmpValue, tmpValue, tmpValue));
                }
            }
        }

        ///
<summary>
        /// 去图形边框
        /// </summary>

        ///
<param name="borderWidth"></param>
        public void ClearPicBorder(int borderWidth)
        {
            for (int i = 0; i < bmpobj.Height; i++)
            {
                for (int j = 0; j < bmpobj.Width; j++)
                {
                    if (i < borderWidth || j < borderWidth || j > bmpobj.Width - 1 - borderWidth || i > bmpobj.Height - 1 - borderWidth)
                        bmpobj.SetPixel(j, i, Color.FromArgb(255, 255, 255));
                }
            }
        }

        ///
<summary>
        /// 灰度转换,逐行方式
        /// </summary>

        public void GrayByLine()
        {
            Rectangle rec = new Rectangle(0, 0, bmpobj.Width, bmpobj.Height);
            BitmapData bmpData = bmpobj.LockBits(rec, ImageLockMode.ReadWrite, bmpobj.PixelFormat);// PixelFormat.Format32bppPArgb);
            //    bmpData.PixelFormat = PixelFormat.Format24bppRgb;
            IntPtr scan0 = bmpData.Scan0;
            int len = bmpobj.Width * bmpobj.Height;
            int[] pixels = new int[len];
            Marshal.Copy(scan0, pixels, 0, len);

            //对图片进行处理
            int GrayValue = 0;
            for (int i = 0; i < len; i++)
            {
                GrayValue = GetGrayNumColor(Color.FromArgb(pixels[i]));
                pixels[i] = (byte)(Color.FromArgb(GrayValue, GrayValue, GrayValue)).ToArgb();      //Color转byte
            }

            bmpobj.UnlockBits(bmpData);

            ////输出
            //GCHandle gch = GCHandle.Alloc(pixels, GCHandleType.Pinned);
            //bmpOutput = new Bitmap(bmpobj.Width, bmpobj.Height, bmpData.Stride, bmpData.PixelFormat, gch.AddrOfPinnedObject());
            //gch.Free();
        }

        ///
<summary>
        /// 得到有效图形并调整为可平均分割的大小
        /// </summary>

        ///
<param name="dgGrayValue">灰度背景分界值</param>
        ///
<param name="CharsCount">有效字符数</param>
        /// <returns></returns>
        public void GetPicValidByValue(int dgGrayValue, int CharsCount)
        {
            int posx1 = bmpobj.Width; int posy1 = bmpobj.Height;
            int posx2 = 0; int posy2 = 0;
            for (int i = 0; i < bmpobj.Height; i++)      //找有效区
            {
                for (int j = 0; j < bmpobj.Width; j++)
                {
                    int pixelValue = bmpobj.GetPixel(j, i).R;
                    if (pixelValue < dgGrayValue)     //根据灰度值
                    {
                        if (posx1 > j) posx1 = j;
                        if (posy1 > i) posy1 = i;

                        if (posx2 < j) posx2 = j;
                        if (posy2 < i) posy2 = i;
                    };
                };
            };
            // 确保能整除
            int Span = CharsCount - (posx2 - posx1 + 1) % CharsCount;   //可整除的差额数
            if (Span < CharsCount)
            {
                int leftSpan = Span / 2;    //分配到左边的空列 ，如span为单数,则右边比左边大1
                if (posx1 > leftSpan)
                    posx1 = posx1 - leftSpan;
                if (posx2 + Span - leftSpan < bmpobj.Width)
                    posx2 = posx2 + Span - leftSpan;
            }
            //复制新图
            Rectangle cloneRect = new Rectangle(posx1, posy1, posx2 - posx1 + 1, posy2 - posy1 + 1);
            bmpobj = bmpobj.Clone(cloneRect, bmpobj.PixelFormat);
        }

        ///
<summary>
        /// 得到有效图形,图形为类变量
        /// </summary>

        ///
<param name="dgGrayValue">灰度背景分界值</param>
        ///
<param name="CharsCount">有效字符数</param>
        /// <returns></returns>
        public void GetPicValidByValue(int dgGrayValue)
        {
            int posx1 = bmpobj.Width; int posy1 = bmpobj.Height;
            int posx2 = 0; int posy2 = 0;
            for (int i = 0; i < bmpobj.Height; i++)      //找有效区
            {
                for (int j = 0; j < bmpobj.Width; j++)
                {
                    int pixelValue = bmpobj.GetPixel(j, i).R;
                    if (pixelValue < dgGrayValue)     //根据灰度值
                    {
                        if (posx1 > j) posx1 = j;
                        if (posy1 > i) posy1 = i;

                        if (posx2 < j) posx2 = j;
                        if (posy2 < i) posy2 = i;
                    };
                };
            };
            //复制新图
            Rectangle cloneRect = new Rectangle(posx1, posy1, posx2 - posx1 + 1, posy2 - posy1 + 1);
            bmpobj = bmpobj.Clone(cloneRect, bmpobj.PixelFormat);
        }

        ///
<summary>
        /// 得到有效图形,图形由外面传入
        /// </summary>

        ///
<param name="dgGrayValue">灰度背景分界值</param>
        ///
<param name="CharsCount">有效字符数</param>
        /// <returns></returns>
        public Bitmap GetPicValidByValue(Bitmap singlepic, int dgGrayValue)
        {
            int posx1 = singlepic.Width; int posy1 = singlepic.Height;
            int posx2 = 0; int posy2 = 0;
            for (int i = 0; i < singlepic.Height; i++)      //找有效区
            {
                for (int j = 0; j < singlepic.Width; j++)
                {
                    int pixelValue = singlepic.GetPixel(j, i).R;
                    if (pixelValue < dgGrayValue)     //根据灰度值
                    {
                        if (posx1 > j) posx1 = j;
                        if (posy1 > i) posy1 = i;

                        if (posx2 < j) posx2 = j;
                        if (posy2 < i) posy2 = i;
                    };
                };
            };
            //复制新图
            Rectangle cloneRect = new Rectangle(posx1, posy1, posx2 - posx1 + 1, posy2 - posy1 + 1);
            return singlepic.Clone(cloneRect, singlepic.PixelFormat);
        }

        ///
<summary>
        /// 平均分割图片
        /// </summary>

        ///
<param name="RowNum">水平上分割数</param>
        ///
<param name="ColNum">垂直上分割数</param>
        /// <returns>分割好的图片数组</returns>
        public Bitmap [] GetSplitPics(int RowNum,int ColNum)
        {
            if (RowNum == 0 || ColNum == 0)
                return null;
            int singW = bmpobj.Width / RowNum;
            int singH = bmpobj.Height / ColNum;
            Bitmap [] PicArray=new Bitmap[RowNum*ColNum];

            Rectangle cloneRect;
            for (int i = 0; i < ColNum; i++)      //找有效区
            {
                for (int j = 0; j < RowNum; j++)
                {
                    cloneRect = new Rectangle(j*singW, i*singH, singW , singH);
                    PicArray[i*RowNum+j]=bmpobj.Clone(cloneRect, bmpobj.PixelFormat);//复制小块图
                }
            }
            return PicArray;
        }

        ///
<summary>
        /// 返回灰度图片的点阵描述字串，1表示灰点，0表示背景
        /// </summary>

        ///
<param name="singlepic">灰度图</param>
        ///
<param name="dgGrayValue">背前景灰色界限</param>
        /// <returns></returns>
        public string GetSingleBmpCode(Bitmap singlepic, int dgGrayValue)
        {
            Color piexl;
            string code = "";
            for (int posy = 0; posy < singlepic.Height; posy++)
                for (int posx = 0; posx < singlepic.Width; posx++)
                {
                    piexl = singlepic.GetPixel(posx, posy);
                    if (piexl.R < dgGrayValue)    // Color.Black )
                        code = code + "1";
                    else
                        code = code + "0";
                }
            return code;
        }

    }

}</pre>
<p>unCodeAiYing.cs</p>
<pre lang="C#" line="1">using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;

namespace BallotAiying2
{
    class unCodeAiYing : UnCodebase
    {
        //字符表
        string[,] CodeArray = new string[,] {{"1","00100111000010000100001000010000100001000010011111"},
{"4","000100000100001100010100100100100100111111000100000100001111"},
{"B","1111110010000101000010100010011110001000100100001010000101000011111110"},
{"N","1110111011001001100100101010010101001010100100110010011001001101110010"},
{"0","011110100001100001101101101101101101101101100001100001011110"},
{"M","111011011011011011011011010101010101010101010101010101110101"},
{"F","1111110010000101001000100100011110001001000100100010000001000001110000"},
{"E","1111110010000101001000100100011110001001000100100010000001000011111110"},
{"A","0001000000100000101000010100001010000101000111110010001001000101110111"},
{"G","001111010001100001100000100000100000100011100001010001001110"},
{"K","1110111010001001001000101000011100001010000100100010010001000101110111"},
{"T","1111111100100100010000001000000100000010000001000000100000010000011100"},
{"C","0011111010000110000011000000100000010000001000000100000101000100011100"},
{"4","00010000100011001010100101001011111000100001000111"},
{"9","011100100010100001100001100011011101000001000001100010011100"},
{"S","011111100001100001100000011000000110000001100001100001111110"},
{"Z","111111100010000010000100000100001000001000010000010001111111"},
{"3","011110100001100001000010001100000010000001100001100001011110"},
{"M","1110111011011001101100110110010101001010100101010010101001010101101011"},
{"Q","0011100010001010000011000001100000110000011000001101100101001100011101"},
{"L","1110000010000001000000100000010000001000000100000010000001000011111111"},
{"W","1101011010101001010100101010010101001101100010100001010000101000010100"},
{"D","111110010001010000010000010000010000010000010000010001111110"},
{"I","11111001000010000100001000010000100001000010011111"},
{"U","1110111010001001000100100010010001001000100100010010001001000100011100"},
{"6","00111010001000010000101111100010000100001000001111"},
{"B","111111010000010000010001011110010001010000010000010000111111"},
{"8","011110100001100001100001011110010010100001100001100001011110"},
{"P","1111110010000101000010100001011111001000000100000010000001000001110000"},
{"N","111011011001011001010101010101010101010011010011010011111001"},
{"X","1110111010001000101000010100000100000010000010100001010001000101110111"},
{"X","111011010001001010001010000100000100001010001010010001111011"},
{"D","1111100010001001000010100001010000101000010100001010000101000101111100"},
{"U","111011010001010001010001010001010001010001010001010001001110"},
{"H","1110111010001001000100100010011111001000100100010010001001000101110111"},
{"R","1111100010001001000100100010011110001010000100100010010001000101110011"},
{"V","111011010001010001010001001010001010001010001010000100000100"},
{"O","0011100010001010000011000001100000110000011000001100000101000100011100"},
{"T","111111100100000100000100000100000100000100000100000100001110"},
{"2","011110100001100001000001000010000100001000010000100001111111"},
{"6","001110010001100000100000101110110001100001100001100001011110"},
{"Z","11111100010000100010000100010000100010000100011111"},
{"Y","111011010001010001001010001010000100000100000100000100001110"},
{"Y","1110111010001001000100010100001010000010000001000000100000010000011100"},
{"5","11111100001000010111110000000000000100001000001111"},
{"R","111110010001010001010001011110010100010010010010010001111001"},
{"W","110101010101010101010101010101011011001010001010001010001010"},
{"H","111011010001010001010001011111010001010001010001010001111011"},
{"5","111111100000100000101110110001000001000001100001100001011110"},
{"V","1110111010001001000100100010001010000101000010100001010000010000001000"},
{"J","001111000010000010000010000010000010000010000010100010111100"},
{"7","111111100010100010000100000100001000001000001000001000001000"},
{"O","001110010001100000100000100000100000100000100000010001001110"},
{"F","111111010000010010010010011110010010010010010000010000111000"},
{"C","001111010000100000100000100000100000100000100000010001001110"},
{"Q","001110010001100000100000100000100000100000101100010011001110"},
{"J","0011111000010000001000000100000010000001000000100000010010001001111000"},
{"9","01110100011000010000100010111000000000001000101110"}};

        public unCodeAiYing(Bitmap pic)
            : base(pic)
        {
        }

        public string getPicnum()
        {
            GrayByPixels(); //灰度处理
            GetPicValidByValue(128, 4); //得到有效空间
            Bitmap[] pics = GetSplitPics(4, 1);     //分割

            if (pics.Length != 4)
            {
                return ""; //分割错误
            }
            else  // 重新调整大小
            {
                pics[0] = GetPicValidByValue(pics[0], 128);
                pics[1] = GetPicValidByValue(pics[1], 128);
                pics[2] = GetPicValidByValue(pics[2], 128);
                pics[3] = GetPicValidByValue(pics[3], 128);
            }

            //      if (!textBoxInput.Text.Equals(""))
            string result = "";
            string dddd = "";
            char singleChar = ' ';
            {
                for (int i = 0; i < 4; i++)
                {
                    string code = GetSingleBmpCode(pics[i], 128);   //得到代码串
                    System.Diagnostics.Debug.WriteLine(code);
                    for (int arrayIndex = 0; arrayIndex < CodeArray.Length/2; arrayIndex++)
                    {
                        if (CodeArray[arrayIndex,1].Equals(code))  //相等
                        {
                            dddd = CodeArray[arrayIndex, 0];
                            //if (arrayIndex < 10)   // 0..9
                            //    singleChar = (char)(48 + arrayIndex);
                            //else if (arrayIndex < 36) //A..Z
                            //    singleChar = (char)(65 + arrayIndex - 10);
                            //else
                            //    singleChar = (char)(97 + arrayIndex - 36);
                            //result = result + singleChar;
                            result = result + dddd;
                        }
                    }
                }
            }
           return result;
        }
    }
}</pre>
<p>使用方式</p>
<pre lang="C#" line="1">HtmlDocument doc = webBrowser1.Document;
              //  IHTMLDocument2 doc2 = (IHTMLDocument2)webBrowser1.Document.DomDocument;
                //      HtmlElement ImgeTag =(HtmlElement) doc2.images.item(0, 0);

                HtmlElement ImgeTag = doc.Forms[0].GetElementsByTagName("IMG")[0];

                Image numPic = GetWebImage(webBrowser1, ImgeTag); // 得到验证码图片
                pictureBox1.Image = numPic;
                unCodeAiYing UnCheckobj = new unCodeAiYing((Bitmap)numPic);
                string strNum = UnCheckobj.getPicnum();     //识别图片
                System.Diagnostics.Debug.WriteLine(strNum);
                for (int i = 0; i < doc.All.Count; i++)
                {
                    if (doc.All[i].TagName.ToUpper().Equals("INPUT"))
                    {
                        switch (doc.All[i].Name)
                        {
                            case "Vcode":
                                doc.All[i].InnerText = strNum;
                                break;
                            case "Submit":
                                ClickBtn = doc.All[i]; //提交
                                break;
                        }
                    }

                }
                ClickBtn.InvokeMember("Click");   //执行按扭操作</pre>
]]></content:encoded>
			<wfw:commentRss>http://ai-2.cn/2010/03/validcodeshibie/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>手机手写笔长按动作消息事件响应</title>
		<link>http://ai-2.cn/2009/09/wm_lbuttondown/</link>
		<comments>http://ai-2.cn/2009/09/wm_lbuttondown/#comments</comments>
		<pubDate>Fri, 11 Sep 2009 04:51:51 +0000</pubDate>
		<dc:creator>csecong</dc:creator>
				<category><![CDATA[vb.net]]></category>
		<category><![CDATA[右键菜单]]></category>
		<category><![CDATA[手写笔长按]]></category>
		<category><![CDATA[手机右键]]></category>

		<guid isPermaLink="false">http://ai-2.cn/?p=184</guid>
		<description><![CDATA[如何响应手写笔长按动作消息，一开始走了弯路，想到用API拦截，其实很简单的 只要绑定右键菜单就可以了^_^ 因为手机手写笔不分左右键，所以点击代表左键单击，长按代表右键单击]]></description>
			<content:encoded><![CDATA[<p>如何响应手写笔长按动作消息，一开始走了弯路，想到用API拦截，其实很简单的</p>
<p>只要绑定右键菜单就可以了^_^</p>
<p>因为手机手写笔不分左右键，所以点击代表左键单击，长按代表右键单击</p>
]]></content:encoded>
			<wfw:commentRss>http://ai-2.cn/2009/09/wm_lbuttondown/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>定时自动刷新页面工具</title>
		<link>http://ai-2.cn/2009/06/autorefreshurl/</link>
		<comments>http://ai-2.cn/2009/06/autorefreshurl/#comments</comments>
		<pubDate>Wed, 24 Jun 2009 02:14:52 +0000</pubDate>
		<dc:creator>csecong</dc:creator>
				<category><![CDATA[vb.net]]></category>
		<category><![CDATA[站长工具]]></category>
		<category><![CDATA[自动刷新]]></category>

		<guid isPermaLink="false">http://ai-2.cn/?p=114</guid>
		<description><![CDATA[昨天碰到个网站，要靠在线时间兑换点数才能下载这个网站的资料，所以做了个自动刷新页面的小工具，每隔几分钟刷新一下页面来防止自动退出登陆，功能相当简单。]]></description>
			<content:encoded><![CDATA[<p>昨天碰到个网站，要靠在线时间兑换点数才能下载这个网站的资料，所以做了个自动刷新页面的小工具，每隔几分钟刷新一下页面来防止自动退出登陆，功能相当简单。</p>
<div id="attachment_118" class="wp-caption alignnone" style="width: 620px"><img class="size-full wp-image-118" title="自动刷新页面工具" src="http://ai-2.cn/wp-content/uploads/2009/06/autoRefresh.gif" alt="自动刷新页面工具" width="610" height="317" /><p class="wp-caption-text">自动刷新页面工具</p></div>
<p><a title="定时刷新页面工具" href="http://www.ai-2.cn/tools/AutoRefresh.exe" target="_blank">点击这里下载AutoRefresh.exe</a></p>
<pre lang="vb.net">Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If Button1.Text = "开始" Then
Timer1.Interval = TextBox1.Text * 60 * 1000
Timer1.Enabled = True
Button1.Text = "结束"
Else
Timer1.Enabled = False
Button1.Text = "开始"
End If
End Sub

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
WebBrowser1.Refresh()
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

WebBrowser1.Navigate(TextBox2.Text)
End Sub

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
TextBox2.AutoCompleteSource = AutoCompleteSource.HistoryList
WebBrowser1.Navigate("http://ai-2.cn")
End Sub

Private Sub LinkLabel1_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
System.Diagnostics.Process.Start("http://ai-2.cn")
End Sub

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
WebBrowser1.Refresh()
End Sub
End Class</pre>
]]></content:encoded>
			<wfw:commentRss>http://ai-2.cn/2009/06/autorefreshurl/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>使用ContentTableAdapter和DataDataSet操作数据库</title>
		<link>http://ai-2.cn/2008/09/contenttableadapter_datadataset/</link>
		<comments>http://ai-2.cn/2008/09/contenttableadapter_datadataset/#comments</comments>
		<pubDate>Fri, 26 Sep 2008 03:20:54 +0000</pubDate>
		<dc:creator>csecong</dc:creator>
				<category><![CDATA[vb.net]]></category>
		<category><![CDATA[contenttableadapter]]></category>
		<category><![CDATA[datadataset]]></category>
		<category><![CDATA[datagridview]]></category>
		<category><![CDATA[sql]]></category>
		<category><![CDATA[数据库]]></category>
		<category><![CDATA[源码]]></category>
		<category><![CDATA[自动发帖]]></category>

		<guid isPermaLink="false">http://ai-2.cn/?p=63</guid>
		<description><![CDATA[vb6.0时代，我们要使用数据库，还需要先引入ado组件，然后使用 Provider=Microsoft.Jet.OLEDB.4.0;Data Source=data.mdb，然后conn.open的方式操作数据库，现在不需要了，直接使用ContentTableAdapter和 DataDataSet就能完成了，简单、方便、快捷]]></description>
			<content:encoded><![CDATA[<p>使用工具Visual Studio 2005</p>
<p>vb6.0时代，我们要使用数据库，还需要先引入ado组件，然后使用 Provider=Microsoft.Jet.OLEDB.4.0;Data Source=data.mdb，然后conn.open的方式操作数据库，现在不需要了，直接使用ContentTableAdapter和 DataDataSet就能完成了，简单、方便、快捷</p>
<p>首先，将数据库加入程序中，在解决方案资源管理器里项目名称上点右键，选择添加，选择现有项，然后找到你要的数据库文件，添加进入<br />
<a href="http://www.ai-2.cn/attachment/da001.gif" target="_blank"><img class="insertimage" title="点击在新窗口中浏览此图片" src="http://www.ai-2.cn/attachment/da001.gif" border="0" alt="点击在新窗口中浏览此图片" width="450" height="294" /></a><br />
然后会弹出数据源配置向导，将你需要的数据表打上钩<br />
<a href="http://www.ai-2.cn/attachment/da002.gif" target="_blank"><img class="insertimage" title="点击在新窗口中浏览此图片" src="http://www.ai-2.cn/attachment/da002.gif" border="0" alt="点击在新窗口中浏览此图片" width="450" height="294" /></a><br />
然后点击完成，ok，解决方法资源管理器里会自动添加上dataDataSet.xsd文件，数据源添加完成<br />
，然后双击打开dataDataSet.xsd文件<br />
<a href="http://www.ai-2.cn/attachment/da003.gif" target="_blank"><img class="insertimage" title="点击在新窗口中浏览此图片" src="http://www.ai-2.cn/attachment/da003.gif" border="0" alt="点击在新窗口中浏览此图片" /></a><br />
出现当前的数据源，分为两部分，上面是表结构，下面是数据库命令，命令里已经默认添加了一个fill,GetData()，这个命令是列出数据库中对应表中的所有数据<br />
我们可以自己添加需要的sql命令了<br />
在这里点击右键，选择添加-&gt;query，进入向导页，因为我们用的access数据库，所以只有一个，使用sql语句来加载数据<br />
<a href="http://www.ai-2.cn/attachment/da004.gif" target="_blank"><img class="insertimage" title="点击在新窗口中浏览此图片" src="http://www.ai-2.cn/attachment/da004.gif" border="0" alt="点击在新窗口中浏览此图片" width="450" height="380" /></a><br />
点击下一步，ok，选择你要加入的sql语句类型吧<br />
<a href="http://www.ai-2.cn/attachment/da005.gif" target="_blank"><img class="insertimage" title="点击在新窗口中浏览此图片" src="http://www.ai-2.cn/attachment/da005.gif" border="0" alt="点击在新窗口中浏览此图片" width="450" height="380" /></a><br />
我们选择insert，向数据库中添加数据，然后编辑一下sql语句，一直下一步，完成，命令行里添加了一个insertquery的命令了<br />
<a href="http://www.ai-2.cn/attachment/da006.gif" target="_blank"><img class="insertimage" title="点击在新窗口中浏览此图片" src="http://www.ai-2.cn/attachment/da006.gif" border="0" alt="点击在新窗口中浏览此图片" /></a><br />
添加数据是需要参数的，参数怎么加呢？<br />
首先在insertquery()这个上点右键，配置，看一下sql语句<br />
在需要添加参数的地方把参数添进去，比如aa,bb<br />
<a href="http://www.ai-2.cn/attachment/da007.gif" target="_blank"><img class="insertimage" title="点击在新窗口中浏览此图片" src="http://www.ai-2.cn/attachment/da007.gif" border="0" alt="点击在新窗口中浏览此图片" width="450" height="380" /></a><br />
点击完成，然后在insertquery()的属性窗口，选择parameters(sql语句或存储过程的参数)，然后添加两个参数aa和bb，当然，数据类型一定要选择正确哦<br />
<a href="http://www.ai-2.cn/attachment/da008.gif" target="_blank"><img class="insertimage" title="点击在新窗口中浏览此图片" src="http://www.ai-2.cn/attachment/da008.gif" border="0" alt="点击在新窗口中浏览此图片" width="450" height="331" /></a><br />
确定，参数添加完成<br />
<a href="http://www.ai-2.cn/attachment/da009.gif" target="_blank"><img class="insertimage" title="点击在新窗口中浏览此图片" src="http://www.ai-2.cn/attachment/da009.gif" border="0" alt="点击在新窗口中浏览此图片" /></a><a href="http://www.ai-2.cn/attachment/da009.gif" target="_blank"><img class="insertimage" title="点击在新窗口中浏览此图片" src="http://www.ai-2.cn/attachment/da009.gif" border="0" alt="点击在新窗口中浏览此图片" /></a><a href="http://www.ai-2.cn/attachment/da009.gif" target="_blank"><img class="insertimage" title="点击在新窗口中浏览此图片" src="http://www.ai-2.cn/attachment/da009.gif" border="0" alt="点击在新窗口中浏览此图片" /></a></p>
<p>怎么使用呢？^_^，在需要的地方直接用me.ContentTableAdapter.insertquery(参数1,参数2)就行了^_^</p>
<p>为了更好的看到数据库的变化，你可以添加一个DataGridView来进行显示，数据源上记得绑定datadataset啊</p>
<p>PS:插入数据后，需要重新读入才能在DataGridView中显示出来</p>
]]></content:encoded>
			<wfw:commentRss>http://ai-2.cn/2008/09/contenttableadapter_datadataset/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>vb.net使用HttpWebResponse进行网站登陆并保持Session</title>
		<link>http://ai-2.cn/2008/09/httpwebresponse/</link>
		<comments>http://ai-2.cn/2008/09/httpwebresponse/#comments</comments>
		<pubDate>Sat, 20 Sep 2008 03:15:37 +0000</pubDate>
		<dc:creator>csecong</dc:creator>
				<category><![CDATA[vb.net]]></category>
		<category><![CDATA[httpwebresponse]]></category>
		<category><![CDATA[自动发帖]]></category>
		<category><![CDATA[自动登陆]]></category>

		<guid isPermaLink="false">http://ai-2.cn/?p=60</guid>
		<description><![CDATA[打算做一个论坛自动发帖的软件，涉及到登陆及在登陆状态下发布文章的问题
1、登陆
登陆我们可以直接用WebRequest.Create(url)的方法,POST数据即可……]]></description>
			<content:encoded><![CDATA[<p>打算做一个论坛自动发帖的软件，涉及到登陆及在登陆状态下发布文章的问题<br />
1、登陆<br />
登陆我们可以直接用WebRequest.Create(url)的方法,POST数据即可，这里需要注意的就是post的数据必须编码一下，文本是不能直接post的<br />
2、取得cookie<br />
如果你想把cookie显示出来，需要使用GetResponseHeader(&#8220;Set-Cookie&#8221;)将cookie以文本字段显示<br />
如果你要发布文章时也提交cookie，直接提交GetResponseHeader(&#8220;Set-Cookie&#8221;)是不行的，因为他是string的文本字段，而HttpWebResponse的CookieContainer确实cookie数组<br />
这时你需要首先定义一个空白的CookieContainer，登陆时就会得到cookie，提交文章直接使用这个值即可</p>
<p>源码部分如下：</p>
<p>以下为网上找到的测试源码，不是vb.net的，不过说明了原理</p>
<div class="code">CookieContainer cc = new CookieContainer();<br />
for(int i=0;i&lt;100;i++)<br />
{<br />
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(&#8220;http://localhost/AspxApp/MainForm.aspx&#8221;);<br />
myReq.CookieContainer = cc;<br />
HttpWebResponse resp = myReq.GetResponse() as HttpWebResponse;<br />
Stream s = resp.GetResponseStream();<br />
StreamReader sr = new StreamReader(s);    String text = sr.ReadToEnd();<br />
sr.Close();<br />
s.Close();<br />
}</div>
<p>我写的代码很乱，而且只是为了测试，所以看起来很繁琐，效率很差，大家将就看一下吧</p>
<div class="code">Imports System.net<br />
Imports System.IO<br />
Imports System.Text.RegularExpressions<br />
Imports System.Text<br />
Public Class Form1<br />
Private requestScrape As HttpWebRequest<br />
Private responseScrape As HttpWebResponse<br />
Private cc As New CookieContainer<br />
Function GetHttpStream(ByVal url As String, ByVal uname As String, ByVal upass As String) As Stream<br />
&#8216; 使用 WebRequestFactory 创建请求。<br />
Dim encoding = New ASCIIEncoding<br />
Dim aa As String, ab As Byte()<br />
aa = &#8220;username=&#8221; &amp; uname &amp; &#8220;&amp;password=&#8221; &amp; upass &amp; &#8220;&amp;loginsubmit=true&#8221;<br />
ab = encoding.GetBytes(aa)<br />
&#8216;TextBox3.Text = aa<br />
requestScrape = CType(WebRequest.Create(url), HttpWebRequest)<br />
With requestScrape<br />
.UserAgent = &#8220;Mozilla/4.0 (compatible; MSIE 6.0b; Windows NT 5.1)&#8221;<br />
.Method = &#8220;POST&#8221;<br />
.ContentType = &#8220;application/x-www-form-urlencoded&#8221;<br />
.ContentLength = ab.Length<br />
.Timeout = 10000<br />
.CookieContainer = cc</p>
<p>End With<br />
Dim newStream As Stream = requestScrape.GetRequestStream()<br />
newStream.Write(ab, 0, ab.Length)<br />
newStream.Close()<br />
Try<br />
&#8216; 返回响应流。<br />
responseScrape = CType(requestScrape.GetResponse(), HttpWebResponse)<br />
Return responseScrape.GetResponseStream()<br />
Catch exp As Exception<br />
&#8216; 因为错误最有可能是由键入错误的 Url 或者<br />
&#8216; 没有 Internet 连接造成的，所以创建一条转发回调用函数的<br />
&#8216; 自定义错误信息。<br />
Throw New Exception(exp.Message.ToString)<br />
End Try<br />
End Function<br />
&#8216; 此函数读取由 httpWebResponse 对象返回的流，并<br />
&#8216; 将其转换为字符串供 RegEx 处理。<br />
Function ConvertStreamToString(ByVal stmSource As Stream, ByVal codeb As Integer) As String<br />
Dim sr As StreamReader = Nothing</p>
<p>If Not IsNothing(stmSource) Then<br />
Try<br />
sr = New StreamReader(stmSource, System.Text.Encoding.GetEncoding(codeb))<br />
&#8216; 使用设定的编码格式读取并返回流的全部内容。<br />
Return sr.ReadToEnd<br />
Catch exp As Exception<br />
&#8216; 不显示 MsgBox。只是转发<br />
&#8216;来自 GetHttpStream() 的错误信息。<br />
Throw New Exception()<br />
Finally<br />
&#8216; 清理 Stream 和 StreamReader。<br />
responseScrape.Close()<br />
sr.Close()<br />
End Try<br />
End If<br />
Return Nothing<br />
End Function</p>
<p>Function GetHttpStream2(ByVal url As String) As Stream<br />
&#8216; 使用 WebRequestFactory 创建请求。<br />
requestScrape = CType(WebRequest.Create(url), HttpWebRequest)<br />
With requestScrape<br />
.UserAgent = &#8220;Mozilla/4.0 (compatible; MSIE 6.0b; Windows NT 5.1)&#8221;<br />
.Method = &#8220;GET&#8221;<br />
.CookieContainer = cc<br />
.Timeout = 10000<br />
End With</p>
<p>Try<br />
&#8216; 返回响应流。<br />
responseScrape = CType(requestScrape.GetResponse(), HttpWebResponse)<br />
Return responseScrape.GetResponseStream()<br />
Catch exp As Exception<br />
&#8216; 因为错误最有可能是由键入错误的 Url 或者<br />
&#8216; 没有 Internet 连接造成的，所以创建一条转发回调用函数的<br />
&#8216; 自定义错误信息。<br />
Throw New Exception(exp.Message.ToString)<br />
End Try<br />
End Function<br />
&#8216; 此函数读取由 httpWebResponse 对象返回的流，并<br />
&#8216; 将其转换为字符串供 RegEx 处理。<br />
Function ConvertStreamToString2(ByVal stmSource As Stream, ByVal codeb As Integer) As String<br />
Dim sr As StreamReader = Nothing</p>
<p>If Not IsNothing(stmSource) Then<br />
Try<br />
sr = New StreamReader(stmSource, System.Text.Encoding.GetEncoding(codeb))<br />
&#8216; 使用设定的编码格式读取并返回流的全部内容。<br />
Return sr.ReadToEnd<br />
Catch exp As Exception<br />
&#8216; 不显示 MsgBox。只是转发<br />
&#8216;来自 GetHttpStream() 的错误信息。<br />
Throw New Exception()<br />
Finally<br />
&#8216; 清理 Stream 和 StreamReader。<br />
responseScrape.Close()<br />
sr.Close()<br />
End Try<br />
End If<br />
Return Nothing<br />
End Function</p>
<p>Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click<br />
Dim ystrm As Stream = GetHttpStream(&#8220;http://127.0.0.1/login.asp&#8221;, TextBox1.Text, TextBox2.Text)  &#8217;获取网址<br />
Dim respHTML As String = ConvertStreamToString(ystrm, 65001)<br />
RichTextBox1.Text = respHTML.ToString<br />
TextBox3.Text = responseScrape.GetResponseHeader(&#8220;Set-Cookie&#8221;).ToString</p>
<p>Dim ystrm2 As Stream = GetHttpStream2(&#8220;http://127.0.0.1/post.asp&#8221;)  &#8217;获取网址<br />
Dim respHTML2 As String = ConvertStreamToString2(ystrm2, 65001)<br />
RichTextBox1.Text = respHTML2.ToString<br />
End Sub<br />
End Class</p></div>
<p>通过比较RichTextBox1.Text的内容判断是否正常发送cookie<br />
65001是UTF8编码，一般用0即可</p>
]]></content:encoded>
			<wfw:commentRss>http://ai-2.cn/2008/09/httpwebresponse/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
