2010年12月31日 星期五

服飾租賃,服飾中盤商,服飾網拍,服飾銷售,服飾進退故障,服飾寄賣,服飾切貨

目前還在努力開發中(已開發2年),本系統目前能運作:
服飾租賃,服飾中盤商,服飾網拍,服飾銷售,服飾進退故障,服飾寄賣,服飾切貨
客戶實務上線運作時間:1年以上
總完成度:65%
仍持續開發中...

在總完成度後,允許跨店拋轉同步資料,可允許application / web GUI 同步運作
詳細將完成開發後,再發表;若有意者,可至官網找詢聯絡方式 池龍工作室
優良的人性化操作介面,資料庫採用:ms-sql(msde) 2000 可轉2005/2008
--

iis6 asp 'clng' error bug?

這真是神奇的問題,困擾了一推人
在實務上:
單純的 iis6 , 並不會出現 型態不符'clng'的問題
但是:
裝上ms-sql 2005/2008(r2) express後,會讓iis6 有些異動;在偵錯變成 vs tools後
便會開始奇怪的偵錯

在asp程式上:
180--->clng(180)==>這樣會是錯的?

逼得一定要改:cdbl(180) 才肯過關....
到底是怎回事

在iis6 asp +sql 2005/2008 下,變成嚴禁使用:cint , clng

若改用asp.net 呢? 哈,竟是可以的;真是讓人很"納悶"呀~~~~
==============================
2011/1/5 更新:
以上原因,最後查出的問題是:
iis6 的回收資源過慢,造成溢位
(如圖)

2010年12月30日 星期四

mssql 2008 解除安裝現有的 SQL Server 執行個體

1.cmd模式
2.目錄切至 C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Release\
執行:
(全部)
Setup.exe /Action=Uninstall /FEATURES=SQL,AS,RS,IS,Tools /INSTANCENAME=MSSQLSERVER

(SQL)
Setup.exe /Action=Uninstall /FEATURES=SQL /INSTANCENAME=MSSQLSERVER

-------
實務經驗操作:
正確移除ms-sql 2008 方式:
0.cmd ->cd C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Release
1.Setup.exe /Action=Uninstall /FEATURES=SQL /INSTANCENAME=MSSQLSERVER
2.重開機
3.Setup.exe /Action=Uninstall /FEATURES=AS,RS,IS,Tools /INSTANCENAME=MSSQLSERVER
4.重開機

2010年12月29日 星期三

mssql 2008 master error 1841

最近公司POS客戶上線,發現mssql 2008 竟然會有發生:
error 1841 , 和其他代碼的錯誤;造成 ms-sql server 服務無法啟動
--
遇到這問題,真是沒搞頭.
今天google一下,發現有一篇:MS SQL 2008 Master DB 資料庫損壞災難復原執行要點
以為是和我相同的問題,結果..."再"仔細看一下;這只是"模擬"檔案不見且預先"備好"內定資料庫
略看了一下,這並非"實務"的經驗;沒什麼幫助
依這種做法,倒不如:將ms-sql 服務停用後,把 \MSSQL\DATA 整個壓縮份起來即可
--
在實務上,我取別台的data回來覆蓋後;一樣無法啟動
網路上也很多都出現相同的 error 1841 的問題,均無法讓ms-sql 正常啟動起來
等待"微軟"出個工具.....來改善減輕我這RD+MIS的負擔

目前這問題,還未找到真正的排除方式

2010年12月26日 星期日

利用ICSharpCode.SharpZipLib 進行壓縮,解壓縮

來源處
--
using System;
using System.Data;
using System.IO;
using ICSharpCode.SharpZipLib.Zip.Compression;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
using ICSharpCode.SharpZipLib.GZip;

/**////
/// Summary description for ICSharp
///

public class ICSharp
{
public ICSharp()
{
//
// TODO: Add constructor logic here
//
}
/**////
/// ??
///

/// ///
public string Compress(string param)
{
byte[] data = System.Text.Encoding.UTF8.GetBytes(param);
//byte[] data = Convert.FromBase64String(param);
MemoryStream ms = new MemoryStream();
Stream stream = new ICSharpCode.SharpZipLib.BZip2.BZip2OutputStream(ms);
try
{
stream.Write(data, 0, data.Length);
}
finally
{
stream.Close();
ms.Close();
}
return Convert.ToBase64String(ms.ToArray());
}
/**////
/// 解?
///

/// ///
public string Decompress(string param)
{
string commonString="";
byte[] buffer=Convert.FromBase64String(param);
MemoryStream ms = new MemoryStream(buffer);
Stream sm = new ICSharpCode.SharpZipLib.BZip2.BZip2InputStream(ms);
//?里要指明要?入的格式,要不就有??
StreamReader reader = new StreamReader(sm,System.Text.Encoding.UTF8);
try
{
commonString=reader.ReadToEnd();
}
finally
{
sm.Close();
ms.Close();
}
return commonString;
}
}

2010年12月24日 星期五

租書軟體,您是否選對了?

歡迎您下載安裝試用:官網-池龍工作室
--
舊DOS租書軟體百年問題,讓原一些尚在使用DOS租書軟體均已找到了適合的軟體
當然本工作室開發的租書軟體也是目標的對象之一
市面的租書軟體很多套,但是否就是真的是跟著時代潮流的進行脫胎換骨呢?(更新改版)
有些店家看到功能多就害怕,退而放棄求簡易的租書軟體
卻萬萬沒考慮到? 未來性和將面臨的種種問題

底下分析說明:

1.在A地開了近5~10年,方圓3公里均沒有其他漫畫店進場;假設B店進駐了
B店使用了一套多種促銷,一路多種變化的促銷;試問您正使用的租書軟體行嗎?
答案:因為我只會用簡單的,所以租書軟體沒有這樣的功能;客群卻在不知不覺下被吸收過去了

2.當初就是因為這套便宜,所以購買了;且功能也夠用了
當客人來問,是否能代購書籍? 不行
當客人來問,B店不需預繳租100元能自動打8折,租200元自動打75折;行嗎? 不行
當客人來問,B店每一天都能推出不同的書類作優惠打折或0元;行嗎? 不行
....客人摸著鼻子,轉頭出門時....不知您的心情?

3.租書過程,是否能同時處理多位客人呢?
A客拿了20本書,要租書了;此時開始刷書到第12本,A客說等一下;他要再去找些書
此時: 能換下一位嗎? 重刷?
B客拿了9本書,要租書了;此時開始刷書到第5本後,A客跑到外面接電話
此時: 該怎辦? 後面還排了4.5位客人呢...
以上各種問題,是否在您的店發生過呢? 是怎樣排除?

4.老問題重問,當初購買的租書軟體;是否很有衝動想要B店也有的功能?
問了後,答案是:一套用到老,不更新!?

5.最後一層的思考,租書店總不能一層不變;但所使用的軟體是否能跟上時代? 雲端?
客人是否能網頁查詢? 查店內書? 使用點數?
本項:將是本工作室下一階段努力的目標

2010年12月23日 星期四

中國WEB開發者網絡

中國WEB開發者網絡
中國WEB開發者網絡:
ASP,ASP.NET,PHP,JSP,源碼,教程,下載,供求,特效
文章真是豐富

把握VB.NET中的流 Stream (3)

來源
--
把握VB.NET中的流(Stream) (三)

文件操作具體實例

在這一部分,你將找到更多常用的文件操作的代碼實例。最常用、最基本的操作就是把text寫入文件和讀回來。現在的應用程序通常不用二進制文件作存儲簡單的變量,而用它來存儲對象,對像集合以及其他機器代碼。下面,將看到具體操作的例子。

讀寫文本文件

為了把text保存到文件,創建一個基於FileStream的StreamReader對象,然後調用Write方法把需要保存的text寫入文件。下面的代碼用SaveFileDialog提示用戶指定一個文件,用於保存TextBox1的內容。

SaveFileDialog1.Filter = _

"Text Files|*.txt|All Files|*.*"

SaveFileDialog1.FilterIndex = 0

If SaveFileDialog1.ShowDialog = DialogResult.OK Then

Dim FS As FileStream = SaveFileDialog1.OpenFile

Dim SW As New StreamWriter(FS)

SW.Write(TextBox1.Text)

SW.Close()

FS.Close()

End If

同樣採用類似的語句,我們讀取一個文本文件,並把內容顯示在TextBox控件中。StreamReader的ReadToEnd方法返回文件的全部內容。

OpenFileDialog1.Filter = _

"Text Files|*.txt|All Files|*.*"

OpenFileDialog1.FilterIndex = 0

If OpenFileDialog1.ShowDialog = DialogResult.OK Then

Dim FS As FileStream

FS = OpenFileDialog1.OpenFile

Dim SR As New StreamReader(FS)

TextBox1.Text = SR.ReadToEnd

SR.Close()

FS.Close()

End If

各種對象的存儲

採用BinaryFormatte以二進制的形式,或者用SoapFormatter類以XML格式都可以序列化一個具體的對象。只要把所有BinaryFormatter的引用改為SoapFormatter,無需改變任何代碼,就可以以XML格式序列化對象。

首先創建一個BinaryFormatter實例:

Dim BinFormatter As New Binary.BinaryFormatter()

然後創建一個用於存儲序列化對象的FileStream對像:

Dim FS As New System.IO.FileStream("c:\test.txt", IO.FileMode.Create)

接著調用BinFormatter的Serialize方法序列化任何可以序列化的framework對像:

R = New Rectangle(rnd.Next(0, 100),rnd.Next(0, 300), _

rnd.Next(10, 40),rnd.Next(1, 9))

BinFormatter.Serialize(FS, R)

加一個Serializable屬性使得自定義的對象可以序列化

Public Structure Person

Dim Name As String

Dim Age As Integer

Dim Income As Decimal

End Structure

下面代碼創建一個Person對像實例,然後調用BinFormatter的Serialize方法序列化自定義對像:

P = New Person()

P.Name = "Joe Doe"

P.Age = 35

P.Income = 28500

BinFormatter.Serialize(FS, P)

你也可以在同一個Stream中接著序列化其他對象,然後以同樣的順序讀回。例如,在序列化Person對像之後接著序列化一個Rectangle對像:

BinFormatter.Serialize(FS, New Rectangle(0, 0, 100, 200))

創建一個BinaryFormatter對象,調用其Deserialize方法,然後把返回的值轉化為正確的類型,就是整個反序列化過程。然後接著發序列化Stream的其他對象。

假定已經序列化了Person和Rectangle兩個對象,以同樣的順序,我們反序列化就可以得到原來的對象:

Dim P As New Person()

P = BinFormatter.Serialize(FS, Person)

Dim R As New Rectangle

R = BinFormatter.Serialize(FS, Rectangle)

Persisting Collections

集合的存儲

大多數程序處理對像集合而不是單個的對象。對於集合數據,首先創建一個數組(或者是其他類型的集合,比如ArrayList或HashTable),用對像填充,然後一個Serialize方法就可以序列化真個集合,是不是很簡單?下面的例子,首先創建一個有兩個Person對象的ArrayList,然後序列化本身:

Dim FS As New System.IO.FileStream _

("c:\test.txt", IO.FileMode.Create)

Dim BinFormatter As New Binary.BinaryFormatter()

Dim P As New Person()

Dim Persons As New ArrayList

P = New Person()

P.Name = "Person 1"

P.Age = 35

P.Income = 32000

Persons.Add(P)

P = New Person()

P.Name = "Person 2"

P.Age = 50

P.Income = 72000

Persons.Add(P)

BinFormatter.Serialize(FS, Persons)

以存儲序列化數據的文件為參數,調用一個BinaryFormatter實例的Deserialize方法,就會返回一個對象,然後把它轉化為合適的類型。下面的代碼反序列化文件中的所有對象,然後處理所有的Person對像:

FS = New System.IO.FileStream _

("c:\test.txt", IO.FileMode.OpenOrCreate)

Dim obj As Object

Dim P As Person(), R As Rectangle()

Do

obj = BinFormatter.Deserialize(FS)

If obj.GetType Is GetType(Person) Then

P = CType(obj, Person)

' Process the P objext

End If

Loop While FS.Position < FS.Length - 1

FS.Close()

下面的例子調用Deserialize方法反序列化真個集合,然後把返回值轉換為合適的類型(Person):

FS = New System.IO.FileStream("c:\test.txt", IO.FileMode.OpenOrCreate)

Dim obj As Object

Dim Persons As New ArrayList

obj = CType(BinFormatter.Deserialize(FS), ArrayList)

FS.Close()

把握VB.NET中的流 Stream (2)

來源
---
把握VB.NET中的流(Stream) (二)

靈活多樣的IO操作
有時候,在數據和字節數組之間轉換是一件繁瑣的事情。為了避免這些無聊的轉換和簡化代碼,採用StreamReader/StreamWrite和BinaryReader/BinaryWriter不愧為明智之舉。StreamReader/StreamWrite分別由TextReader/TextWriter類派生,自動執行字節編碼的轉換。BinaryReader/BinaryWriter由Stream派生,主要以二進制的形式讀寫數據。
從二進制文件讀數據的時候,首先創建一個BinaryReader的實例,BinaryReader的構建函數接受一個FileStream對象,代表將要讀的文件。我們前面已經看過,可以用File.OpenRead 或者 File.OpenWrite 方法創建FileStream對象。
如下所示:
Dim BR As New IO.BinaryReader(IO.File.OpenRead(path))
Dim BW As New IO.BinaryWriter(IO.File.OpenWrite(path))
BinaryWriter類有Write和WriteLine兩種方法,都可以接受任何類型的數據作為參數寫入文件(WriteLine在文件尾追加一行數據)。BinaryReader類有很多讀數據的方法,數據存儲在文件上的時候,並沒有任何關於自己類型的信息,所以讀數據的時候,必須選擇合適的重載Read方法。
下面的例子假設BW是一個已經初始化過的BinaryWriter對象,表示如何寫一個字符串、整數、雙精度數字到文件:
BW.WriteLine("A String")
BW.WriteLine(12345)
BW.WriteLine(123.456789999999)
讀回數據的時候,必須選擇BinaryReader合適的Read方法:
Dim s As String = BR.ReadString()
Dim i As Int32 = BR.ReadInt32()
Dim dbl As Double = BR.ReadDouble()
對於文本文件,採用StreamReader/StreamWriter對象。方法跟上面差不多,寫數據同樣用Write和WriteLine方法。Read方法讀一個字符,ReadLine讀一行數據(直到有回車/換行符為止),ReadToEnd讀所有的字符,到文件結束。
對像序列化
到目前為止,我們只是把簡單類型的數據寫到文件中並讀回程序。而實際上,大多數的程序讀寫的數據可能並不是簡單類型,而是複雜的結構,例如:數組,數組列表,哈希表等。於是,我們採取一種成為序列化的技術,首先把數組的值轉化為字節序列,然後寫入文件,這樣整個數組就存儲下來。相反,我們稱之為反序列化。
序列化是.NET的一個很大的話題,這列介紹一下基本的信息。
用BinaryFormatter的Serialize 和 Deserialize方法把一個對像保存到文件和讀回程序。首先,imports System.RunTime.Serialization.Formatters,免得寫那麼長的申明。Formatters名空間包含了BinaryFormatter類,用於以二進制的數據序列化對象。
創建BinaryFormatter實例,接著調用Serialize方法,Serialize接受兩個參數:一個是可寫的FileStream實例,用於保存數據的文件;另外一個是對像本身:
Dim BinFormatter As New Binary.BinaryFormatter()
Dim R As New Rectangle(10, 20, 100, 200)
BinFormatter.Serialize(FS, R)
BinaryFormatter的Deserialize方法只有一個參數,FileStream實例。在當前位置,反序列化得到一個類型不明的對象,我們必須用Ctype轉換為原來的對象。下面的例子反序列化上面的文件得到原來的Rectangle對像:
Dim R As New Rectangle()
R = CType(BinFormatter.Deserialize(FS), Rectangle)
我們也可以以XmlFormatter進行對像序列化。首先在IDE的Project菜單選擇添加System.Runtime.Serialization.Formatters.Soap,然後就可以進行創建SoapFormatter對象了,方法跟BinFormatter一樣,只不過數據的存儲採用XML格式:
Dim FS As New IO.FileStream("c:\Rect.xml", IO.FileMode.Create, IO.FileAccess.Write)
Dim XMLFormatter As New SoapFormatter()
Dim R As New Rectangle(8, 8, 299, 499)
XMLFormatter.Serialize(FS, R)
打開c:\Rect.xml ,實際上裡面存儲了這些內容:
- <SOAP-ENV:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:clr="http://schemas.microsoft.com/soap/encoding/clr/1.0" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
- <SOAP-ENV:Body>
- <a1:Rectangle id="ref-1" xmlns:a1="http://schemas.microsoft.com/clr/nsassem/System.Drawing/System.Drawing%2C%20Version%3D1.0.3300.0%2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Db03f5f7f11d50a3a">
<x>8</x>
<y>8</y>
<width>249</width>
<height>499</height>
</a1:Rectangle>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

把握VB.NET中的流 Stream (1)

來源
--
把握VB.NET中的流(Stream) (一)

當你第一次用VB.NET讀寫文件的時候,你肯定會發現VB.NET摒棄了傳統的文件I/O支持,感覺不習慣。其實,在.NET裡面,微軟用豐富的「流」對像取代了傳統的文件操作,而「流」,是一個在Unix裡面經常使用的對象。
我們可以把流當作一個通道,程序的的數據可以沿著這個通道」流」到各種數據存儲機構(比如:文件,字符串,數組,或者其他形式的流等)。為什麼我們會摒棄用了那麼久的IO操作,而代之為流呢?其中很重要的一個原因就是並不是所有的數據都存在於文件中。現在的程序,從各種類型的數據存儲中獲取數據,比如可以是一個文件,內存中的緩衝區,還有InterneT。而流技術使得應用程序能夠基於一個編程模型,獲取各種數據,而不必要學會怎麼樣去獲取遠程web服務器上的一個文件的具體技術。我們只需要在應用程序和web服務器之間創建一個流,然後讀取服務器發送的數據就可以了。
流對象,封裝了讀寫數據源的各種操作,最大的優點就是一當你學好怎麼樣操作某一個數據源時,你就可以把這種技術擴展到其他形形色色的數據源。
流的種類
流是一個抽像類,你不能在程序中申明Stream的一個實例。在.NET裡面,由Stream派生出5種具體的流,分別是:
FileStream 支持對文件的順序和隨機讀寫操作
MemoryStream 支持對內存緩衝區的順序和隨機讀寫操作
NETworkStream 支持對Internet網絡資源的順序和隨機讀寫操作,存在於System.Net.Sockets名稱空間
CryptoStream 支持數據的編碼和解碼,存在於System.Security.Cryptography 名稱空間
BufferedStream 支持緩衝式的讀寫對那些本身不支持的對象
並不是所有的Stream都採用用完全一摸一樣的方法,比如讀取本地文件的流,可以告訴我們文件的長度,當前讀寫的位置等,你可以用Seek方法跳到文件的任意位置。相反,讀取遠程文件的流不支持這些特性。不過,Stream本身有CanSeek, CanRead 和 CanWrite屬性,用於區別數據源,告訴我們支持還是不支持某中特性。
下面我們簡單介紹一個FileStream類
FileStream類
進行本地文件操作的時候,我們可以採用FileSteam類, 可以很簡單的讀寫為字節數組(arrays of bytes)。對於簡單數據類型的數據的讀寫,可以採用BinaryReader 和BinaryWriter以及StreamReader,StreamWriter類。 BinaryReader,用特定的編碼將基元數據類型讀作二進制值。BinaryWriter以二進制形式將基元類型寫入流,並支持用特定的編碼寫入字符串。StreamReader/Writer則是把數據存儲為XML格式。在VB.NET裡面採用那個區別不大,因為所用的類都應用於兩種格式。
VB.NET支持傳統的隨機讀寫文件,你可以創建文件,用於存儲Struct,然後根據記錄數訪問。就像在以前的Vb版本中一樣,用FileOpen,FileGet函數。很大程度上,這已經被XML或者數據庫取代。如果你創建新的應用程序,而有不需要考慮跟就版本的兼容問題,建議採用.NET的新特性。
不管你將要使用拿一個StreamClass,你都必須創建一個FileStream對象。有很多方式創建,最簡單就是指定文件路徑,打開模式,如下面的語法。
Dim fStream As New FileStream(path, fileMode, fileAccess)
Path要包含文件的路徑以及文件名。fileMode是枚舉類型FileMode的成員之一,如下表所示。fileAccess是枚舉類型FileAccess的成員。Read (只讀), ReadWrite (讀寫), and Write (寫操作)。決定了文件的讀寫權限。
成員名稱
說明
Append
打開現有文件並查找到文件尾,或創建新文件。
Create
指定操作系統應創建新文件。如果文件已存在,它將被改寫。
CreateNew
指定操作系統應創建新文件。
Open
指定操作系統應打開現有文件。
OpenOrCreate
指定操作系統應打開文件(如果文件存在);否則,應創建新文件。
Truncate
指定操作系統應打開現有文件。文件一旦打開,就將被截斷為為零字節大小。
當然,你也可以用 (Open, OpenRead, OpenText, OpenWrite)創建FileStream
Dim FS As New FileStream = IO.File.OpenWrite("c:\Stream.txt")
另外一種方式打開文件可以用OpenFileDialog 和 SaveFileDialog控件的OpenFile方法。
不需要指定任何參數。 OpenFileDialog的OpenFile方法以只讀方式打開文件; SaveFileDialog的OpenFile方法以讀寫方式打開文件。
FileStream只支持最基本的操作,把數據寫入字節數組或者從字節數組寫入文件中。如果我們用FileStream把數據保存在文件中,首先把數據轉化為Byte數組,然後調用FileStream的Write方法。同樣,FileStream的Read方法,返回的也是字節數組。你或許不會經常直接使用FileStream對象,我們還是有必要簡單看一下它的基本功能
創建FileStream對像之後,調用WriteByte 寫一個字節到文件中。 Write方法可以將一個數組寫入文件中,需要三個參數
Write(buffer, offset, count)
Buffer是要寫入數組地址,offset是偏移量,count指寫入字節數量,Read的語法也一樣。
由於FileStream要跟Bytes Array打交道,所以研究一下ASCIIEncoding 的GetBytes和UnicodeEncoding 的GetChars很有必要
下面的例子是一個轉換操作。
Dim buffer() As Byte
Dim encoder As New System.Text.ASCIIEncoding()
Dim str As String = "This is a line of text"
ReDim buffer(str.Length - 1)
Encoder.GetBytes(str, 0, str.Length, buffer, 0)
FS.Write(buffer, 0, buffer.Length)
注意:必須Resize要寫入的Byte數組為要讀寫的長度。

Async File Downloader

Private Sub DownloadFile(ByVal fileToDownload As String, ByVal savePath As String)
Dim webClient As New WebClient()
AddHandler webClient.DownloadFileCompleted, AddressOf Completed AddHandler webClient.DownloadProgressChanged, AddressOf ProgressChanged
webClient.DownloadFileAsync(New Uri(fileToDownload), savePath)
End Sub

Private Sub ProgressChanged(ByVal sender As Object, ByVal e As DownloadProgressChangedEventArgs)
Progressbar1.Value = e.ProgressPercentage
End Sub

Private Sub Completed(ByVal sender As Object, ByVal e As AsyncCompletedEventArgs)
MessageBox.Show("Finished!", "File complete!", MessageBoxButtons.OK, MessageBoxIcon.Information)
Progressbar1.Value = 0
End Sub

增加 WebClient.DownloadProgressChanged 事件

Public Shared Sub DownLoadFileInBackground2(ByVal address As String)

Dim client As WebClient = New WebClient()

' Specify that the DownloadFileCallback method gets called
' when the download completes.
AddHandler client.DownloadFileCompleted, AddressOf DownloadFileCallback2
' Specify a progress notification handler.
AddHandler client.DownloadProgressChanged, AddressOf DownloadProgressCallback
Dim uri as Uri = New Uri(address)
client.DownloadFileAsync(uri, "serverdata.txt")
End Sub

webClient.DownloadFileAsync

简单介绍一下WebClient:
WebClient 类提供向 URI 标识的任何本地、Intranet 或 Internet 资源发送数据以及从这些资源接收数据的公共方法。
WebClient 类使用 WebRequest 类提供对资源的访问。WebClient 实例可以通过任何已向 WebRequest.RegisterPrefix 方法注册的 WebRequest 子代访问数据。
注意
默认情况下,.NET Framework 支持以 http:、https:、ftp:、和 file: 方案标识符开头的 URI。

下面描述用于将数据上载到资源的 WebClient 方法:
OpenWrite 检索一个用于将数据发送到资源的 Stream。
OpenWriteAsync 检索 Stream,它在不阻止调用线程的情况下将数据发送到资源。
UploadData 将字节数组发送到资源,并返回包含任何响应的 Byte 数组。
UploadDataAsync 在不阻止调用线程的情况下,将 Byte 数组发送到资源。
UploadFile 将本地文件发送到资源,并返回包含任何响应的 Byte 数组。
UploadFileAsync 在不阻止调用线程的情况下,将本地文件发送到资源。
UploadValues 将 NameValueCollection 发送到资源,并返回包含任何响应的 Byte 数组。
UploadValuesAsync 在不阻止调用线程的情况下,将 NameValueCollection 发送到资源,并返回包含任何响应的 Byte 数组。
UploadString 在不阻止调用线程的情况下,将 String 发送到资源。
UploadStringAsync 在不阻止调用线程的情况下,将 String 发送到资源。

下面描述从资源下载数据的 WebClient 方法:
OpenRead 从资源以 Stream 的形式返回数据。
OpenReadAsync 在不阻止调用线程的情况下,从资源返回数据。
DownloadData 从资源下载数据并返回 Byte 数组。
DownloadDataAsync 在不阻止调用线程的情况下,从资源下载数据并返回 Byte 数组。
DownloadFile 从资源将数据下载到本地文件。
DownloadFileAsync 在不阻止调用线程的情况下,将数据从资源下载到本地文件。
DownloadString 从资源下载 String 并返回 String。
DownloadStringAsync 在不阻止调用线程的情况下,从资源下载 String。

您可以使用 CancelAsync 方法取消尚未完成的异步操作。
默认情况下,WebClient 实例不发送可选的 HTTP 报头。如果您的请求需要可选报头,必须将该报头添加到 Headers 集合。例如,要在响应中保留查询,必须添加用户代理报头。此外,如果用户代理标头丢失,服务器可能返回 500(内部服务器错误)。
在 WebClient 实例中,AllowAutoRedirect 设置为 true。
给继承者的说明 派生类应调用 WebClient 的基类实现,以确保派生类按预期方式工作。

实现源码为:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;

namespace wiindowsFormsApplication
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.textBox1.Text = @"http://dl-sh-ocn-1.pchome.net/0d/bx/koomail50b8.rar";
}

WebClient webClient = new WebClient();
private void btn_down_Click(object sender, EventArgs e)
{

if (webClient.IsBusy)//是否存在正在进行中的Web请求
{
webClient.CancelAsync();
}
//为webClient添加事件
webClient.DownloadProgressChanged +=new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
webClient.DownloadFileCompleted+=new AsyncCompletedEventHandler(webClient_DownloadFileCompleted);
//开始下载
webClient.DownloadFileAsync(new Uri(this.textBox1.Text), "aa.rar");
}

private void webClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
this.progressBar1.Value = e.ProgressPercentage;
this.lbl_pro.Text = e.ProgressPercentage.ToString() + "%";
this.lbl_detail.Text = string.Format("正在下载文件,完成进度{0}/{1}(字节)"
,e.BytesReceived
,e.TotalBytesToReceive);
}

private void webClient_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Cancelled)
MessageBox.Show("下载被取消!");
else
MessageBox.Show("下载完成!");
}

private void btn_cancel_Click(object sender, EventArgs e)
{
this.webClient.CancelAsync();
this.webClient.Dispose();
}
}
}

2010年12月22日 星期三

WebClient object to download the data at a URI in VB .NET

來源處
--
Private Sub btnUpload_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnFetch.Click
Me.Cursor = Cursors.WaitCursor
Application.DoEvents()

Try
' Make a WebClient.
Dim web_client As WebClient = New WebClient

' Get the indicated URI.
Dim response As Stream = _
web_client.OpenRead(txtURI.Text)

' Read the result.
Dim stream_reader As New IO.StreamReader(response)
txtResults.Text = stream_reader.ReadToEnd()

' Close the stream reader and its underlying stream.
stream_reader.Close()
Catch ex As Exception
MessageBox.Show(ex.Message, "Read Error", _
MessageBoxButtons.OK, _
MessageBoxIcon.Exclamation)
End Try

Me.Cursor = Cursors.Default
End Sub

IIS6 中, ASP 上傳、下載限制修正

icrosoft 的 Internet Information Service6 是 Windows Server 2003 選用的 Web 服務,也是最新的版本。隨著 Windows Server 2003 的銷售,愈來愈多的網站管理員也接觸到了 IIS 6 。而在 IIS6 中為了安全性的考量,預設最大的檔案上傳大小限制為 200KB(204800 Byte ) , 因此在上傳檔案大小超過 200KB ,便會遭遇上傳錯誤的訊息。則此部分可以透過 metabase.xml 中的參數來修正。
【路徑 C:\windows\sytem32\inetserv\metabase.xml 】

請依照下列六步驟,修正 Windows Server 2003 IIS 6 的 ASP 上傳與下載檔案大小上限問題:
Step1. 先停止 IIS 服務,
  開始 -> 系統管理工具 -> 服務
  停止 IIS Admin Service 和 World Wide Web Publishing Service

Step2. 用文字編輯器開啟 C:\windows\sytem32\inetserv\metabase.xml

Step3. 尋找字串
AspMaxRequestEntityAllowed
  將 204800 (200KB) 改成您想要的大小,此部分為上傳限制。

Step4. 尋找字串
AspBufferingLimit
  將 預設的 4194304 (4MB) 改成您想要的大小,此部分為下載限制。

Step5. 重新啟動 IIS Admin Service 和 World Wide Web Publishing Service 服務。

Step6. 完成 ASP 上傳、下載限制修正。

如何變更IIS 6.0預設上傳與下載檔案大小限制

IIS 6.0預設的上傳檔案大小只有200KB喔!

對一般上傳檔案大小的需求來說當然是不夠

接下來就教您如何變更IIS 6.0預設上傳與下載檔案大小限制的方法

===============================================

以記事本開啟 C:\windows\sytem32\inetserv\metabase.xml

上傳限制:
找尋 AspMaxRequestEntityAllowed 字串
將 204800 (200K) 修改成你要的數字

下載限制:
找尋 AspBufferingLimit 字串
預設 4MB ,將它修改成你要的數字

WebClient Use

來源處
--
請至原站看唷,各種用法均有範例說明

Imports System.Net

Module Module1
Sub Main()
' Resource acquisition statement.
Using client As New WebClient
' Set one of the headers.
client.Headers("User-Agent") = "Mozilla/4.0"

' Download data as byte array.
Dim arr() As Byte = client.DownloadData("http://dotnetperls.com/")

' Result.
Console.WriteLine(arr.Length)
End Using
End Sub
End Module

Disable Windows Form Close (x) Button

來源處
---
保證有效

Here come the code:

'for close button declaration
Private Const MF_BYPOSITION = &H400
Private Const MF_REMOVE = &H1000
Private Const MF_DISABLED = &H2

Private Declare Function RemoveMenu Lib "user32" (ByVal hMenu As IntPtr, ByVal nPosition As Integer, ByVal wFlags As Long) As IntPtr
Private Declare Function GetSystemMenu Lib "user32" (ByVal hWnd As IntPtr, ByVal bRevert As Boolean) As IntPtr
Private Declare Function GetMenuItemCount Lib "user32" (ByVal hMenu As IntPtr) As Integer
Private Declare Function DrawMenuBar Lib "user32" (ByVal hwnd As IntPtr) As Boolean

The function:

Public Sub DisableCloseButton(ByVal hwnd As IntPtr)
Dim hMenu As IntPtr
Dim menuItemCount As Integer

hMenu = GetSystemMenu(hwnd, False)
menuItemCount = GetMenuItemCount(hMenu)
Call RemoveMenu(hMenu, menuItemCount - 1, MF_DISABLED Or MF_BYPOSITION)
Call RemoveMenu(hMenu, menuItemCount - 2, MF_DISABLED Or MF_BYPOSITION)
Call DrawMenuBar(hwnd)
End Sub


How to call it:


DisableCloseButton(Me.Handle)

打造 form 外殼

請參考來源
--
不錯的參考

2010年12月21日 星期二

How to check if a file exists over HTTP

請參考此處

解決IIS6.0上放置的文檔無法下载的問題

一般採用 net 開發自動更新,會採用http(web)方式來放置
如:
System .Net.WebClient
My.Computer.Network.DownloadFile

該開放運作站台 對應 INI 或其他版本對照檔,IIS 就必須對 MIME 開放
---
底下為各副檔名的MIME對照表
---
.asx,video/x-ms-asf
.xml,text/xml
.tsv,text/tab-separated-values
.ra,audio/x-pn-realaudio
.sv4crc,app1ication/x-sv4crc
.spc,app1ication/x-pkcs7-certificates
.pmc,app1ication/x-perfmon
.lit,app1ication/x-ms-reader
.crd,app1ication/x-mscardfile
.isp,app1ication/x-internet-signup
.wmlsc,app1ication/vnd.wap.wmlscriptc
.vst,app1ication/vnd.visio
.xlam,app1ication/vnd.ms-excel.addin.macroEnabled.12
.ttf,app1ication/octet-stream
.pfm,app1ication/octet-stream
.csv,app1ication/octet-stream
.aaf,app1ication/octet-stream
.one,app1ication/onenote
.hta,app1ication/hta
.atom,app1ication/atom+xml
.323,text/h323
.mhtml,message/rfc822
.midi,audio/mid
.p7r,app1ication/x-pkcs7-certreqresp
.mny,app1ication/x-msmoney

.clp,app1ication/x-msclip
.vsd,app1ication/vnd.visio
.lpk,app1ication/octet-stream
.bin,app1ication/octet-stream
.onetoc,app1ication/onenote
.x,app1ication/directx
.wvx,video/x-ms-wvx
.vcf,text/x-vcard
.htc,text/x-component
.htt,text/webviewhtml
.h,text/plain
.mht,message/rfc822
.mid,audio/mid
.p7b,app1ication/x-pkcs7-certificates
.gz,app1ication/x-gzip
.dvi,app1ication/x-dvi
.cpio,app1ication/x-cpio
.vdx,app1ication/vnd.ms-visio.viewer
.sldm,app1ication/vnd.ms-powerpoint.slide.macroEnabled.12
.xlm,app1ication/vnd.ms-excel
.fdf,app1ication/vnd.fdf
.setreg,app1ication/set-registration-initiation
.eps,app1ication/postscript
.p7s,app1ication/pkcs7-signature
.toc,app1ication/octet-stream
.mdp,app1ication/octet-stream
.ics,app1ication/octet-stream
.chm,app1ication/octet-stream
.asi,app1ication/octet-stream
.afm,app1ication/octet-stream
.evy,app1ication/envoy
.wmp,video/x-ms-wmp
.qt,video/quicktime
.mpv2,video/mpeg
.xslt,text/xml
.etx,text/x-setext
.cod,image/cis-cod
.snd,audio/basic
.au,audio/basic
.man,app1ication/x-troff-man
.qtl,app1ication/x-quicktimeplayer
.pmw,app1ication/x-perfmon
.class,app1ication/x-java-applet
.iii,app1ication/x-iphone
.csh,app1ication/x-csh
.z,app1ication/x-compress
.vtx,app1ication/vnd.visio
.vsw,app1ication/vnd.visio
.wps,app1ication/vnd.ms-works
.potx,app1ication/vnd.openxmlformats-officedocument.presentationml.template
.ps,app1ication/postscript
.p7c,app1ication/pkcs7-mime
.thn,app1ication/octet-stream
.mso,app1ication/octet-stream
.dot,app1ication/msword
.doc,app1ication/msword
.sgml,text/sgml
.nws,message/rfc822
.pbm,image/x-portable-bitmap
.ief,image/ief
.wav,audio/wav
.texi,app1ication/x-texinfo
.mvb,app1ication/x-msmediaview
.hdf,app1ication/x-hdf
.vsx,app1ication/vnd.visio
.dotm,app1ication/vnd.ms-word.template.macroEnabled.12
.docm,app1ication/vnd.ms-word.document.macroEnabled.12
.pptx,app1ication/vnd.openxmlformats-officedocument.presentationml.presentation
.psm,app1ication/octet-stream
.java,app1ication/octet-stream
.eot,app1ication/octet-stream
.jar,app1ication/java-archive
.mpeg,video/mpeg
.xsf,text/xml
.map,text/plain
.uls,text/iuls
.rf,image/vnd.rn-realflash
.m3u,audio/x-mpegurl
.wma,audio/x-ms-wma
.aifc,audio/aiff
.mdb,app1ication/x-msaccess
.mvc,app1ication/x-miva-compiled
.stl,app1ication/vnd.ms-pki.stl
.ppsx,app1ication/vnd.openxmlformats-officedocument.presentationml.slideshow
.xlsb,app1ication/vnd.ms-excel.sheet.binary.macroEnabled.12
.setpay,app1ication/set-payment-initiation
.prm,app1ication/octet-stream
.mix,app1ication/octet-stream
.lzh,app1ication/octet-stream
.hhk,app1ication/octet-stream
.onepkg,app1ication/onenote
.xaf,x-world/x-vrml
.flr,x-world/x-vrml
.IVF,video/x-ivf
.cnf,text/plain
.asm,text/plain
.tiff,image/tiff
.wax,audio/x-ms-wax
.ms,app1ication/x-troff-ms
.tcl,app1ication/x-tcl
.shar,app1ication/x-shar
.sh,app1ication/x-sh
.nc,app1ication/x-netcdf
.hlp,app1ication/winhlp
.oda,app1ication/oda
.pfb,app1ication/octet-stream
.fla,app1ication/octet-stream
.wm,video/x-ms-wm
.rgb,image/x-rgb
.ppm,image/x-portable-pixmap
.ram,audio/x-pn-realaudio
.sit,app1ication/x-stuffit
.dir,app1ication/x-director
.mpp,app1ication/vnd.ms-project
.xla,app1ication/vnd.ms-excel
.ssm,app1ication/streamingmedia
.axs,app1ication/olescript
.ods,app1ication/oleobject
.psp,app1ication/octet-stream
.jpb,app1ication/octet-stream
.wrz,x-world/x-vrml

.m1v,video/mpeg
.mno,text/xml
.cmx,image/x-cmx
.jpeg,image/jpeg
.dib,image/bmp
.rmi,audio/mid
.aiff,audio/aiff
.wmd,app1ication/x-ms-wmd
.wri,app1ication/x-mswrite
.pub,app1ication/x-mspublisher
.ins,app1ication/x-internet-signup
.wks,app1ication/vnd.ms-works
.xls,app1ication/vnd.ms-excel
.ai,app1ication/postscript
.crl,app1ication/pkix-crl
.qxd,app1ication/octet-stream
.dwp,app1ication/octet-stream
.xof,x-world/x-vrml
.wmv,video/x-ms-wmv
.nsc,video/x-ms-asf
.mpa,video/mpeg
.pnm,image/x-portable-anymap
.rpm,audio/x-pn-realaudio-plugin
.aif,audio/x-aiff
.me,app1ication/x-troff-me
.pml,app1ication/x-perfmon
.trm,app1ication/x-msterminal
.m13,app1ication/x-msmediaview
.js,app1ication/x-javascript
.dxr,app1ication/x-director
.potm,app1ication/vnd.ms-powerpoint.template.macroEnabled.12
.xltx,app1ication/vnd.openxmlformats-officedocument.spreadsheetml.template
.xlt,app1ication/vnd.ms-excel
.xlc,app1ication/vnd.ms-excel
.p10,app1ication/pkcs10
.smi,app1ication/octet-stream
.sea,app1ication/octet-stream
.hqx,app1ication/mac-binhex40
.spl,app1ication/futuresplash
.movie,video/x-sgi-movie
.lsf,video/x-la-asf
.txt,text/plain
.jfif,image/pjpeg
.jpe,image/jpeg
.zip,app1ication/x-zip-compressed
.wmf,app1ication/x-msmetafile
.m14,app1ication/x-msmediaview
.latex,app1ication/x-latex
.wcm,app1ication/vnd.ms-works
.pptm,app1ication/vnd.ms-powerpoint.presentation.macroEnabled.12
.xlsx,app1ication/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.hhp,app1ication/octet-stream
.aca,app1ication/octet-stream
.accdb,app1ication/msaccess
.jcz,app1ication/liquidmotion
.wrl,x-world/x-vrml
.wmx,video/x-ms-wmx
.asr,video/x-ms-asf
.lsx,video/x-la-asf
.xsl,text/xml
.html,text/html
.tif,image/tiff
.der,app1ication/x-x509-ca-cert
.pfx,app1ication/x-pkcs12
.p12,app1ication/x-pkcs12
.ppsm,app1ication/vnd.ms-powerpoint.slideshow.macroEnabled.12
.cur,app1ication/octet-stream
.accdt,app1ication/msaccess
.hdml,text/x-hdml
.htm,text/html
.xbm,image/x-xbitmap
.jpg,image/jpeg
.texinfo,app1ication/x-texinfo
.ppam,app1ication/vnd.ms-powerpoint.addin.macroEnabled.12
.xlw,app1ication/vnd.ms-excel
.rm,app1ication/vnd.rn-realmedia
.pdf,app1ication/pdf
.rar,app1ication/octet-stream
.psd,app1ication/octet-stream
.inf,app1ication/octet-stream
.emz,app1ication/octet-stream
.dsp,app1ication/octet-stream
.onea,app1ication/onenote
.jck,app1ication/liquidmotion
.mpe,video/mpeg
.mp2,video/mpeg
.sct,text/scriptlet
.ras,image/x-cmu-raster
.swf,app1ication/x-shockwave-flash
.wmz,app1ication/x-ms-wmz
.gtar,app1ication/x-gtar
.dcr,app1ication/x-director
.sldx,app1ication/vnd.openxmlformats-officedocument.presentationml.slide
.pps,app1ication/vnd.ms-pps
.p7m,app1ication/pkcs7-mime
.xsn,app1ication/octet-stream
.ocx,app1ication/octet-stream
.accde,app1ication/msaccess
.mov,video/quicktime
.wmls,text/vnd.wap.wmlscript
.cpp,text/plain
.c,text/plain
.bas,text/plain
.css,text/css
.art,image/x-jg
.mp3,audio/mpeg
.t,app1ication/x-troff
.roff,app1ication/x-troff
.tar,app1ication/x-tar
.hhc,app1ication/x-oleobject
.scd,app1ication/x-msschedule
.pko,app1ication/vnd.ms-pki.pko
.sst,app1ication/vnd.ms-pki.certstore
.ppt,app1ication/vnd.ms-powerpoint
.xtp,app1ication/octet-stream
.u32,app1ication/octet-stream
.pcx,app1ication/octet-stream
.msi,app1ication/octet-stream
.exe,app1ication/octet-stream
.asd,app1ication/octet-stream
.onetoc2,app1ication/onenote
.fif,app1ication/fractals
.mpg,video/mpeg
.vml,text/xml
.xdr,text/plain
.vcs,text/plain
.hxt,text/html
.eml,message/rfc822
.xpm,image/x-xpixmap
.ico,image/x-icon
.gif,image/gif
.dwf,drawing/x-dwf
.src,app1ication/x-wais-source
.tr,app1ication/x-troff
.pmr,app1ication/x-perfmon
.pma,app1ication/x-perfmon
.dll,app1ication/x-msdownload
.bcpio,app1ication/x-bcpio
.wmlc,app1ication/vnd.wap.wmlc
.wdb,app1ication/vnd.ms-works
.dotx,app1ication/vnd.openxmlformats-officedocument.wordprocessingml.template
.docx,app1ication/vnd.openxmlformats-officedocument.wordprocessingml.document
.pot,app1ication/vnd.ms-powerpoint
.xltm,app1ication/vnd.ms-excel.template.macroEnabled.12
.rtf,app1ication/rtf
.prf,app1ication/pics-rules
.snp,app1ication/octet-stream
.cab,app1ication/octet-stream
.avi,video/x-msvideo
.asf,video/x-ms-asf
.dtd,text/xml
.wml,text/vnd.wap.wml
.vbs,text/vbscript
.rtx,text/richtext
.dlm,text/dlm
.xwd,image/x-xwindowdump
.pgm,image/x-portable-graymap
.bmp,image/bmp
.crt,app1ication/x-x509-ca-cert
.ustar,app1ication/x-ustar
.tex,app1ication/x-tex
.sv4cpio,app1ication/x-sv4cpio
.tgz,app1ication/x-compressed
.cdf,app1ication/x-cdf
.vss,app1ication/vnd.visio
.cat,app1ication/vnd.ms-pki.seccat
.thmx,app1ication/vnd.ms-officetheme
.xlsm,app1ication/vnd.ms-excel.sheet.macroEnabled.12
.prx,app1ication/octet-stream
.pcz,app1ication/octet-stream
.onetmp,app1ication/onenote
.acx,app1ication/internet-property-stream
.wsdl,text/xml
.disco,text/xml
.xsd,text/xml
.wbmp,image/vnd.wap.wbmp
.png,image/png
.pnz,image/png
.smd,audio/x-smd
.smz,audio/x-smd
.smx,audio/x-smd
.mmf,app1ication/x-smaf

.docm,app1ication/vnd.ms-word.document.macroEnabled.12
.docx,app1ication/vnd.openxmlformats-officedocument.wordprocessingml.document
.dotm,app1ication/vnd.ms-word.template.macroEnabled.12
.dotx,app1ication/vnd.openxmlformats-officedocument.wordprocessingml.template
.potm,app1ication/vnd.ms-powerpoint.template.macroEnabled.12
.potx,app1ication/vnd.openxmlformats-officedocument.presentationml.template
.ppam,app1ication/vnd.ms-powerpoint.addin.macroEnabled.12
.ppsm,app1ication/vnd.ms-powerpoint.slideshow.macroEnabled.12
.ppsx,app1ication/vnd.openxmlformats-officedocument.presentationml.slideshow
.pptm,app1ication/vnd.ms-powerpoint.presentation.macroEnabled.12
.pptx,app1ication/vnd.openxmlformats-officedocument.presentationml.presentation
.xlam,app1ication/vnd.ms-excel.addin.macroEnabled.12
.xlsb,app1ication/vnd.ms-excel.sheet.binary.macroEnabled.12
.xlsm,app1ication/vnd.ms-excel.sheet.macroEnabled.12
.xlsx,app1ication/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.xltm,app1ication/vnd.ms-excel.template.macroEnabled.12
.xltx,app1ication/vnd.openxmlformats-officedocument.spreadsheetml.template

WebClient 使用

Sub DownloadFile(ByVal uri As String, ByVal destFile As String, _
Optional ByVal username As String = Nothing, Optional ByVal pwd As String = _
Nothing)
Dim wc As New System.Net.WebClient
If Not username Is Nothing AndAlso Not pwd Is Nothing Then
wc.Credentials = New System.Net.NetworkCredential(username, pwd)
End If

wc.DownloadFile(uri, destFile)
End Sub

Testing Command Line Arguments For Values

來源
--
' Loop through all the command line arguments given.
For I As Integer = 0 To My.Application.CommandLineArgs.Count - 1
' If an argument equals /m
If My.Application.CommandLineArgs.Item(I) = "/m" Then
MsgBox("You have used /m!")
Else ' If it doesn't equal "/m"
MsgBox("Incorrect CMD Argument.")
End If
Next

QuNect ODBC for QuickBase

網站
--
Application Note for QuNect ODBC for QuickBase

VB.Net Console Application for Copying Rows from a SQL Server Table to a QuickBase Table

This console application takes five command line arguments.
The first argument is the name of your SQL Server.
The second argument is your SQL Server username.
The third argument is your SQL Server password.
The fourth argument is the SQL Server database where the table in questions resides.
The fifth argument is the SQL Server table.
The SQL Server table should have as the last word in its name the DBID of the corresponding QuickBase table. You can find the DBID of your QuickBase table by reading the How to Find the DBID of a QuickBase Table application note. All columns in the SQL Server table will be copied to the columns of the same name in the QuickBase table. This piece of code relies on a properly configured ODBC Data Source called QuickBase via QuNect.

Imports System.Data.Odbc
Imports System.Data.SqlClient

Module SQLQuNectQuickBase

Dim quNectConn As OdbcConnection
Dim quNectCmd As OdbcCommand
Dim quNectCacheWritesCmd as OdbcCommand
Dim quNectFlushCmd As OdbcCommand
Dim quNectParam As OdbcParameter
Dim sqlConn As SqlConnection
Dim sqlComm As SqlCommand
Dim sqlDr As SqlDataReader

Sub Main()

If My.Application.CommandLineArgs.Count <> 5 Then
Console.WriteLine("Please supply: SQLserver SQLuser SQLpassword SQLDatabase SQLTable")
Console.WriteLine("The SQL table should have the QuickBase DBID as the last or only word in the table name.")
Exit Sub
End If
Dim argvServer As String = My.Application.CommandLineArgs.Item(0)
Dim argvUID As String = My.Application.CommandLineArgs.Item(1)
Dim argvPassword As String = My.Application.CommandLineArgs.Item(2)
Dim argvDatabase As String = My.Application.CommandLineArgs.Item(3)
Dim argvTable As String = My.Application.CommandLineArgs.Item(4)
quNectConn = New OdbcConnection("DSN=QuickBase via QuNect;")
Try
quNectConn.Open()
Catch excpt As Exception
Console.WriteLine(excpt.Message)
Exit Sub
End Try

'First let's open up a connection to SQL Server
Dim sqlConnectString As String = "server=" & argvServer & ";uid=" & argvUID & ";pwd=" & argvPassword & ";database=" & argvDatabase
sqlConn = New SqlConnection(sqlConnectString)
sqlConn.Open()
sqlComm = New SqlCommand("Select * from """ & argvTable & """", sqlConn)
Try
sqlDr = sqlComm.ExecuteReader()
Catch excpt As Exception
Console.WriteLine("SQL Server complained: " & excpt.Message)
Exit Sub
End Try

Dim fieldCount As Integer = sqlDr.FieldCount
Dim fieldCounter As Integer
Dim quickBaseSQLFieldList As String = "("
Dim quickBaseSQLParameterList As String = "("
Dim quickBaseSQL As String

For fieldCounter = 0 To fieldCount - 1
quickBaseSQLFieldList &= """" & sqlDr.GetName(fieldCounter).ToString() & ""","
quickBaseSQLParameterList &= "?,"
Next
quickBaseSQLFieldList = quickBaseSQLFieldList.Substring(0, quickBaseSQLFieldList.Length - 1) & ")"
quickBaseSQLParameterList = quickBaseSQLParameterList.Substring(0, quickBaseSQLParameterList.Length - 1) & ")"
quickBaseSQL = "INSERT INTO """ & argvTable & """ " & quickBaseSQLFieldList & " VALUES " & quickBaseSQLParameterList

quNectCmd = New OdbcCommand(quickBaseSQL, quNectConn)
For fieldCounter = 0 To fieldCount - 1
Dim thisODBCType As Odbc.OdbcType
If sqlDr.GetFieldType(fieldCounter).Name = "String" Then
thisODBCType = OdbcType.NVarChar
ElseIf sqlDr.GetFieldType(fieldCounter).Name = "Double" Then
thisODBCType = OdbcType.Double
ElseIf sqlDr.GetFieldType(fieldCounter).Name = "DateTime" Then
thisODBCType = OdbcType.DateTime
ElseIf sqlDr.GetFieldType(fieldCounter).Name = "Date" Then
thisODBCType = OdbcType.Date
ElseIf sqlDr.GetFieldType(fieldCounter).Name = "Money" Then
thisODBCType = OdbcType.Numeric
ElseIf sqlDr.GetFieldType(fieldCounter).Name = "Bit" Then
thisODBCType = OdbcType.Bit
ElseIf sqlDr.GetFieldType(fieldCounter).Name.Contains("Char") Then
thisODBCType = OdbcType.VarChar
ElseIf sqlDr.GetFieldType(fieldCounter).Name = "Decimal" Then
thisODBCType = OdbcType.Decimal
End If
quNectParam = New OdbcParameter("@qdb" & fieldCounter, thisODBCType)
quNectCmd.Parameters.Add(quNectParam)
Next

While sqlDr.Read()
For fieldCounter = 0 To fieldCount - 1
quNectCmd.Parameters(fieldCounter).Value = sqlDr(fieldCounter)
Next fieldCounter
Try
quNectCmd.ExecuteNonQuery()
Catch excpt As Exception
Console.WriteLine(excpt.Message)
End Try

End While
sqlDr.Close()
sqlConn.Close()
quNectConn.Close()
End Sub

End Module

Process Start

來源處

Module Module1
Sub Main()
' One file parameter to the executable
Dim sourceName As String = "ExampleText.txt"
' The second file parameter to the executable
Dim targetName As String = "Example.gz"

' New ProcessStartInfo created
Dim p As New ProcessStartInfo

' Specify the location of the binary
p.FileName = "C:\7za.exe"

' Use these arguments for the process
p.Arguments = "a -tgzip """ & targetName & """ """ & sourceName & """ -mx=9"

' Use a hidden window
p.WindowStyle = ProcessWindowStyle.Hidden

' Start the process
Process.Start(p)
End Sub
End Module

2010年12月15日 星期三

winform 呼叫 console 使用

1.
Imports System.Runtime.InteropServices

2.
_
Public Shared Function AllocConsole() As Boolean
End Function
_
Public Shared Function FreeConsole() As Boolean
End Function

請參考詳細:
WinForm程序中使用控制台作为输出窗口

2010年12月11日 星期六

DevExpress 安装、升级(vs2005/2008)

很詳細
----------
因我有使用 DevExpress 的免費工具,還很不錯
不小心試安裝了其他協力廠商的元件;竟發生VS 載入失敗...
真是可怕..還好DevExpress本身也已知道會發生這問題,特有一支重新註冊 VS2005/vs2008 的工具
一定要使用:{開始}->{程式集}->{Developer Express v2009 vol 2}->
->{Components}->{Tools}->{ToolboxCreator} <--執行後,再開 VS 2008 就回來了!!

2010年12月9日 星期四

使用Visual C#实现断点续传

原處
在了解HTTP断点续传的原理之前,让我们先来了解一下HTTP协议,HTTP协议是一种基于tcp的简单协议,分为请求和回复两种。请求协议是由客户机(浏览器)向服务器(WEB SERVER)提交请求时发送报文的协议。回复协议是由服务器(web server),向客户机(浏览器)回复报文时的协议。请求和回复协议都由头和体组成。头和体之间以一行空行为分隔。

  以下是一个请求报文与相应的回复报文的例子:
GET /image/index_r4_c1.jpg HTTP/1.1
Accept: */*
Referer: http://192.168.3.120:8080
Accept-Language: zh-cn
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.0.3705)
Host: 192.168.3.120:8080
Connection: Keep-Alive


HTTP/1.1 200 OK
Server: Microsoft-IIS/5.0
Date: Tue, 24 Jun 2003 05:39:40 GMT
Content-Type: image/jpeg
Accept-Ranges: bytes
Last-Modified: Thu, 23 May 2002 03:05:40 GMT
ETag: "bec48eb862c21:934"
Content-Length: 2827

….

  下面我们就来说说"断点续传",顾名思义,断点续传就是在上一次下载时断开的位置开始继续下载。
在HTTP协议中,可以在请求报文头中加入Range段,来表示客户机希望从何处继续下载。


  比如说从第1024字节开始下载,请求报文如下:


GET /image/index_r4_c1.jpg HTTP/1.1
Accept: */*
Referer: http://192.168.3.120:8080
Accept-Language: zh-cn
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.0.3705)
Host: 192.168.3.120:8080
Range:bytes=1024-
Connection: Keep-Alive

  .NET中的相关类

  明白了上面的原理,那么,我们来看看.NET FRAMEWORK中为我们提供了哪些类可以来做这些事。

  完成HTTP请求

System.Net.HttpWebRequest

  HttpWebRequest 类对 WebRequest 中定义的属性和方法提供支持,也对使用户能够直接与使用 HTTP 的服务器交互的附加属性和方法提供支持。

  HttpWebRequest 将发送到 Internet 资源的公共 HTTP 标头值公开为属性,由方法或系统设置。下表包含完整列表。可以将 Headers 属性中的其他标头设置为名称/值对。但是注意,某些公共标头被视为受限制的,它们或者直接由 API公开,或者受到系统保护,不能被更改。Range也属于被保护之列,不过,.NET为开发者提供了更方便的操作,就是 AddRange方法,向请求添加从请求数据的开始处或结束处的特定范围的字节范围标头

  完成文件访问

System.IO.FileStream

  FileStream 对象支持使用Seek方法对文件进行随机访问, Seek 允许将读取/写入位置移动到文件中的任意位置。这是通过字节偏移参考点参数完成的。字节偏移量是相对于查找参考点而言的,该参考点可以是基础文件的开始、当前位置或结尾,分别由SeekOrigin类的三个属性表示。

  代码实现

  了解了.NET提供的相关的类,那么,我们就可以方便的实现了。

  代码如下:


static void Main(string[] args)
{

string StrFileName="c:\\aa.zip"; //根据实际情况设置
string StrUrl="http://www.xxxx.cn/xxxxx.zip"; //根据实际情况设置

//打开上次下载的文件或新建文件
long lStartPos =0;
System.IO.FileStream fs;
if (System.IO.File.Exists(StrFileName))
{
fs= System.IO.File.OpenWrite(StrFileName);
lStartPos=fs.Length;
fs.Seek(lStartPos,System.IO.SeekOrigin.Current); //移动文件流中的当前指针
}
else
{
fs = new System.IO.FileStream(StrFileName,System.IO.FileMode.Create);
lStartPos =0;
}

//打开网络连接
try
{
System.Net.HttpWebRequest request =(System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(StrUrl);
if ( lStartPos>0)
request.AddRange((int)lStartPos); //设置Range值

//向服务器请求,获得服务器回应数据流
System.IO.Stream ns= request.GetResponse().GetResponseStream();

byte[] nbytes = new byte[512];
int nReadSize=0;
nReadSize=ns.Read(nbytes,0,512);
while( nReadSize >0)
{
fs.Write(nbytes,0,nReadSize);
nReadSize=ns.Read(nbytes,0,512);
}
fs.Close();
ns.Close();
Console.WriteLine("下载完成");
}
catch(Exception ex)
{
fs.Close();
Console.WriteLine("下载过程中出现错误:"+ex.ToString());
}
}

输出硬盘文件,提供下载 支持大文件、续传、速度限制、资源占用小

原文
--
///
/// 输出硬盘文件,提供下载 支持大文件、续传、速度限制、资源占用小
///

/// Page.Request对象
/// Page.Response对象
/// 下载文件名
/// 带文件名下载路径
/// 每秒允许下载的字节数
/// True Or False
public bool ResponseFile(HttpRequest MyRequest, HttpResponse MyResponse, string MyFileName, string MyFullPath, long MySpeed)
{
try
{
FileStream myFile = new FileStream(MyFullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
BinaryReader br = new BinaryReader(myFile);
try
{
MyResponse.AddHeader("Accept-Ranges", "bytes");
MyResponse.Buffer = false;

long fileLength = myFile.Length;
long startBytes = 0;
int pack = 10240; //10K bytes
int sleep = (int)Math.Floor(1000.0 * pack / MySpeed) + 1;

if (MyRequest.Headers["Range"] != null)
{
MyResponse.StatusCode = 206;
string[] range = MyRequest.Headers["Range"].Split(new char[] { '=', '-' });
startBytes = Convert.ToInt64(range[1]);
}

MyResponse.AddHeader("Content-Length", (fileLength - startBytes).ToString());

if ((startBytes != 0))
{
MyResponse.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
}

MyResponse.AddHeader("Connection", "Keep-Alive");
MyResponse.ContentType = "application/octet-stream";
MyResponse.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(MyFileName, System.Text.Encoding.UTF8));
br.BaseStream.Seek(startBytes, SeekOrigin.Begin);

int maxCount = (int)Math.Floor(1.0*(fileLength - startBytes) / pack) + 1;

for (int i = 0; i <= maxCount; i++)
{
if ((MyResponse.IsClientConnected))
{
MyResponse.BinaryWrite(br.ReadBytes(pack));
System.Threading.Thread.Sleep(sleep);
}
else
{
i = maxCount;
}
}
}
catch
{
return false;
}
finally
{
br.Close();myFile.Close();
}
}
catch
{
return false;
}
return true;
}

直接调用就行了.如
ResponseFile(Request, Response, "MyText.txt", @"D:\testtable.txt", 200 * 1024);

在WinForm中使用Web Services 來實現 軟件 自動升級( Auto Update )

來源處
winform程序相對web程序而言,功能更強大,編程更方便,但軟件更新卻相當麻煩,要到客戶端一台一台地升級,面對這個實際問題,在最近的一個小項目中,本人設計了一個通過軟件實現自動升級技術方案,彌補了這一缺陷,有較好的參考價值。

一、升級的好處。
長期以來,廣大程序員為到底是使用Client/Server,還是使用Browser/Server結構爭論不休,在這些爭論當中,C/S結構的程序的可維護性差,佈置困難,升級不方便,維護成本高就是一個相當重要的因素,也是那些B/S的支持者們將Client/Server結構打入地獄的一個重要原因。

現在好了,我們就在最新的基於Microsoft 的 WinForm上用WebServices來實現軟件的自動升級功能。

二、升級的技術原理。
升級的原理有好幾個,首先無非是將現有版本與最新版本作比較,發現最新的則提示用戶是否升級。當然也有人用其它屬性比較的,例如:文件大小。:) 或者更新日期。
而實現的方法呢?在VB時代,我使用的是XmlHTTP+INet控件。用XmlHTTP獲取信息,用INET傳輸升級文件,而用一個簡單的BAT文件來實現升級。

Public Sub CheckUpdate()
On Error Resume Next
Dim b As Boolean
Dim XmlHttp As Object
Set XmlHttp = CreateObject("Microsoft.XMLHttp")
XmlHttp.Open "GET", "Http://mu.5inet.net/MuAdmin/update.xml", False
XmlHttp.Send

Dim vs As String
vs = XmlHttp.responseText
If Err.Number > 0 Then
Exit Sub
End If

Dim Xml As Object
Set Xml = CreateObject("Microsoft.XmlDom")
Xml.LoadXml vs
Dim Version As String
Dim downAddr As String
Dim FSize As Long
Dim fInfo As String
Version = Xml.DocumentElement.ChildNodes(0).Text
downAddr = Xml.DocumentElement.ChildNodes(1).Text
FSize = CLng(Xml.DocumentElement.ChildNodes(2).Text)
fInfo = Xml.DocumentElement.ChildNodes(3).Text
Set Xml = Nothing
Set XmlHttp = Nothing

Dim Major As Long
Dim Minor As Long
Dim Revision As Long
Dim C() As String
C = Split(Version, ".")
Major = CLng(C(0))
Minor = CLng(C(1))
Revision = CLng(C(2))

If Major > App.Major Then
b = True
ElseIf Minor > App.Minor Then
b = True
ElseIf Revision > App.Revision Then
b = True
Else
b = False
End If
If (b) Then
Dim result As VbMsgBoxResult
result = MsgBox("發現程序新版本。當前版本為:" & App.Major & "." & App.Minor & "." & App.Revision & ",目前最新版本為:" & Version & ",是否進行更新?", vbQuestion Or vbYesNo, "自動更新")
If result = vbYes Then
Dim frm As New Update
frm.DownloadAddress = downAddr
frm.size = FSize
frm.InfoPage = fInfo
frm.Version = Version
frm.Show vbModal
End If
End If
End Sub


而BAT文件有個特性,是可以刪除自己本身。下面是BAT文件的內容.
@echo off
echo
echo echo 歡迎使用無垠奇跡管理器升級嚮導。
echo 本次升級版本為:1.1.0。
echo 請按任意鍵開始升級無垠奇跡管理器... echo
echo
pause
del SQLSrvBrowser.Exe
ren ~update.tmp SQLSrvBrowser.Exe
echo 升級成功,按任意鍵重新啟動應用程序。
pause
start http://mu.5inet.net/
start SQLSrvBrowser.Exe
del update.bat


三、在.Net時代的實現。
在.Net時代,我們就有了更多的選擇,可以使用WebRequest,也可以使用WebServices。在這裡我們將用WebServices來實現軟件的自動升級。

實現原理:在WebServices中實現一個GetVer的WebMethod方法,其作用是獲取當前的最新版本。
  然後將現在版本與最新版本比較,如果有新版本,則進行升級。

  步驟:
    1、準備一個XML文件 (Update.xml)。


1.0.1818.42821
修正一些Bug















作用是作為一個升級用的模板。
    2、WebServices的GetVer方法。


[WebMethod(Description="取得更新版本")]
public string GetVer()
{
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("update.xml"));
XmlElement root = doc.DocumentElement;
return root.SelectSingleNode("version").InnerText;
}
     3、WebServices的GetUpdateData方法。
[WebMethod(Description="在線更新軟件")]
[SoapHeader("sHeader")]
public System.Xml.XmlDocument GetUpdateData()
{
//驗證用戶是否登陸
if(sHeader==null)
return null;
if(!DataProvider.GetInstance.CheckLogin(sHeader.Username,sHeader.Password))
return null;
//取得更新的xml模板內容
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("update.xml"));
XmlElement root = doc.DocumentElement;
//看看有幾個文件需要更新
XmlNode updateNode = root.SelectSingleNode("filelist");
string path = updateNode.Attributes["sourcepath"].Value;
int count = int.Parse(updateNode.Attributes["count"].Value);
//將xml中的value用實際內容替換
for(int i=0;i{
XmlNode itemNode = updateNode.ChildNodes[i];
string fileName = path + itemNode.Attributes["name"].Value;
FileStream fs = File.OpenRead(Server.MapPath(fileName));
itemNode.Attributes["size"].Value = fs.Length.ToString();
BinaryReader br = new BinaryReader(fs);
//這裡是文件的實際內容,使用了Base64String編碼
itemNode.SelectSingleNode("value").InnerText = Convert.ToBase64String(br.ReadBytes((int)fs.Length),0,(int)fs.Length);
br.Close();
fs.Close();
}
return doc;
}
    4、在客戶端進行的工作。
      首先引用此WebServices,例如命名為:WebSvs,
string nVer = Start.GetService.GetVer(); 
if(Application.ProductVersion.CompareTo(nVer)<=0)
update();

在本代碼中 Start.GetService是WebSvs的一個Static 實例。首先檢查版本,將結果與當前版本進行比較,如果為新版本則執行UpDate方法。 void update()
{
this.statusBarPanel1.Text = "正在下載...";
System.Xml.XmlDocument doc = ((System.Xml.XmlDocument)Start.GetService.GetUpdateData());
doc.Save(Application.StartupPath + @"\update.xml");
System.Diagnostics.Process.Start(Application.StartupPath + @"\update.exe");
Close();
Application.Exit();
}這裡為了簡單起見,沒有使用異步方法,當然使用異步方法能更好的提高客戶體驗,這個需要讀者們自己去添加。:) update的作用是將升級的XML文件下載下來,保存為執行文件目錄下的一個Update.xml文件。任務完成,退出程序,等待Update.Exe 來進行升級。     5、Update.Exe 的內容。 private void Form1_Load(object sender, System.EventArgs e)
{
System.Diagnostics.Process[] ps = System.Diagnostics.Process.GetProcesses();
foreach(System.Diagnostics.Process p in ps)
{
//MessageBox.Show(p.ProcessName);
if(p.ProcessName.ToLower()=="customerapplication")
{
p.Kill();
break;
}
}
XmlDocument doc = new XmlDocument();
doc.Load(Application.StartupPath + @"\update.xml");
XmlElement root = doc.DocumentElement;
XmlNode updateNode = root.SelectSingleNode("filelist");
string path = updateNode.Attributes["sourcepath"].Value;
int count = int.Parse(updateNode.Attributes["count"].Value);
for(int i=0;i{
XmlNode itemNode = updateNode.ChildNodes[i];
string fileName = itemNode.Attributes["name"].Value;
FileInfo fi = new FileInfo(fileName);
fi.Delete();
//File.Delete(Application.StartupPath + @"\" + fileName);
this.label1.Text = "正在更新: " + fileName + " (" + itemNode.Attributes["size"].Value + ") ...";
FileStream fs = File.Open(fileName,FileMode.Create,FileAccess.Write);
fs.Write(System.Convert.FromBase64String(itemNode.SelectSingleNode("value").InnerText),0,int.Parse(itemNode.Attributes["size"].Value));
fs.Close();
}
label1.Text = "更新完成";
File.Delete(Application.StartupPath + @"\update.xml");
label1.Text = "正在重新啟動應用程序...";
System.Diagnostics.Process.Start("CustomerApplication.exe");
Close();
Application.Exit();
} 這個代碼也很容易懂,首先就是找到主進程,如果沒有關閉,則用Process.Kill()來關閉主程序。然後則用一個XmlDocument來Load程序生成的update.xml文件。用xml文件裡指定的路徑和文件名來生成指定的文件,在這之前先前已經存在的文件刪除。更新完畢後,則重新啟動主應用程序。這樣更新就完成了。
四、總結:
  從這個實例看來,WebService的工作是很簡單的,也是很容易實現的。好好的使用WebService能夠為我們的程序帶來很多新的,強的功能。總而言之,.Net是易用的,強大的語言。如果大家對本代碼有任何意見,歡迎光臨《開發者》論壇: http://forums.coder.cn/ ,希望和大家共同探討。
此文亦發表在本人Blog上:http://blogs.coder.cn/skyover/archive/2004/06/07/485.aspx

2010年12月7日 星期二

EnterSources

不錯的站
---
Languages
C / C++ Language
C++ / CLI
C Sharp
MSIL
VBScript
VB.NET
VB6 Interop
Other .NET Languages
XML
Java
Perl

微軟:非同步伺服器通訊端範例

非同步伺服器通訊端範例

VB.net檔案傳輸

Imports System.Net
Imports System.Net.NetworkInformation
Imports System.Net.Sockets
Imports System.Text.Encoding
Public Module FileTransfer
Private Const BufferSize As Integer = 16384
Private Const Port As Integer = 2070
'''
''' 捕獲外來訊息的伺服器類別
'''

'''
Public Class FileServer
Public Shared Mainform As Form1
Public Port As Integer = FileTransfer.Port
Private ServerSocket As Socket
Public Sub New(ByRef form As Form)
Mainform = form
ServerSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
Dim ipen As IPHostEntry = Dns.GetHostEntry(Dns.GetHostName)
Dim endpoint = New IPEndPoint(IPAddress.Any, Port)
ServerSocket.Bind(endpoint)
ServerSocket.Listen(1000)
ServerSocket.BeginAccept(AddressOf CatchSocket, ServerSocket)
End Sub
'捕捉新連線
Public Sub CatchSocket(ByVal result As IAsyncResult)
'重新導向到轉接器
Dim TIO As New TempInterObject(ServerSocket.EndAccept(result))
TIO.Sock.ReceiveBufferSize = BufferSize
'開始處理基本傳輸資料
TIO.Sock.BeginReceive(TIO.Buffer, 0, TIO.Buffer.Length, 0, AddressOf InfoWorker, TIO)
ServerSocket.BeginAccept(AddressOf CatchSocket, ServerSocket)
End Sub
'處理開頭資料
Public Sub InfoWorker(ByVal result As IAsyncResult)
Dim TIO As TempInterObject = CType(result.AsyncState, TempInterObject)
Dim len As Integer = TIO.Sock.EndReceive(result)
Dim Src As String = UTF8.GetString(TIO.Buffer, 0, len)
Dim Command As String = Src.Substring(0, Src.IndexOf(" "))
Dim File As String = Src.Substring(Src.IndexOf(" ") + 1)
Dim nTask As TransferTask
If Command = "GET" Then '對方要求檔案
nTask = New TransferTask(File, TIO.Sock, TransferTask.Method.SEND) '發送檔案資訊->傳輸檔案
Else '對方要求傳送檔案給本機
Dim Sign(0) As Byte
Sign(0) = IIf(My.Computer.FileSystem.FileExists(File), 0, 1) '如果檔案存在則不允許
TIO.Sock.Send(Sign, 1, SocketFlags.None) '傳送准許憑證
nTask = New TransferTask(File, TIO.Sock, TransferTask.Method.GET) '開始下載
nTask.FileSize = Val(Command.Substring(Command.IndexOf("[") + 1, Command.IndexOf("]") - Command.IndexOf("["))) '分析檔案大小
End If
End Sub
End Class
'''
''' 轉接Socket用的暫時類別
'''

'''
Public Class TempInterObject
Public Buffer(BufferSize - 1) As Byte
Public Sock As Socket
Public Sub New(ByVal SocketObject As Socket)
Me.Sock = SocketObject
End Sub
End Class
'''
''' 傳送檔案 控制類別("下載工作"物件)
'''

'''
Public Class TransferTask
Public Enum Method
[GET] = 0
[SEND] = 1
End Enum
Public FilePath As String = ""
Public Host As String = "", Port As Integer = FileTransfer.Port
Private Data(BufferSize - 1) As Byte
Private Reader As IO.FileStream
Private Sock As Socket
Private WriteStream As IO.FileStream
Protected Friend FileSize As UInteger = 0
Private ReadSize As UInteger = 0
Private LastProgress As Integer = 0
Private mType As Method = 0
Private Delegate Sub InvokeFinished(ByVal [Error] As Boolean)
Private FinishedInvoker As New InvokeFinished(AddressOf onProgressFinished)
'接收檔案(主動)
Private Sub GetNew(ByVal File As String, ByVal LocalFile As String, ByVal Host As String)
Sock = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
Sock.Connect(Host, Port)
FilePath = LocalFile
Sock.SendBufferSize = BufferSize
SendString("GET " & File)
Sock.BeginReceive(Data, 0, Data.Length, SocketFlags.None, AddressOf GetSize, Me)
End Sub
'傳送檔案(主動)
Private Sub SendNew(ByVal File As String, ByVal RemoteFile As String, ByVal Host As String)
Sock = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
Sock.Connect(Host, Port)
FilePath = File
Sock.SendBufferSize = BufferSize
FileSize = GetFileSize(File)
SendString("SEND[" & FileSize & "] " & RemoteFile)
'偵測憑證
Sock.BeginReceive(Data, 0, 1, SocketFlags.None, AddressOf Accepted, Me)
End Sub
'傳送或接收檔案(主動)
Public Sub New(ByVal FileA As String, ByVal FileB As String, ByVal Host As String, ByVal Type As Method, Optional ByVal Port As Integer = 2070)
mType = Type
Me.Host = Host
Me.Port = Port
If Type = Method.GET Then GetNew(FileA, FileB, Host) Else SendNew(FileA, FileB, Host)
End Sub
'傳送或接收檔案(被動)
Public Sub New(ByVal File As String, ByVal Sock As Socket, ByVal Type As Method)
mType = Type
Me.Sock = Sock
FilePath = File
Sock.SendBufferSize = BufferSize
If Type = Method.SEND Then
'傳送檔案
'送出檔案大小
FileSize = GetFileSize(File)
SendString(FileSize)
'偵測憑證
Sock.BeginReceive(Data, 0, 1, SocketFlags.None, AddressOf Accepted, Me)
Else
'接收檔案
Sock.BeginReceive(Data, 0, Data.Length, SocketFlags.None, AddressOf Recived, Me)
End If
End Sub
'對方准許我方傳送
Private Sub Accepted(ByVal Result As IAsyncResult)
Sock.EndReceive(Result)
If Data(0) = 0 Then
onProgressFinished(True)
Sock.Close()
Exit Sub
End If
Reader = New IO.FileStream(FilePath, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read)
If Reader.Length < BufferSize Then
System.Array.Resize(Data, Reader.Length)
End If
Reader.BeginRead(Data, 0, Data.Length, AddressOf FileReaded, Me)
End Sub
'我方接收檔案串流
Private Sub Recived(ByVal result As IAsyncResult)
'讀取
Dim Len As Integer = 0
Try
Len = Sock.EndReceive(result)
Catch : End Try
If Len = 0 Then
Sock.Shutdown(SocketShutdown.Both)
Sock.Close()
If WriteStream IsNot Nothing Then
'下載終了
WriteStream.Close()
WriteStream.Dispose()
End If
onProgressFinished(False)
Exit Sub
End If
If WriteStream Is Nothing Then
WriteStream = New IO.FileStream(FilePath, IO.FileMode.Append)
End If
'修改進度!
ReadSize += Len
onProgressChanged()
WriteStream.Write(Data, 0, Len)
Try
Sock.BeginReceive(Data, 0, Data.Length, SocketFlags.None, AddressOf Recived, Me)
Catch
WriteStream.Close()
WriteStream.Dispose()
onProgressFinished(Not ReadSize = Len)
End Try
End Sub
'取得被動的對方傳送的檔案大小
Private Sub GetSize(ByVal result As IAsyncResult)
Dim Len As Integer = Sock.EndReceive(result)
FileSize = Val(UTF8.GetString(Data, 0, Len))
Dim Sign(0) As Byte
Sock.Send(Sign, 1, SocketFlags.None)
Sock.BeginReceive(Data, 0, Data.Length, SocketFlags.None, AddressOf Recived, Me)
End Sub
'傳送字串
Private Sub SendString(ByVal msg As String)
Dim Buffer() As Byte = System.Text.Encoding.UTF8.GetBytes(msg)
Sock.BeginSend(Buffer, 0, Buffer.Length, SocketFlags.None, AddressOf StringSended, Sock)
End Sub
'傳送字串的End偵聽函式
Private Sub StringSended(ByVal result As IAsyncResult)
Try : CType(result.AsyncState, Socket).EndSend(result) : Catch : End Try
End Sub
'傳送串流的End偵聽函式
Private Sub StreamSended(ByVal result As IAsyncResult)
Sock.EndSend(result) '結束非同步傳送Stream
If Reader.Length <= Reader.Position Then '如果讀到盡頭
Sock.Close()
Reader.Close()
Reader.Dispose()
onProgressFinished(False)
Exit Sub
End If
If Reader.Length - Reader.Position < BufferSize Then '如果剩下位傳送的位元組不到BufferSize
System.Array.Resize(Data, Reader.Length - Reader.Position)
End If
ReadSize += Data.Length '增加進度
onProgressChanged()
Reader.BeginRead(Data, 0, Data.Length, AddressOf FileReaded, Me)
End Sub
'讀取串流的End偵聽函式
Private Sub FileReaded(ByVal result As IAsyncResult)
Reader.EndRead(result) '結束非同步讀取Stream
Sock.BeginSend(Data, 0, Data.Length, SocketFlags.None, AddressOf StreamSended, Me) '開始傳送資料
End Sub
'進度改變檢測
Private Sub onProgressChanged()
If FileServer.Mainform.InvokeRequired Then
FileServer.Mainform.BeginInvoke(New MethodInvoker(AddressOf onProgressChanged))
Exit Sub
End If
If Int(Progress) - LastProgress > 0 Then
RaiseEvent ProgressChanged(Me, Progress)
End If
LastProgress = Int(Progress)
End Sub
'結束下載
Private Sub onProgressFinished(ByVal [Error] As Boolean)
If FileServer.Mainform.InvokeRequired Then
FileServer.Mainform.BeginInvoke(FinishedInvoker, [Error])
Exit Sub
End If
RaiseEvent ProgressChanged(Me, 100)
RaiseEvent ProgressFinished(Me, [Error])
End Sub
'屬性
Public ReadOnly Property Progress() As Single
Get
If FileSize > 0 Then
Return (ReadSize / FileSize) * 100
Else
Return 0
End If
End Get
End Property
Public ReadOnly Property Length() As UInteger
Get
Return FileSize
End Get
End Property
Public ReadOnly Property Type() As Method
Get
Return mType
End Get
End Property
'''
''' 當下載進度改變時呼叫
'''

''' "下載工作"物件
''' 進度(百分比)
'''
Public Event ProgressChanged(ByVal Sender As TransferTask, ByVal value As Integer)
'''
''' 下載完成時呼叫
'''

''' "下載工作"物件
''' 是否錯誤
'''
Public Event ProgressFinished(ByVal Sender As TransferTask, ByVal [Error] As Boolean)
End Class
'''
''' 取得檔案大小
'''

''' 檔案路徑
''' 檔案大小(位元組)
'''
Public Function GetFileSize(ByVal Path As String) As Integer
Return My.Computer.FileSystem.GetFileInfo(Path).Length
End Function
'''
''' 非同步傳送檔案
'''

''' 本機檔案(被傳送的)
''' 遠端位置(被傳送後要放置的位置)
''' 遠端主機
''' 結束時呼叫
''' 進度更新呼叫
'''
Public Sub BeginTransFile(ByVal Local As String, ByVal Remote As String, ByVal Host As String, Optional ByVal onEnd As TransferTask.ProgressFinishedEventHandler = Nothing, Optional ByVal onChange As TransferTask.ProgressChangedEventHandler = Nothing)
Dim Task As New TransferTask(Local, Remote, Host, TransferTask.Method.SEND)
If onEnd IsNot Nothing Then AddHandler Task.ProgressFinished, onEnd
If onChange IsNot Nothing Then AddHandler Task.ProgressChanged, onChange
End Sub
'''
''' 非同步下載檔案
'''

''' 本機檔案(被傳送後要放置的位置)
''' 遠端位置(被傳送的)
''' 遠端主機
''' 結束時呼叫
''' 進度更新呼叫
'''
Public Sub BeginGetFile(ByVal Remote As String, ByVal Local As String, ByVal Host As String, Optional ByVal onEnd As TransferTask.ProgressFinishedEventHandler = Nothing, Optional ByVal onChange As TransferTask.ProgressChangedEventHandler = Nothing)
Dim Task As New TransferTask(Remote, Local, Host, TransferTask.Method.GET)
If onEnd IsNot Nothing Then AddHandler Task.ProgressFinished, onEnd
If onChange IsNot Nothing Then AddHandler Task.ProgressChanged, onChange
End Sub
End Module

vbnet socket 傳檔+續傳

來源處

---
主機端:
' 宣告儲存二進位檔案通道編號的變數
Dim FileNo As Integer
' 儲存接收檔案的檔案名稱變數
Dim RecvFileName As String

Private Sub Form_Load()
' 初始化各種控制項的相關屬性值
Label2.Caption = "接收位元組"
Label3.Caption = "0"
Me.Caption = "EX1004 主機端"
Timer1.Interval = 100

' 初始化二組Winsock控制項
' Winsock1用來傳送溝通訊息
Winsock1.Protocol = sckTCPProtocol
Winsock1.LocalPort = 6000
Winsock1.Listen
' Winsock2用來傳送檔案內容
Winsock2.Protocol = sckTCPProtocol
Winsock2.LocalPort = Winsock1.LocalPort + 1
Winsock2.Listen
End Sub

Private Sub Timer1_Timer()
' 判斷Winsock控制項的狀態
Select Case Winsock1.State
Case sckClosed ' 常數值0
Label1.Caption = "已經關閉用戶端連線"
Case sckOpen ' 常數值1
Label1.Caption = "開啟"
Case sckListening ' 常數值2
Label1.Caption = "監聽中..."
Case sckConnectionPending ' 常數值3
Label1.Caption = "尚未連連線"
Case sckResolvingHost ' 常數值4
Label1.Caption = "主機解析中"
Case sckHostResolved ' 常數值5
Label1.Caption = "主機解析完畢"
Case sckConnecting ' 常數值6
Label1.Caption = "連線中..."
Case sckConnected ' 常數值7
Label1.Caption = "已經連線"
Case sckClosing ' 常數值8
Label1.Caption = "正在關閉連線"
' 判斷Winsock控制項的連線狀態
If Winsock1.State <> sckClosed Then
' 關閉Winsock1控制項現有的連線作業
Winsock1.Close
DoEvents
' 將Winsock1控制項設定在監聽模式
Winsock1.Listen
' 關閉Winsock2控制項現有的連線作業
Winsock2.Close
DoEvents
Winsock2.Listen
End If
End Select
End Sub

Private Sub Winsock1_ConnectionRequest(ByVal RequestID As Long)
If Winsock1.State <> sckClosed Then Winsock1.Close
' 允許遠端設備使用必要的識別碼(RequestID)與主機
' 進行連接。
Winsock1.Accept RequestID
End Sub

Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long)
Dim sVar As String
Dim OldLength As Long
Dim FileNo1 As Integer
Dim Buffers() As Byte
Winsock1.GetData sVar, vbString
Select Case Mid(sVar, 1, 4)
' 用戶端傳來檔案名稱表示準備傳送檔案,
' 並等候主機端的回應
Case "檔案名稱"
' 檔案名稱文字之後,即為即將接收的檔案名稱
RecvFileName = Mid(sVar, 5)
If Len(Dir$(RecvFileName)) > 0 Then
' 檔案存在
OldLength = FileLen(RecvFileName)
Name App.Path & "\" & RecvFileName As App.Path & "\TEMP.BIN"
DoEvents
End If
' 重新設定顯示接收位元組的Label3控制項
Label3.Caption = "0"
' 取得可用的檔案通道
FileNo = FreeFile
' 以二進位檔案寫入模式,開啟指定的檔案開啟
Open App.Path & "\" & RecvFileName For Binary Access Write As #FileNo
' 依據 OldLength變數的值,判斷是否需要續傳
If OldLength > 0 Then
FileNo1 = FreeFile
' 開啟暫存檔
Open App.Path & "\TEMP.BIN" For Binary Access Read As #FileNo1
' 將暫存檔的內容全數讀入緩衝區位元組陣列
ReDim Buffers(OldLength - 1)
Get #FileNo1, , Buffers
DoEvents
' 將暫存檔的內容寫入即將續傳的檔案中
Put #FileNo, , Buffers
Close #FileNo1
DoEvents
' 刪除暫存檔
Kill App.Path & "\TEMP.BIN"
DoEvents
' 回傳『斷點續傳』訊息 + 已經接收的檔案位元組數量
Winsock1.SendData "斷點續傳" & OldLength
Else
' 回傳主機端已經開啟二進位檔案的寫入模式
Winsock1.SendData "準備就緒"
End If
Case "傳送檔案"
Label1.Caption = "傳送檔案"
Case "傳送完畢"
' 關閉已經開啟的通道
Close #FileNo
FileNo = 0
' 回傳主機端已經接收完畢
Winsock1.SendData "資料接收完畢"
DoEvents
End Select
End Sub

Private Sub Winsock2_ConnectionRequest(ByVal RequestID As Long)
If Winsock2.State <> sckClosed Then Winsock2.Close
' 允許遠端設備使用必要的識別碼(RequestID)與主機
' 進行連接。
Winsock2.Accept RequestID
End Sub

Private Sub Winsock2_DataArrival(ByVal bytesTotal As Long)
Dim sVar() As Byte
' 從 FileNo變數的值,可以判定二進位檔案寫入模式是否已經準備就緒
If FileNo > 0 Then
' 讀取 Winsock2 控制項的接收緩衝區
Winsock2.GetData sVar, vbByte
' 將位元組陣列寫入檔案
Put #FileNo, , sVar
Winsock1.SendData "資料接收中"
' 更新已經接收位元組數量的資訊
Label3.Caption = CLng(Label3.Caption) + UBound(sVar, 1) + 1
End If
End Sub



---
用戶端(用來傳送檔案):
' 宣告用來儲存將要傳送檔案名稱的變數
Dim SendFileName As String

' 按下『連線』按鈕
Private Sub Command1_Click()
' 關閉 Winsock1、Winsock2控制項的目前連線
If Winsock1.State <> sckClosed Then
Winsock1.Close
End If
If Winsock2.State <> scckclosed Then
Winsock2.Close
End If
' 初始化Winsock1控制項和Winsock2控制項
Winsock1.Protocol = sckTCPProtocol
Winsock1.RemoteHost = Text1.Text
Winsock1.RemotePort = CLng(Text2.Text)
Winsock2.Protocol = sckTCPProtocol
Winsock2.RemoteHost = Text1.Text
Winsock2.RemotePort = CLng(Text2.Text) + 1
' 和主機端連接
Winsock1.Connect
Winsock2.Connect
End Sub

' 按下『離線』按鈕
Private Sub Command2_Click()
Winsock1.Close
Winsock2.Close
End Sub

Private Sub Command3_Click()
' 宣告即將取出檔案名稱的變數
Dim Datas() As String
CommonDialog1.Filter = "所有檔案(*.*)|*.*"
CommonDialog1.InitDir = "C:\"
CommonDialog1.ShowOpen
' 判斷 FileName 屬性值是否空白
If Trim(CommonDialog1.FileName) = "" Then
Exit Sub
End If
' 設定 SendFileName變數的值
SendFileName = CommonDialog1.FileName
' 將 SendFileName變數的值 暫存在 Label3控制項的Tag屬性
Label3.Tag = "『" & SendFileName & "』"
' 取出不含路徑資訊的檔案名稱
Datas = Split(SendFileName, "\")
' 傳送即將傳送的檔案名稱
Winsock1.SendData "檔案名稱" & Datas(UBound(Datas, 1))
DoEvents
End Sub

Private Sub Form_Load()
' 初始化各種控制項的相關屬性
Label1.Caption = "主機位址:"
Label2.Caption = "連接埠編號:"
Label3.Caption = ""
Me.Caption = "EX1004 用戶端"
Command1.Caption = "連線"
Command2.Caption = "離線"
Command3.Caption = "傳送檔案"
Text1.Text = "127.1"
Text2.Text = "6000"
' 啟用 Timer1控制項監視Winsock1控制項的狀態
Timer1.Interval = 100
End Sub

Private Sub Timer1_Timer()
' 判斷Winsock控制項的狀態
Select Case Winsock1.State
Case sckClosed ' 常數值0
Label4.Caption = "尚未連線"
Case sckOpen ' 常數值1
Label4.Caption = "開啟"
Case sckListening ' 常數值2
Label4.Caption = "監聽中..."
Case sckConnectionPending ' 常數值3
Label4.Caption = "尚未連連線"
Case sckResolvingHost ' 常數值4
Label4.Caption = "主機解析中"
Case sckHostResolved ' 常數值5
Label4.Caption = "主機解析完畢"
Case sckConnecting ' 常數值6
Label4.Caption = "連線中..."
Case sckConnected ' 常數值7
Label4.Caption = "已經和主機端連線"
Case sckClosing ' 常數值8
Label4.Caption = "切斷連線中"
End Select
End Sub

Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long)
Dim sVar
Dim TotalBytes As Long ' 取得檔案的位元組數量
Dim Buffers() As Byte ' 緩衝區位元組陣列
Dim I As Long ' 迴圈變數
Dim Mods As Long ' 取得餘數
Dim Quotient As Long ' 取得商
Dim FileNo As Integer ' 儲存檔案通道編號
Dim BreakPoint As Long ' 取得傳輸中斷點的位元組數量
Winsock1.GetData sVar, vbString
Select Case Trim(sVar)
Case "資料接收完畢"
Label3.Caption = Label3.Tag & "檔案接收完畢"
' 表示主機端已經開啟二進位檔案的寫入模式
Case "準備就緒"
Label3.Caption = Label3.Tag & "檔案傳送中..."
TotalBytes = FileLen(SendFileName)
' 假設每次讀取 1024個位元組
' 取得檔案位元組數量和 1024的餘數
Mods = TotalBytes Mod 1024 ' 取餘數
Quotient = Fix(TotalBytes / 1024) ' 取商數
FileNo = FreeFile ' 取得可用的檔案通道
ReDim Buffers(1023) ' 重新宣告位元組陣列的大小
Open SendFileName For Binary Access Read As #FileNo
' 執行迴圈讀取檔案內容
For I = 1 To Quotient
Get #FileNo, , Buffers ' 從檔案讀取位元組資料
DoEvents
Winsock2.SendData Buffers ' 傳送檔案的位元組資料
Next
' 處理最後的『第n部分』
If Mods <> 0 Then
' 餘數的數值即為最後需要傳送的位元組數量
ReDim Buffers(Mods - 1)
Get #FileNo, , Buffers ' 從檔案讀取剩餘的位元組資料
Winsock2.SendData Buffers ' 傳送檔案的位元組資料
DoEvents
End If
Close #FileNo
' 告訴主機端檔案已經傳送完畢
Winsock1.SendData "傳送完畢"
DoEvents
Case Else
If Mid(sVar, 1, 4) = "斷點續傳" Then
' 取得斷點位元組數量
BreakPoint = CLng(Mid(sVar, 5))
TotalBytes = FileLen(SendFileName) - BreakPoint
' 假設每次讀取 1024個位元組
' 取得檔案位元組數量和 1024的餘數
Mods = TotalBytes Mod 1024 ' 取餘數
Quotient = Fix(TotalBytes / 1024) ' 取商數
FileNo = FreeFile ' 取得可用的檔案通道
Open SendFileName For Binary Access Read As #FileNo
ReDim Buffers(BreakPoint - 1) ' 重新宣告位元組陣列的大小
Get #FileNo, , Buffers ' 讀取但不處理
DoEvents
ReDim Buffers(1023) ' 重新宣告位元組陣列的大小
' 執行迴圈讀取檔案內容
For I = 1 To Quotient
Get #FileNo, , Buffers ' 從檔案讀取位元組資料
Winsock2.SendData Buffers ' 傳送檔案的位元組資料
DoEvents
Next
' 處理最後的『第n部分』
If Mods <> 0 Then
' 餘數的數值即為最後需要傳送的位元組數量
ReDim Buffers(Mods - 1)
Get #FileNo, , Buffers ' 從檔案讀取剩餘的位元組資料
Winsock2.SendData Buffers ' 傳送檔案的位元組資料
DoEvents
End If
Close #FileNo
' 告訴主機端檔案已經傳送完畢
Winsock1.SendData "傳送完畢"
DoEvents
End If
End Select
End Sub

编写的记事本

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;

namespace 文本文件夹
{
public partial class form1 : Form
{
string fileName = "Untitle";
public form1()
{
InitializeComponent();

}

private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog openFile = new OpenFileDialog();
openFile.Filter = "Text Documents(*.txt)|*.txt|All Files|*.*";
openFile.FilterIndex = 2;

if (openFile.ShowDialog() == DialogResult.OK)
{
fileName = openFile.FileName;

open();

}
}
protected void open()
{
try
{
textBox1.Clear();
textBox1.Text = File.ReadAllText(fileName );
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "错误警告!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

}
}

private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
textBox1.Clear();
}

private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saveFile = new SaveFileDialog();
saveFile.Filter = "(*.txt)|*.txt|(*.doc)|.doc";
saveFile.FilterIndex = 1;

if (saveFile.ShowDialog() == DialogResult.OK)
{
fileName = saveFile.FileName;
save();
}

}
protected void save()
{
try
{
File.WriteAllText(fileName, textBox1.Text );
}
catch (Exception ex)
{

MessageBox.Show(ex.Message, "错误警告!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);


}
}

private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saveFile = new SaveFileDialog();
saveFile.Filter = "(*.txt)|*.txt|(*.doc)|.doc";
saveFile.FilterIndex = 1;
if (saveFile.ShowDialog() == DialogResult.OK)
{
if (fileName == "Untitle")
{
saveAsToolStripMenuItem_Click(sender, e);
}
else
{
save();
}
}
}

private void 字体ToolStripMenuItem_Click(object sender, EventArgs e)
{
FontDialog font = new FontDialog();
if(font.ShowDialog ()==DialogResult .OK )
{
textBox1.Font = font.Font;
}
}

private void 颜色ToolStripMenuItem_Click(object sender, EventArgs e)
{
ColorDialog color = new ColorDialog();
if (color.ShowDialog() == DialogResult.OK)
{
textBox1.ForeColor = color.Color;

}
}

private void 说明ToolStripMenuItem_Click(object sender, EventArgs e)
{
AboutBox1 Abox = new AboutBox1();
Abox.ShowDialog();
}

private void timeofEditToolStripMenuItem_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text + DateTime.Now.ToString();

}

private void 全选ToolStripMenuItem_Click(object sender, EventArgs e)
{
textBox1.SelectAll();

}

private void 复制ToolStripMenuItem1_Click(object sender, EventArgs e)
{
try
{
textBox1.SelectAll();
System.Windows.Forms.Clipboard.SetText(this.textBox1.SelectedText);
}

catch (Exception ex)
{
MessageBox.Show(ex.Message, "粘贴错误警告", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private void 剪贴ToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
textBox1.SelectAll();
System.Windows.Forms.Clipboard.SetText(this.textBox1.SelectedText);
textBox1.Clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "粘贴错误警告", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}


private void tie_Click(object sender, EventArgs e)
{
try
{
System.Windows.Forms.IDataObject data = System.Windows.Forms.Clipboard.GetDataObject();
if (data.GetDataPresent(DataFormats.Text))
{
textBox1.SelectedText = data.GetData(DataFormats.Text).ToString();
}

}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "粘贴错误警告", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}









}


}

ADO.net基于SQL是实现模式

using System.Data;
using System.Data.SqlClient;
using System;

class test
{
private static void Main()
{
//建立数据源
SqlConnection con = new SqlConnection();
con.ConnectionString ="Data Source=PC-200809131136;Initial Catalog=Northwind;Integrated Security=True";
con.Open();

//链接数据库
SqlCommand sc = new SqlCommand();
sc.Connection = con;
sc.CommandType = CommandType.Text;

sc.CommandText = "select * from Customers where CustomerID='BLAUS' ";

SqlDataReader reader =sc.ExecuteReader ();

//输入结果
while (reader .Read ())
{
Console.WriteLine("\t{0},\t{1},\t{2}",reader[0],reader[1],reader[2]);
}
Console.ReadLine();

}
}

ADO.net实现数据库的连接

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace conect_sql
{
class Program
{
static void Main(string[] args)
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=sampledata;Integrated Security=True");
con.Open();

SqlCommand com = new SqlCommand("insert 用户名单(用户名,密码) values(@NewName,@NewID)", con);
com.Parameters.Add("@NewName",SqlDbType.NChar );

com.Parameters["@NewName"].Value = Console.ReadLine();

com.Parameters.Add("@NewID", SqlDbType.Int);
com.Parameters["@NewID"].Value = Console.ReadLine();
SqlDataReader re = com.ExecuteReader();


while (re.Read())
{
Console.WriteLine("\t{0}\t{1}", re[0], re[1]);
}
Console.Read();

}
}
}

無連線使用ADO.NET

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace sql运用
{
class Program
{
static void Main(string[] args)
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Northwind;Integrated Security=True");
con.Open();

DataSet dataset = new DataSet();

SqlDataAdapter adapter1 = new SqlDataAdapter("select * From Customers ",con);
adapter1.Fill(dataset, "customers"); //建立一个customers表。并把它放入dataset中
SqlDataAdapter adapter2 = new SqlDataAdapter("select * From Orders ", con);
adapter2.Fill(dataset, "orders");

foreach (DataRow row in dataset.Tables["customers"].Rows)
{
Console.WriteLine(row[0] + " " + row[1] + " " + row[2]);
}
Console.Read();
foreach (DataRow row in dataset.Tables["orders"].Rows)
{
Console.WriteLine(row[0] + " " + row[1] + " " + row[2]);
}

Console .Read();
Console.Read();
}
}
}

構建DataSet實例

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;


namespace datatable
{
class Program
{
static void Main(string[] args)
{
DataTable table1 = new DataTable("Student");
table1.Columns.Add("ID",typeof (int));
table1.Columns.Add("Name",typeof (String ));
table1.Columns.Add("Sex",typeof (string ));

table1.Columns[0].Unique = true;
table1.Columns[0].AutoIncrement = true;
table1.Columns[0].AutoIncrementSeed = 10;
table1.Columns[0].AutoIncrementStep = 10;

DataRow row1 = table1.NewRow();
row1[0] = 001;
row1[1] = "Jam";
row1["Sex"] = "Man";
table1.Rows.Add(row1 );
DataRow row2 = table1.NewRow();
row2[0] = 002;
row2[1] = "Luch";
row2["Sex"] = "Woman";
table1.Rows.Add(row2);

DataTable table2 = new DataTable("Address");
table2.Columns.Add("ID",typeof (int));
table2.Columns.Add("Address");
table2.Columns.Add("TelePhone",typeof (string ));

DataRow row3 = table2.NewRow();
row3["ID"] =1;
row3[1] = "BeJing";
row3[2] = 13000001234;
table2.Rows.Add(row3 );

ForeignKeyConstraint foreignkey = new ForeignKeyConstraint(table1 .Columns [0],table2.Columns [0]);
foreignkey.DeleteRule = Rule.Cascade;
foreignkey.UpdateRule = Rule.Cascade ;
table2.Constraints.Add(foreignkey);
// table1.PrimaryKey = new DataColumn[] { table1.Columns[0], table1.Columns[1] };


DataRow row4 = table2.NewRow();
row4["ID"] = 2;
row4[1] = "ShangHai";
row4[2] = 13888884567;
table2.Rows.Add(row4);

DataSet dataset = new DataSet();

dataset.Tables.Add(table1 );
dataset.Tables.Add(table2);


foreach (DataRow row in table1.Rows)
{
for (int i = 0; i < table1.Columns.Count; i++)
Console.Write(row [i]+" ");
Console.WriteLine();
}
Console.WriteLine();
foreach (DataRow row in table2.Rows)
{
for (int i = 0; i < table2.Columns.Count; i++)
Console.Write(row[i]+" ");
Console.WriteLine();
}


Console.WriteLine();
Console.WriteLine();

//table1.Rows[0][0] = 6;
//table1.Rows.RemoveAt(1);

foreach (DataRow row in table1.Rows)
{
for (int i = 0; i < table1.Columns.Count; i++)
Console.Write(row[i] + " ");
Console.WriteLine();
}
Console.WriteLine();
foreach (DataRow row in table2.Rows)
{
for (int i = 0; i < table2.Columns.Count; i++)
Console.Write(row[i] + " ");
Console.WriteLine();
}
Console.Read();

}
}
}