2014年5月30日 星期五

MSSQL 資料庫所有欄位名稱以及所有資料表名稱


搜尋資料庫所有欄位名稱,可以使用這兩種語法
select * from syscolumns
select * from sys.columns

取得資料庫中所有資料表的名稱,可以使用以下語法
SELECT * FROM INFORMATION_SCHEMA.TABLES

IdealProgrammer.com 超多程式語言範例的網站

Catalog of 1,300+ Hours of .NET Video Tutorials : IdealProgrammer.com
--
真多!! 有空要來好好進修了

Visual Studio 下載

Visual Studio 下載
---
Visual Studio 出版的速度真是快,1年1版 ..
這代表什麼 ?
....
....
....
新的技術和方法都有進步和突破
這腳步真的走得好快,大家跟上微軟腳步了嗎

超大免費架站空間2FREEHOSTING 20G空間 150G流量 無廣告 提供PHP 、MySQL

Free Web Hosting with cPanel, PHP5, SSH and MySQL. Host Free Website

---
超大免費架站空間2FREEHOSTING 20G空間 150G流量 無廣告 提供PHP 、MySQL

好康耶!!

2014年5月27日 星期二

how to create a ms access db and table using adodb in vb.net

參考1:how to create a ms access db and table using adodb in vb.net
參考引用2:How to create access database
--

\\\set a reference to COM adox ext 2.x for dll and security
Public Class Main
Public Shared Sub Main()
Dim catNewDB As New ADOX.Catalog
Dim fi As New IO.FileInfo("c:\db1.mdb")
If fi.Exists Then
If MessageBox.Show("Delete?", "Existing File db1.mdb", _
MessageBoxButtons.YesNo) = DialogResult.Yes Then
fi.Delete()
Else
Exit Sub
End If
End If
catNewDB.Create("Provider=Microsoft.Jet.OLEDB.4.0; " & "Data
Source=C:\db1.mdb")
'To make tables we use Adonet
Dim conn As New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLED B.4.0;" &
_
" Data Source=C:\db1.mdb;User Id=admin;Password=;")
Dim cmd As New OleDb.OleDbCommand("CREATE TABLE persons ( " & _
"AutoId int identity ," & _
"Id int NOT NULL," & _
"Name NVarchar(50)," & _
"BirthDate datetime," & _
"IdCountry int," & _
"CONSTRAINT [pk_AutoId] PRIMARY KEY (AutoId)) ", conn)
conn.Open()
Try
cmd.ExecuteNonQuery()
Catch ex As OleDb.OleDbException
MessageBox.Show(ex.Message, "OleDbException")
Exit Sub
Catch ex As Exception
MessageBox.Show(ex.Message, "GeneralException")
Exit Sub
End Try
cmd = New OleDb.OleDbCommand("CREATE TABLE countries ( " & _
"AutoId int identity ," & _
"Id int NOT NULL," & _
"Name NVarchar(50)," & _
"CONSTRAINT [pk_AutoId] PRIMARY KEY (AutoId)) ", conn)
Try
cmd.ExecuteNonQuery()
Catch ex As OleDb.OleDbException
MessageBox.Show(ex.Message, "OleDbException")
Exit Sub
Catch ex As Exception
MessageBox.Show(ex.Message, "GeneralException")
Exit Sub
End Try
conn.Close()
End Sub
End Class
/// 

2014年5月26日 星期一

健康小常識

請參考來源:健康小常識
--

孔雀魚-疾病與難病對策

參考引用來源:孔雀魚-疾病與難病對策
--
 孔雀魚-疾病與難病對策


撰文自一位朋友

疾 病 與 難 病 對 策

白點病
初期魚體出現數粒小白點,末期則全身佈滿白點,二次感染合併水黴病及細菌感染,至嚴重時,則藥石罔效。 投入適量甲基藍藥水,每10加侖水 4~8cc,無底砂配合過濾系統之容器,藥量宜減為二分之一至四分之一,或將患病的魚放在百分之一的食鹽水中,亦可治癒。(成蟲殺除難,但仔蟲殺除容易,故維持水中有效藥劑約7∼20天左右,即可完全撲滅)

黑點病 
病魚頭部可見長形的淺黃色孢囊,其孢囊成熟時,呈黑色,即搖尾幼蟲與後囊幼蟲,它們亦侵襲魚體眼睛、肌肉、血管、鰓、內臟器官,若於眼睛的水晶體部位發現不透明的斑塊,則有可能受到感染 此病不具傳染性,但是會傷害肌肉組織及使眼睛受到或失明,嚴重時可致死,目前並無藥可癒,僅可用消毒過的針,或鑷子將蟲挑除

水黴菌病 
受傷的表皮產生毛狀、絲狀菌絲,肉眼所見絲狀物即為已死的黴菌屍體,活的黴菌則寄生在皮膚及肌肉上。 投入適量甲基藍藥水,或將患病的魚放在百分之一的食鹽水、盤尼西林水溶液中,亦具效果。(受傷、搬運撈捕魚兒宜做預防措施) 爛 嘴 病 魚兒的嘴及頰部覆蓋白色附著物,鰭、鰓、口部最易感染。此病傳染力甚強,發病後數天,魚箱中的魚兒可能全滅。 可採用跟水黴菌病相同的治療法,或早一點塗抹多聚氰就有效。(若短時間內無法痊癒,每易造成抗藥性細菌,故使用藥劑時宜核對水量及用藥量,以正確治療)

爛爛鰭病尾
水質受到污染,或被其牠的魚兒咬傷,傷口受到感染,魚鰭一開始變白,惡化則會腐爛死亡。 投入適量甲基藍藥水、盤尼西林、綠F金或使用薄的食鹽水飼養。

鰓吸蟲寄生症
呼吸較急促,鰓蓋大開,鰓絲有腫脹與白化現象,不喜歡游動,有時具有使水箱魚兒全滅的傳染力。 利用福馬林溶劑,進行長期或短期藥浴,因成蟲撲滅容易,但蟲卵殺滅困難,會在三天後陸續孵出,可在水中保持萬用水、甲基藍藥水有效成份3~5天,殺滅幼蟲。

松果狀鱗腫 (立鱗病) 
魚體發腫,魚鱗豎起,狀似松果,致病原因不明。 可在罹病初期,每10公升的水加入0.1gr的氯黴素,或每10公升的水加入3萬單位的盤尼西林溶液。

口絲蟲感染症
皮膚出現整片雲狀物灰色黏液的感染現象,大量口絲蟲寄生時,體表會出現一塊一塊破皮的血斑,魚鰭不張開,並且磨擦植物或底部,不進食而體重下降,常使病魚慵懶斜躺昏睡。 可採用跟白點病相同的治療法或每2公升的水加入1毫升的福馬林,浸浴15分鐘,亦可每100公升的水中加入1公克的叮啶黃素作約2天的浸浴,將水溫提高至30度c可幫助去除口絲蟲。

氣泡病 
魚體表面或各魚鰭長出粒狀的氣泡會逐漸變大,如同水泡一般,得此病會使魚窒息或氣泡栓塞致死。發病原因是水中氧氣或氮氣過剩,初期僅需換水,則於短期內即可痊癒,嚴重時,可使用綠F金、硝酸糖棕等水溶液藥浴。

額頭穿孔症
在額頭及眼眶附近有一個或數個凹穴,伴有黴菌感染時,則會有白色絲狀物出現。 水質老舊的魚缸易罹患此病,故勤換水及清理魚缸可預防,臭頭藥粉、賀利沙民,同時進行藥浴口服及可生效。(早期治療容易,末期易引發死亡率)

鞭毛蟲病
食欲不佳,鰓部不動,鱗上出現泌血斑點,浮到水面。 每公升水加入15毫克的氯黴素及實施水質管理。

血行障礙症 
血液不足,造成背鰭與臀鰭供血不良,導致細胞壞死,呈鋸齒狀殘缺但不會持續蝕爛,用爛尾病治療法也不見療效者。應注意水質情況及寄生蟲的問題,於水中加入抗菌劑,同時強化營養,短期內可以復原。

條蟲寄生症 
腹部明顯腫大,壓之結實,有別於腹水或腹腫脹,內臟易受壓迫而失去功能,成魚易誤診為抱卵。口服腸內寄生蟲清除劑,早期發現,治療容易,蟲體過大時有暴腹之可能,若已侵入內臟器官則迴生乏術。

不孕症
卵巢的退行性變化、脂肪變性、卵巢囊腫、卵巢石化、腹水、泳鰾病變、體內寄生蟲感染、雄魚在維他命缺乏一段時間後,生殖力即永遠受損 魚類長期攝取脂肪過多的餌料,會發生脂肪變性,因此當魚進入繁殖期時應減少餵食投餌量,並於產卵之前絕食3∼5天,另外,使用煌綠、奎寧劑、叮啶黃、孔雀綠等,也會導致一時性的不孕

傳染性腹水病
此病有兩種症狀,即典型腹水病及潰瘍性腹水病,其疾病症狀眼球突出、眼睛衰退、肛門突出及發炎,鰓呈白色,嚴重爛鰭,並可看見表皮紅斑,腹腔可能積存膿液,使腹部腫脹,潰瘍性病症於潰瘍患處為紅色,被白色環圍著,存於發黑表皮下,鱗片脫落處,可見到膿腫 將氯黴素、鏈黴素、北里黴素等抗生素,以加入飼料方式治療,使肝臟增加負荷的飼料會助長此病,對於罹患此病的魚,應該立即撈除

錨蟲甲殼類寄生蟲
其頭部有一根錨狀物,會刺入魚體,體長約1.2公分,魚體外觀看來,如同長毛一般。 用鑷子將錨蟲逐一夾出,或置病魚於比重1.025的海水、食鹽水溶液之中,亦可在10公升的水裡加50mg的過錳酸鉀,也可使用底特松 (藥性劇烈的農藥)加以驅除。

魚虱甲殼類寄生蟲
呈圓盤形,直徑約5mm,會在水中游動,寄生魚體,吸取魚血,同時放出毒液,致使魚兒表皮發炎,變紅,魚變的好動,無法休息,魚鰭縮摺,磨擦缸中砂石、裝飾物,肉眼可見粉紅色中心的小紅點。 用鑷子將魚虱逐一夾出,或將病魚放入百分之一的食鹽水中,經過一、二天便可消除魚虱,亦可將100公升的水溶入1公克的高錳酸鈉,浸浴1小時。

線蟲
此頑疾由白色到棕色的線蟲所致,病魚變得呆滯、消瘦、停止進食,有時可看到線蟲懸掛於肛門外 對付線蟲是很困難的,可採用驅蟲劑,但對魚亦有毒害,最好是移開隔離或消滅病魚 水 蛭 細小的腔腸動物,約1公分,呈圓筒狀,口腔周圍有六、七根觸手,會吞食仔魚。 將魚移出魚箱,加高水溫至攝氏四十度以上,即可殺除水蛭。

 
對成魚不具威脅,但會吃魚卵和仔魚。 以高濃度食鹽水,浸漬魚箱,並攪拌刷洗底砂和岩石十分鐘,即可驅除蛭。

鉤頭蟲 
少數的鉤頭蟲可能對魚的影響並不大,但是較重的感染使病魚消瘦、肛門發炎、蟲卵附在消化管道內,阻塞消化管道 此病是無法受到控制,因尚未有藥物能影響在腸道內的寄生蟲或其幼蟲,其預防感染的措失,是停止餵食淡水蝦、水蝨、昆蟲幼蟲,並將罹患此病的魚除去

雙身蟲 
肉眼可見灰棕色的蟲狀生物,常見於鰓的邊緣,引發鰓部發炎、縮摺及流血,魚會頭朝上不停衝出水面 每1公升的水溶入15公克食鹽,做短時間浸浴,亦可每100公升的水溶入1公克的叮啶黃素或阿滌平,做長期藥浴、浸浴數天

變體病 
到目前為止,仍未得到結論,根據病情猜測可能原因:一為水中含有重金屬鹽類,刺激魚的神經和肌肉收縮所致;另一為缺乏某種營養物質(如鈣和維生素等)而產生畸形 可換水數次,改良水質並加強飼料管理,多投餵含鈣質多,營養豐富的餌料,可減少此病發生

凍傷 
溫度很低時,魚就會被凍傷,造成各魚鰭產生紅色血絲,影響魚類生活機能,嚴重時可引起死亡 放入保溫器材,並多投富脂肪餌料,以增加魚的抗寒能力

感冒
由於水溫的急遽變更,刺激神經末稍,引起概能混亂,行動失常,器官機能失調,甚至漂浮水面失去游動能力,嚴重時可使魚死亡 換水時,要注意兩個水體溫度的差異情況不可相差太大(魚苗不可超過2度C,魚種不可超過5度C

腫瘤
惡性腫瘤可分為五大類:軟骨、骨骼、肌肉、神經、心臟癌瘤,其皮膚腫瘤或上皮癌可發現生長於表皮及鱗片 良性腫瘤可因受外界刺激而形成,只需移走刺激物,通常會消失,惡性腫瘤則極少可治癒

萎癟症
病魚身體乾癟、頭大身小、體色發黑、背肌薄如刀刃、鰓絲蒼白,呈嚴重貧血現象,往往於邊緣遲鈍地游動 主要由於放養過密,食料不足,可掌握魚種適當放養密度和加強飼料管理,使魚有充足的餌料 結 核 病 魚缺乏食慾、逐漸消瘦、背脊彎曲或呈拱形、胃部凹陷、體色蒼白、眼球突出及脫落、鱗片缺損、鰓部畸形、表皮發炎,鰭部受傳染,內臟停止運作並長出小結癤,病魚動作遲緩,游泳不正常 只有少數的抗生素具有療效,如四環素

球蟲病
眼球深陷及顯著消瘦,病魚挺起頭部,可看見黃色液體自肛門排出,當壓下患魚胃部,此情況更為明顯 水塘收集的紅蟲及玻璃蟲,常導致魚患此病,發生腸發炎,此病頗具傳染性,不能用藥療治癒,可從保護魚著手,避免使用紅蟲及玻璃蟲餌料,撈除病魚,消毒魚缸

魚鯉發炎症
發病初期,魚停止進食,病情持續下去,則充滿氣泡或濃液的胞囊在腹腔後端形成,使魚體膨脹,頭部豎立,包囊變大時,泳鰾有發炎、增厚的徵狀,當病情再惡化,鰾壁崩壞,感染內臟器官 此病具高度傳染性,由病毒引起,施用抗生素僅可減緩病情惡化,最好還是殺除病魚

霓虹燈魚病 
魚體褪色消瘦、腹部乾癟、體側螢光帶斷落、肌肉變紅發亮,帶有乳白透明膜、行動呆滯及失去平衡、游泳不正常 尚未有已知的治療法,故當確定有魚罹患此病時,應迅速將其撈除,並消毒清理水族箱

2014年5月25日 星期日

vbnet save xml / read xml

參考:How to save a DataSet as an XML file
參考:How Can write a DataSet as XML through VB.Net & C#?
參考:Export Datatable to xml
參考 MSDN:DataTable.WriteXml 方法

-------------
vb net datatable to xml

#1
Dim dt As New DataTable
dt.Columns.Add(New DataColumn("Column1"))
dt.Columns.Add(New DataColumn("Column2"))
Dim r = dt.NewRow
r.Item(0) = "Value1"
r.Item(1) = "Value2"
dt.Rows.Add(r)
r = dt.NewRow
r.Item(0) = "Value3"
r.Item(1) = "Value4"
dt.Rows.Add(r)
Dim ds As New DataSet
ds.Tables.Add(dt)

Dim simpleresult As String = ds.GetXml


Dim result As String
Using ms As New IO.MemoryStream()
    ds.WriteXml(ms, System.Data.XmlWriteMode.WriteSchema)
    result = System.Text.Encoding.UTF8.GetString(ms.ToArray)
End Using


#2
Private Sub btnWriteXMLData_Click(ByVal sender As System.Object, _
                        ByVal e As System.EventArgs) Handles btnWriteXMLData.Click
        Dim dsSales As New DataSet()
        Dim cn As New SqlConnection _
                    ("data source=localhost;initial catalog=pubs;user id=sa")
        Dim daAuthors As New SqlDataAdapter("select * from sales ", cn)
        Dim daPublishers As New SqlDataAdapter("select * from stores ", cn)

        ' Load data from database
        daAuthors.Fill(dsSales, "Sales")
        daPublishers.Fill(dsSales, "Stores")

        ' Write XML to file
        dsSales.WriteXml("XMLFile.xml")

End Sub


#3

Dim SB As New StringBuilder
Dim SW As New IO.StringWriter(SB)
Items.WriteXml(SW, Data.XmlWriteMode.WriteSchema)



#4
Dim ds As DataSet

'  ... Fill the DataSet with data from your database ...

ds.WriteXml("XML/MyData.xml", XmlWriteMode.WriteSchema)

Dim ds As DataSet = new DataSet()
ds.ReadXml("XML/MyData.xml", XmlReadMode.ReadSchema)


#5
DS.Tables(0).DefaultView.Sort = "ID ASC"
Dim outputDataTable = DS.Tables(0).DefaultView.ToTable()
outputDataTable.WriteXml("c:\blah\user.xml")

2014年5月23日 星期五

稅額扣底比率的意義及退稅計算方式

參考部分引用來源:請教稅額扣底比率的意義及退稅計算方式?
--
 4600元為股利淨額
扣抵稅額比率33.5%,可扣抵稅額為=4600*33.5%=1541
股利總額為=4600+1541=6141元
個人綜合所得稅=6141*13%=798
可退稅金額=798-1541=743元

2014年5月20日 星期二

VB6 Resize Form & Controls For Screen Size

請參考來源
--
參考來源2:Resize controls to fit when a form resizes
 

vb6 自动调整窗体内控件的大小

參考引用來源:自动调整窗体内控件的大小?如果是,那何必使用控件:
--
 '*************************************************************************
'**模 块 名:ModAutoSize
'**说    明:自动调整窗体控件大小及位置
'**创 建 人:嗷嗷叫的老马
'**             http://www.m5home.com/
'**日    期:2003年12月17日
'**备    注: 摘于网络
'**版    本:V1.0
'*************************************************************************
''   在Form_Load里面调用:
''               ControlAutoSize Me,0
''   在Form_Resize里面调用:
''               ControlAutoSize Me,1
''**********************************
'


Option Explicit
 
Private Type cP
  Wp As Single
  Hp As Single
  Tp As Single
  Lp As Single
End Type
Dim Ap() As cP
 
Private Sub Ai(ByRef mForm As Form)
    On Error Resume Next
    Dim I As Integer
    For I = 0 To mForm.Controls.Count - 1
          With Ap(I)
                .Wp = mForm.Controls(I).Width / mForm.Width
                .Hp = mForm.Controls(I).Height / mForm.Height
                .Lp = mForm.Controls(I).Left / mForm.Width
                .Tp = mForm.Controls(I).top / mForm.Height
          End With
    Next I
End Sub
 
Public Function ControlAutoSize(ByRef mForm As Form, ByVal OptIndex As Long)
    Select Case OptIndex
        Case 0
            mForm.Height = mForm.ScaleHeight
            ReDim Ap(0 To mForm.Controls.Count - 1)
            Call Ai(mForm)
        Case Else
            Dim I As Integer
             
            On Error Resume Next
            With mForm
                For I = 0 To .Controls.Count - 1
                    .Controls(I).Move Ap(I).Lp * .ScaleWidth, _
                                     Ap(I).Tp * .ScaleHeight, _
                                     Ap(I).Wp * .ScaleWidth, _
                                     Ap(I).Hp * .ScaleHeight
                Next I
            End With
    End Select
End Function

2014年5月18日 星期日

MS SQL連接遠端伺服器


MS SQL連接遠端伺服器
如何連接遠端伺服器, 大家也許都會, 順利的話當然OK, 但偶爾遇上錯誤訊息時, 可能還是抓不到頭緒, 剛好最近在連接遠端伺服器時發生一些錯誤訊息, 找到問題原因後, 在此作個記錄!
連接遠端伺服器所使用的 SQL字串如下, 大家應該是大同小異
的使用方式, 請參考微軟MSDN的說明, 很詳細.

--1. =====建立連接伺服器, 將伺服器加入 sys.servers =====
EXEC sp_addlinkedserver
    @server = 'ABC', --被訪問的伺服器别名, 可取任何名字
    @srvproduct = '' ,
    @provider = 'MSDASQL',
    @provstr = 'DRIVER={SQL Server};SERVER=172.16.3.11;UID=user;PWD=1234;Database=eb3'
GO

-- 2. === 建立連接遠端伺服器登入映射
EXEC sp_addlinkedsrvlogin
'ABC',
'false',
NULL,
--遠端伺服器登入帳號
'user',
--遠端伺服器登入密碼
'1234'

GO

-- 3. ======執行 Select =====
SELECT  *
FROM  tblABC
LEFT JOIN tblDEF

-- 4. ==== 移除連接
sp_dropserver 'ABC','droplogins'   --移除連接

GO

2014年5月16日 星期五

Open file with external exe file inside VB form


Public Class Form1
    Declare Auto Function SetParent Lib "user32.dll" (ByVal hWndChild As IntPtr, ByVal hWndNewParent As IntPtr) As Integer
    Declare Auto Function SendMessage Lib "user32.dll" (ByVal hWnd As IntPtr, ByVal Msg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As Integer
    Private Const WM_SYSCOMMAND As Integer = 274
    Private Const SC_MAXIMIZE As Integer = 61488
    Dim proc As Process
    Dim AppPath As String
    Dim strPath As String
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        AppPath = "C:\Users\User\Documents\Visual Studio 2010\Projects\Z26.exe"
        strPath = ""C:\Users\User\Documents\Visual Studio 2010\Projects\3d_tictac.bin"
        proc = Process.Start(AppPath)
        proc.WaitForInputIdle()

        SetParent(proc.MainWindowHandle, Panel1.Handle)
        SendMessage(proc.MainWindowHandle, WM_SYSCOMMAND, SC_MAXIMIZE, 0)
    End Sub
End Class

內崁exe資源檔要如何開啟使用

參考1:
Private Sub Form1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Click
Dim tobjStream As IO.Stream = Me.GetType.Assembly.GetManifestResourceStream("resourcesample2.License.txt")
Dim tobjStreamReader As New IO.StreamReader(tobjStream, System.Text.Encoding.Default)
Dim tstrLicense As String = tobjStreamReader.ReadToEnd
'如果是图象就可以使用dim tobjBMP as new bmp(tobjstrem)的方法直接得到资源内容
MessageBox.Show(tstrLicense)'显示刚才读得的结果
End Sub

參考2
  string apName = "ClaimLicense.Manifest"; // WindowsApplication6 corresponds to Default Namespace in your project settings.
System.IO.Stream strm = null;
strm = this.GetType().Assembly.GetManifestResourceStream(apName);
byte[] buf = new byte[strm.Length];
strm.Read(buf, 0, buf.Length);
apName = "AAA.EXE";
FileStream fs = new FileStream(apName,FileMode.Create, FileAccess.Write);
fs.Write(buf, 0, buf.Length);
fs.Close();
strm.Close();

2014年5月15日 星期四

過濾集數 1-3,8 寫法

以前就遇到租書軟體轉檔集數標示的問題!
----
特殊集數範圍或是多集輸入法:
1.  2-5
2.  33
3.  3-11,12
4.  2-5,6-9
----
這次又遇到此寫法,想了好久;最終還是破解此問題!
 Private Sub Command1_Click()
For i = 0 To 10
   Select Case i
     Case 2 To 5, 7
       Print i
   End Select
Next i
End Sub
-------------
將所有集數倒出來,再利用程式來過濾
當然這樣會有一個問題,就是當集數全展開;筆數會非常龐大
但沒辦法,這種鳥寫法 ; 就得用這種過濾來處理

筆電螢幕變色,另類用法

因筆電有點歷史了且 OS Windows XP , 且大部分工作用的均轉移到WIN7 上
筆電螢幕要修也不知道是LCD 還是顯示卡問題,一動就要好多千
因工作又須要開這台會變色的筆電,實在一片紅..受不了!
突然想到改用遠端來用就可以了!
當然較接近直覺的遠端,還是要用Windows  mstsc!


將遠端開啟後!
透過另外一台連線,哈! 還是能將就一下使用的!
管它變色到黑的也ok!

2014年5月14日 星期三

MSSQL --- MSDN 刪除主索引鍵

請參考MSDN:刪除主索引鍵
--


USE AdventureWorks2012;
GO
-- Return the name of primary key.
SELECT name
FROM sys.key_constraints
WHERE type = 'PK' AND OBJECT_NAME(parent_object_id) = N'TransactionHistoryArchive';
GO
-- Delete the primary key constraint.
ALTER TABLE Production.TransactionHistoryArchive
DROP CONSTRAINT PK_TransactionHistoryArchive_TransactionID;
GO

參考引用來源:SQL SERVER – How to Drop Primary Key Contraint
--
SQL SERVER – How to Drop Primary Key Contraint
One area that always, unfailingly pulls my interest is SQL Server Errors and their solution. I enjoy the challenging task of passing through the maze of error to find a way out with a perfect solution. However, when I received the following error from one of my regular readers, I was a little stumped at first! After some online probing, I figured out that it was actually syntax from MySql and not SQL Server. The reader encountered error when he ran the following query.

ALTER TABLE Table1
DROP PRIMARY KEY
GO

Msg 156, Level 15, State 1, Line 3
Incorrect syntax near the keyword ‘PRIMARY’.

As mentioned earlier, this syntax is for MySql, not SQL Server. If you want to drop primary key constraint in SQL Server, run the following query.

ALTER TABLE Table1
DROP CONSTRAINT PK_Table1_Col1
GO

Let us now pursue the complete example. First, we will create a table that has primary key. Next, we will drop the primary key successfully using the correct syntax of SQL Server.

CREATE TABLE Table1(
Col1 INT NOT NULL,
Col2 VARCHAR(100)
CONSTRAINT PK_Table1_Col1 PRIMARY KEY CLUSTERED (
Col1 ASC)
)
GO

/* For SQL Server/Oracle/MS ACCESS */
ALTER TABLE Table1
DROP CONSTRAINT PK_Table1_Col1
GO

/* For MySql */
ALTER TABLE Table1
DROP PRIMARY KEY
GO

I hope this example lucidly explains how to drop primary key. This, no doubt, is a very simple and basic explanation, but when I chanced upon the error message it aroused curiosity in me.  As you all know by now I love sharing new issues and ideas with my readers. So I have included this interesting error in my blog.

Let me have your feedback on this post and also, do feel free to share with me your ideas as well!

 

2014年5月8日 星期四

簡易POS系統 - 金湧 GR POS




簡易POS系統 - 金湧 GR POS
採用 Excel 當資料庫管理*限採用office 2003*
交易檔限 100 筆內,均免費無限期使用!
當超過100筆時,將 trans.xls 內的 M , D 表內清除即可繼續使用!*M:頭檔, D:明細檔*
1.商品檔 product.xls
2.交易檔 trans.xls
----------------------
注意:當執行 POS 時,不可開啟 excel 檔!! 必須都關閉!
數量--輸入:1 後,按 enter
數量--輸入:2 後,按 enter
刷商品條碼*支援用CCD刷入*
當未輸入數量,自動定義數量=1
----------------------
操作:
1.管理商品檔
2.處理交易檔
當超過到達99筆,系統不允許再交易!
此時可將 trans.xls ---複製到 trans-1030508.xls後
再將trans.xls內的 M,D 工作表內的資料清除
注意:標題*欄位*必須保留! 否則將無法運作!

免費下載使用,請加入FB社團:池龍工作室 後,即可在檔案區下載!!

2014年5月6日 星期二

Read Excel Sheet Data into DataTable

參考引用來源:Read Excel Sheet Data into DataTable - CodeProject
--
 Solution 1:

public static DataTable exceldata(string filePath)
        {    
            DataTable dtexcel = new DataTable();
               bool hasHeaders = false;
                string HDR = hasHeaders ? "Yes" : "No";
                string strConn;
                if (filePath.Substring(filePath.LastIndexOf('.')).ToLower() == ".xlsx")
                    strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;HDR=" + HDR + ";IMEX=0\"";
                else
                    strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=\"Excel 8.0;HDR=" + HDR + ";IMEX=0\"";
                OleDbConnection conn = new OleDbConnection(strConn);
                conn.Open();
                DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
                //Looping Total Sheet of Xl File
                /*foreach (DataRow schemaRow in schemaTable.Rows)
                {
                }*/
                //Looping a first Sheet of Xl File
                DataRow schemaRow = schemaTable.Rows[0];
                string sheet = schemaRow["TABLE_NAME"].ToString();
                if (!sheet.EndsWith("_"))
                {
                    string query = "SELECT  * FROM [" + sheet3 + "]";
                    OleDbDataAdapter daexcel = new OleDbDataAdapter(query, conn);
                    dtexcel.Locale = CultureInfo.CurrentCulture;
                    daexcel.Fill(dtexcel);
                }
           
            conn.Close();
            return dtexcel;

        }

vb.net 設置輸出保留n位小數


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim strNumFormat As String
        Dim intSumDec As Integer = 1
        Dim dblAmt As Decimal = 101.87
        strNumFormat = "{0:#,##0." & New String("0", intSumDec) & "}"
        'String.Format(strNumFormat, dblAmt)
        Label1.Text = String.Format(strNumFormat, dblAmt)
    End Sub

VB.NET中使用FTP下載檔案的兩種方法


.net沒有專門處理FTP的類,我們可以通過調用系統自帶的FTP.EXE 或者是調用win32 API中的wininet.dll來完成基本操作。希望以下的代碼能為大家抛磚引玉。

方法一: 使用Ftp.exe ,通過process類來調用它。

Imports System.Diagnostics

...

Public Sub GetFileByCallFtp()

'定義ProcessStartInfo,Process的啟動資訊。

Dim psi As New ProcessStartInfo

'ftp.exe的路徑最好放到設定檔裡。

psi.FileName = "C:\WINNT\system32\ftp.exe"

psi.RedirectStandardInput = False

psi.RedirectStandardOutput = True

'該值指示不使用作業系統Shell程式啟動進程。

psi.UseShellExecute = False

'命令集檔案名.注意,路徑中不能有空格.

Dim fileName As String = "C\ftp.txt"

'-s:FileName表示,從檔中讀取控制命令

psi.Arguments = "-s:" + fileName

Dim proc As Process

proc = Process.Start(psi)

'等待進程完成任務

proc.WaitForExit()

'在主控台輸出結果

Console.WriteLine(proc.StandardOutput)

Console.ReadLine()

End Sub

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

ftp.txt 裡的內容

方法二,使用win32 api —— wininet.dll

首先是,api聲明:

因為此測試程式,是VB.NET ConsoleApplication所以,api聲明寫在Module裡,

方法是靜態的。所以沒加Shared關鍵字, 這一點請大家注意。

_
Public Function InternetOpen(ByVal sAgent As String, ByVal LAccessType As Integer, ByVal sProxyName As String, _
ByVal SProxyBypass As String, ByVal lFlags As Integer) As Integer
End Function

_
Public Function InternetConnect(ByVal hInternetSession As Integer, ByVal sServerName As String, _
ByVal nServerPort As Integer, ByVal sUsername As String, _
ByVal sPassword As String, ByVal lService As Integer, _
ByVal lFlags As Integer, ByVal lCoNtext As Integer) As Integer
End Function

_
Public Function FtpGetFile(ByVal hFtpSession As Integer, ByVal lpszRemoteFile As String, _
ByVal lpszNewFile As String, ByVal fFailIfExists As Boolean, _
ByVal dwFlagsAndAttributes As Integer, ByVal dwFlags As Integer, _
ByVal dwCoNtext As Integer) As Boolean
End Function

_
Public Function InternetCloseHandle(ByVal hInet As Integer) As Integer
End Function

調用:

Public Sub GetFileByCallWininetDLL()
Try
Dim intinet As Integer = InternetOpen(Nothing, 0, Nothing, Nothing, 0)
If intinet > 0 Then

'參數:intinet的session值,ftp位址,埠,使用者名,密碼,lService, lFlags,lCoNtext

Dim intinetconn As Integer = InternetConnect(intinet, "192.168.110.152", 0, "tokiwa", "tokiwa", 1, 0, 0)

If intinetconn > 0 Then

'下載某個檔到指定檔

Dim ret As Boolean = FtpGetFile(intinetconn, "pagerror.gif", "C:\itest.gif", 0, 0, 1, 0)

If ret Then
Console.WriteLine("ok!")
Console.ReadLine()
End If
InternetCloseHandle(intinetconn)
InternetCloseHandle(intinet)
Else
Console.WriteLine("can't connect!")
Console.ReadLine()
End If

Else
Console.WriteLine("ftp wrong!")
Console.ReadLine()
End If
Catch ex As Exception
Console.WriteLine(ex.Message)
Console.ReadLine()
End Try

End Sub

vbnet 全形半形互相轉換


PublicFunctionToSBC()FunctionToSBC(ByValinputAsString)AsString'轉全形
DimcAsChar()=input.ToCharArray
DimiAsInteger=0
WhileiIfc(i)=ChrW(32)Then
c(i)=ChrW(12288)
ElseIfAscW(c(i))<127then p="">c(i)=ChrW((AscW(c(i))+65248))
EndIf
System.Math.Min(System.Threading.Interlocked.Increment(i),i-1)
EndWhile
ReturnNewString(c)
EndFunction


PublicFunctionToDBC()FunctionToDBC(ByValinputAsString)AsString'轉半形

DimcAsChar()=input.ToCharArray
DimiAsInteger=0
WhileiIfAscW(c(i))=12288Then
c(i)=ChrW(32)
ElseIfAscW(c(i))>65280AndAlsoAscW(c(i))<65375then p="">c(i)=ChrW(AscW(c(i))-65248)
EndIf
System.Math.Min(System.Threading.Interlocked.Increment(i),i-1)
EndWhile
ReturnNewString(c)
EndFunction

vbnet 實現的一個簡單的P2P示例


這是用VB.net實現的一個簡單的P2P示例.利用了UDP打洞技術.分伺服器端跟用戶端.伺服器端負責登陸記錄使用者的IP和埠及轉發打洞消息.(相關技術在CSDN搜一下.有很多的.).原理到處都有,這裡就沒有貼出來.這裡貼出了VB.net的代碼.供初學者交流.也歡迎高手點評...

  伺服器端在啟動成功後.輸入help可以查看到伺服器相關命令.

  用戶端在登陸成功後.輸入help可以查看用戶端相關命令.(登陸時使用者名隨便.)

  以下是伺服器端:

Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports System.Threading
Imports System.Collections

Module myUDPServer

#Region "全域變數"

Dim ServerSocket As New Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)
Dim ipep As IPEndPoint = New IPEndPoint(IPAddress.Any, 11000)

Dim htUserList As New Hashtable '用來保存線上使用者和使用者的"IP和埠"

Dim userName(0) As String
Dim userIPEP(0) As IPEndPoint
Dim userTime(0) As Integer

Dim timerDelegate As New TimerCallback(AddressOf onLineTimeOut)

#End Region

#Region "參數"

'以下是用戶端到伺服器端的消息開頭
Const LOGININ As String = "10" '請求登陸的消息|||消息形式:10+自己的使用者名
Const LOGINOUT As String = "11" '請求登出的消息|||消息形式:11+自己的使用者名
Const GETULIST As String = "12" '請求獲得線上使用者清單|||消息形式:12
Const P2PCONN As String = "13" '請求P2P連接的消息|||消息形式:13+自己的使用者名+|+對方的使用者名
Const HOLDLINE As String = "14" '保持連接.|||消息開式:14+自己的使用者名

'以下是伺服器到用戶端的消息開頭
Const HVUSER As String = "20" '使用者名已存在
Const GETUSER As String = "21" '線上使用者清單|||消息格式:21+使用者名+EP
Const MAKHOLD As String = "22" '打洞命令|||消息格式:22+IP
Const LOGINOK As String = "23" '登陸成功
Const SERVCLS As String = "24" '伺服器關閉
Const MSGEND As String = "25" '消息結束

'以下是伺服器端的命名
Const EXITPRO As String = "EXIT" '退出命令
Const SHOWULIST As String = "SHOWUSER" '顯示線上使用者
Const HELP As String = "HELP" '顯示説明

#End Region

#Region "方法"

'主函數,程式入口
Sub Main()

'獲得伺服器的IP位址
Dim addressList As System.Net.IPAddress() = Dns.GetHostByName(Dns.GetHostName()).AddressList
Dim ServerIP As IPAddress = addressList(0)

ServerSocket.Bind(ipep)
Console.WriteLine("伺服器正在啟動....")
Console.WriteLine("伺服器IP:" & ServerIP.ToString & " 正在監聽" & ipep.Port.ToString & "埠")
Dim listenTH As New Thread(AddressOf listen)
listenTH.Start() '啟用監聽的執行緒
Console.WriteLine("伺服器啟動成功.....")

Dim timer As New Timer(timerDelegate, Nothing, 0, 5000)

Dim SVInput As String
While True
Console.Write("Server>")
SVInput = Console.ReadLine().ToUpper
Select Case SVInput
Case EXITPRO
listenTH.Abort()
ServerSocket.Close()
Exit Sub
Case SHOWULIST
showUser()
Case HELP
Console.Write("*********************************" & Chr(10) & Chr(13) & "exit:輸出當前程式" & Chr(10) & Chr(13) & "showuser:顯示當前線上使用者例表" & Chr(10) & Chr(13) & "help:顯示説明" & Chr(10) & Chr(13) & "*********************************" & Chr(10) & Chr(13))
Case Else
Console.WriteLine("*********************************" & Chr(10) & Chr(13) & "笨瓜,你輸入的不是有效的命令." & Chr(10) & Chr(13) & "*********************************")
End Select
End While


End Sub

'列印線上使用者
Sub showUser()
Dim hava As Boolean = False
If userName.Length <> 0 Then
Dim i As Integer
For i = 1 To userName.Length - 1
If userName(i) <> "" Then
hava = True
Exit For
End If
Next
If hava = False Then
Console.WriteLine("*********************************" & Chr(10) & Chr(13) & "當前沒有使用者線上" & Chr(10) & Chr(13) & "*********************************")
Exit Sub
End If
Console.WriteLine("*********************************")
For i = 1 To userName.Length - 1
If userName(i) <> "" Then
Console.WriteLine("使用者名:" & userName(i) & " 位址:" & userIPEP(i).ToString)
End If
Next
Console.WriteLine("*********************************")
Else
Console.WriteLine("*********************************" & Chr(10) & Chr(13) & "當前沒有使用者線上" & Chr(10) & Chr(13) & "*********************************")
End If
End Sub

'伺服器監聽函數
Sub listen()

While True

Try
Dim recv As Integer = 0
Dim data As [Byte]() = New Byte(1024) {}
Dim sender As New IPEndPoint(IPAddress.Any, 0)
Dim tempRemoteEP As EndPoint = CType(sender, EndPoint)
recv = ServerSocket.ReceiveFrom(data, tempRemoteEP)

'Console.WriteLine(Encoding.Unicode.GetString(data))

Dim msgHead As String = Encoding.Unicode.GetString(data, 0, 4)
Select Case msgHead
Case LOGININ
Dim LoginThing As String = userLogin(data, tempRemoteEP, recv)
If LoginThing = HVUSER Then
sendMsg(HVUSER, tempRemoteEP)
ElseIf LoginThing = LOGINOK Then
sendMsg(LOGINOK, tempRemoteEP)

End If

Case LOGINOUT
userloginout(data, recv)

Case GETULIST
Dim userinfo As String = getUserList()
sendMsg(userinfo, tempRemoteEP)

Case P2PCONN
questP2PConn(data, recv)

Case HOLDLINE
holdOnLine(data, recv)
End Select

Catch e As Exception
'Console.WriteLine(e.ToString)
End Try
End While

End Sub

'轉發P2P連接請求
Private Sub questP2PConn(ByVal data() As Byte, ByVal recv As Integer)

Dim recvStr As String = Encoding.Unicode.GetString(data, 4, recv - 4)
Dim split() As String = recvStr.Split("|")

Dim fromEP As IPEndPoint
Dim toEP As IPEndPoint
Dim i As Integer
For i = 1 To userName.Length - 1
If userName(i) = split(0) Then


fromEP = userIPEP(i)
End If
If userName(i) = split(1) Then
toEP = userIPEP(i)
End If
Next
Dim holdbytes() As Byte = Encoding.Unicode.GetBytes(MAKHOLD & fromEP.ToString)
ServerSocket.SendTo(holdbytes, toEP)
End Sub

'函數.返回所有線上使用者.其格式:使用者名+|+使用者IPEP+|
Private Function getUserList() As String
Dim userInfo As String = GETUSER
Dim i As Integer
For i = 1 To userName.Length - 1
If userName(i) <> "" Then
userInfo += userName(i) & "|" & userIPEP(i).ToString & "|"
End If
Next
Return userInfo
End Function

'使用者登陸,直接返回登陸是否成功的值
Private Function userLogin(ByVal data As Byte(), ByVal userEP As IPEndPoint, ByVal recvCount As Integer) As String

Dim Uname As String = Encoding.Unicode.GetString(data, 4, recvCount - 4)

Dim Uinfobytes() As Byte

Dim i As Integer
Dim j As Integer

For i = 1 To userName.Length - 1
If Uname = userName(i) Then
Return HVUSER
End If
Next

For i = 1 To userName.Length - 1
If userName(i) = "" Then
userName(i) = Uname
userIPEP(i) = userEP
userTime(i) = 60
Console.Write(Chr(10) & Chr(13) & "*********************************" & Chr(10) & Chr(13) & Uname.Trim & "上線了." & "使用者位址:" & userEP.ToString & Chr(10) & Chr(13) & "*********************************" & Chr(10) & Chr(13))
Console.Write("Server>")

Uinfobytes = Encoding.Unicode.GetBytes(LOGININ & userName(i) & "|" & userIPEP(i).ToString)

For j = 1 To userName.Length - 1
If userName(j) <> "" And userName(j) <> Uname Then
ServerSocket.SendTo(Uinfobytes, userIPEP(j))
End If
Next
Return LOGINOK
End If
Next

Dim userCount As Integer = userName.Length

ReDim Preserve userName(userCount)
ReDim Preserve userIPEP(userCount)
ReDim Preserve userTime(userCount)

userName(userName.Length - 1) = Uname
userIPEP(userIPEP.Length - 1) = userEP
userTime(userTime.Length - 1) = 60

Console.Write(Chr(10) & Chr(13) & "*********************************" & Chr(10) & Chr(13) & Uname.Trim & "上線了." & "使用者位址:" & userEP.ToString & Chr(10) & Chr(13) & "*********************************" & Chr(10) & Chr(13))
Console.Write("Server>")

Uinfobytes = Encoding.Unicode.GetBytes(LOGININ & userName(userName.Length - 1) & "|" & userIPEP(userName.Length - 1).ToString)

For j = 1 To userName.Length - 1
If userName(j) <> "" And userName(j) <> Uname Then
ServerSocket.SendTo(Uinfobytes, userIPEP(j))
End If
Next
Return LOGINOK

End Function

'使用者登出
Private Sub userloginout(ByVal data As Byte(), ByVal recvCount As Integer)

Dim i As Integer
Dim Uname As String = Encoding.Unicode.GetString(data, 4, recvCount - 4)

For i = 1 To userName.Length - 1

If Uname = userName(i) Then

Dim loginOutMsg As String = LOGINOUT & userName(i)


userName(i) = ""
userIPEP(i) = Nothing
userTime(i) = 0

Dim j As Integer
For j = 1 To userName.Length - 1
If userName(j) <> "" Then

sendMsg(loginOutMsg, userIPEP(j))

End If
Next

Console.WriteLine(Chr(10) & Chr(13) & "*********************************")
Console.WriteLine("使用者" & Uname & "下線了.")
Console.WriteLine("*********************************")
Console.Write("Server>")

Exit For

End If

Next

End Sub

'保持使用者線上的過程
Private Sub holdOnLine(ByVal data As Byte(), ByVal recvCount As Integer)

Dim Uname As String = Encoding.Unicode.GetString(data, 4, recvCount - 4)

Dim i As Integer

For i = 1 To userName.Length - 1

If Uname = userName(i) Then

userTime(i) = 60
Exit For

End If

Next

End Sub

'使用者超時退出
Private Sub onLineTimeOut(ByVal state As [Object])

Dim i As Integer

For i = 1 To userName.Length - 1

If userTime(i) > 0 Then

userTime(i) -= 5

If userTime(i) <= 0 Then

Dim loginoutmsg As String = LOGINOUT & userName(i)

Console.WriteLine(Chr(10) & Chr(13) & "*********************************")
Console.WriteLine("使用者" & userName(i) & "下線了.")
Console.WriteLine("*********************************")
Console.Write("Server>")

userName(i) = ""
userIPEP(i) = Nothing

Dim ULoginOutbytes() As Byte = Encoding.Unicode.GetBytes(loginoutmsg)

Dim j As Integer
For j = 1 To userName.Length - 1

If userName(j) <> "" Then
If userIPEP(j) Is Nothing Then
Else
ServerSocket.SendTo(ULoginOutbytes, userIPEP(j))
End If
End If

Next

End If

End If

Next

End Sub

'發送消息的函數
Sub sendMsg(ByVal msg As String, ByVal remoteEP As IPEndPoint)
Dim sendBytes As [Byte]() = Encoding.Unicode.GetBytes(msg)
Try

ServerSocket.SendTo(sendBytes, remoteEP)

Catch e As Exception
Console.WriteLine(e.ToString())
End Try
End Sub

#End Region

End Module

以下是用戶端:

Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports System.Threading


Module Module1

#Region "參數"

'以下是用戶端到伺服器端的消息開頭
Const LOGININ As String = "10" '請求登陸的消息|||消息形式:10+自己的使用者名
Const LOGINOUT As String = "11" '請求登出的消息|||消息形式:11+自己的使用者名
Const GETULIST As String = "12" '請求獲得線上使用者清單|||消息形式:12+自己的使用者名


Const P2PCONN As String = "13" '請求P2P連接的消息|||消息形式:13+自己的使用者名+對方的使用者名
Const HOLDLINE As String = "14" '保持連接.|||消息開式:14+自己的使用者名


'以下是伺服器到用戶端的消息開頭
Const HVUSER As String = "20" '使用者名已存在
Const GETUSER As String = "21" '線上使用者清單|||消息格式:21+使用者名+EP
Const MAKHOLD As String = "22" '打洞命令|||消息格式:22+IP
Const LOGINOK As String = "23" '登陸成功
Const SERVCLS As String = "24" '伺服器關閉
Const MSGEND As String = "25" '消息結束


'以下是用戶端到用戶端的消息開頭
Const HOLDOK As String = "30" '打洞成功
Const CHATMSG As String = "31" '聊天消息
Const CHTMSGEND As String = "32" '聊天消息發送成功


'以下是用戶端的命名
Const EXITPRO As String = "EXIT" '退出命令
Const SHOWULIST As String = "SHOWUSER" '顯示線上使用者
Const HELP As String = "HELP" '顯示説明
Const SEND As String = "SEND" '發送消息


#End Region


#Region "全域全量"


Delegate Sub myMethodDelegate(ByRef myInData As Byte()) '登陸時用的事件


'Dim MaxTry As Integer = 5
Dim msgSendEnd As Boolean = False '消息是否發送成功,若發送成功,則會返回結束消息
Dim ThListen As New Thread(AddressOf listen) '監聽的執行緒
Dim ClientSocket As New Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp) '用戶端套節字的定義


Dim username As String '當前使用者名
Dim ServerEP As IPEndPoint '伺服器的IPEP
Dim holdBytes As [Byte]() = Encoding.Unicode.GetBytes(HOLDLINE & username) '和伺服器保持連接連接時用到的byte陣列


Dim OLUserName() As String
Dim OLUserEP() As IPEndPoint
Dim getUrecCount As Integer
Dim testHold As Boolean = False
Dim testChat As Boolean = False


Private receiveDone As ManualResetEvent '在登陸時用來阻塞執行緒,等待收到資料
Private sendDone As ManualResetEvent '用來陰塞發送消息的執行緒.等待收到回送的確認訊息
Private getUDone As ManualResetEvent '用來阻塞請求好友名單的執行緒,等待接收好友名單
Private holdDone As ManualResetEvent '用來阻塞打洞時的執行緒
Private chatDone As ManualResetEvent '用來阻塞發送聊天消息時的執行緒


Dim timerDelegate As New TimerCallback(AddressOf holdonline) '為保持線上狀態弄得


#End Region


#Region "方法"


'主函數,程式入口
Sub Main()
Dim InputIP As String
Dim InputOK As Boolean = False



'判斷輸入的IP,並且保存伺服器的IPEP
While InputOK <> True
Console.Write("請輸入伺服器IP:")
InputIP = Console.ReadLine()
Try
ServerEP = New IPEndPoint(IPAddress.Parse(InputIP), 11000)
InputOK = True
Catch
Console.WriteLine("你輸入的伺服器IP不正確,請重新輸入.")
InputOK = False
End Try
End While


Dim bool As Boolean = False


'判斷使用者是否登陸成功
While bool <> True


Dim LoginOK As Boolean = Login()
If LoginOK = True Then
bool = True
Else
Console.Write("是否重試:輸入Y重試,輸入任意值退出程式:")
Dim tempYN As String = Console.ReadLine.ToUpper
If tempYN = "Y" Then
bool = False
Else
Exit Sub
End If
End If


End While


Console.WriteLine("使用者名:" & username)
holdBytes = Encoding.Unicode.GetBytes(HOLDLINE & username)
'登陸成功後.用一個timer,每隔50秒向伺服器發送消息,保持線上狀態跟在主機註冊的埠
Dim timer As New Timer(timerDelegate, Nothing, 10000, 50000)


'請求線上名單
Console.WriteLine("正在獲取線上名單,請稍後....")
Dim getUbool As Boolean = False
While getUbool <> True
getUbool = getU()
If getUbool = False Then
Console.Write("是否重試:輸入Y重試,輸入任意值退出程式:")
Dim tempYN As String = Console.ReadLine.ToUpper
If tempYN = "Y" Then
bool = False
Else
Exit Sub
End If
End If
End While


ThListen.Start()


'用來處理用戶端的一些命令
Dim SVInput As String
While True
Console.Write("Client>")
SVInput = Console.ReadLine().ToUpper
Select Case SVInput
Case EXITPRO
exitApp()
ThListen.Abort()
ClientSocket.Close()
Exit Sub
Case SHOWULIST
Console.WriteLine("*********************************")
showUserList()
Console.WriteLine("*********************************")
Case HELP
Console.Write("*********************************" & Chr(10) & Chr(13) & "exit:輸出當前程式" & Chr(10) & Chr(13) & "showuser:顯示當前線上使用者例表" & Chr(10) & Chr(13) & "send:發送消息.格式:send 使用者名 消息" & Chr(10) & Chr(13) & "help:顯示説明" & Chr(10) & Chr(13) & "*********************************" & Chr(10) & Chr(13))
Case Else
If SVInput.Substring(0, 4) = "SEND" Then
Dim split() As String = SVInput.Split(" ")
If split.Length = 3 Then
sendChatMsg(split(1), split(2))
Else
Console.WriteLine("*********************************" & Chr(10) & Chr(13) & "你輸入的命令格式不正確.send命令格式為:send 使用者名 你的消息" & Chr(10) & Chr(13) & "*********************************")
End If
Else
Console.WriteLine("*********************************" & Chr(10) & Chr(13) & "笨瓜,你輸入的不是有效的命令." & Chr(10) & Chr(13) & "*********************************")
End If
End Select
End While


End Sub


'登陸函數
Private Function Login() As Boolean


receiveDone = New ManualResetEvent(False)
Dim userBytes As [Byte]()


Dim userOK As Boolean = False


Console.Write("請輸入你的使用者名:")


'判斷使用者名是否符合格式
While (userOK <> True)
username = Console.ReadLine.ToUpper
userBytes = Encoding.Unicode.GetBytes(LOGININ & username)


If userBytes.Length > 24 Or userBytes.Length < 10 Then
Console.WriteLine("使用者名不得小於6個位元組,且不得大於20個位元組.")
Console.Write("請重新輸入你的使用者名:")
Else
userOK = True
End If
End While


'向伺服器發送客戶消息
ClientSocket.SendTo(userBytes, ServerEP)


Dim data As [Byte]() = New Byte(1024) {}


Dim comStr As String = Encoding.Unicode.GetString(data, 0, 4)

'異面的接收伺服器回送的消息
Dim DGrecv As New myMethodDelegate(AddressOf recvLogin)
DGrecv.BeginInvoke(data, Nothing, Nothing)

'等待伺服器回送消息的時長為10秒,否則為伺服器超時
receiveDone.WaitOne(30000, True)

Dim recvStr As String = Encoding.Unicode.GetString(data, 0, 4)

If recvStr = comStr Then
Console.WriteLine("伺服器超時.登陸失敗!!")
Return False
End If

If Encoding.Unicode.GetString(data, 0, 4) = LOGINOK Then
Console.WriteLine("登陸成功!!")
Return True
ElseIf Encoding.Unicode.GetString(data, 0, 4) = HVUSER Then
Console.WriteLine("使用者名重複.登陸失敗!!")
Return False
Else
Console.WriteLine("伺服器未知錯誤,登陸失敗!!")
Return False
End If

End Function

'登出函數
Private Sub exitApp()

Dim loginOutStr As String = LOGINOUT & username
Dim sendBytes As [Byte]() = Encoding.Unicode.GetBytes(loginOutStr)
ClientSocket.SendTo(sendBytes, ServerEP)

End Sub

'請求好友清單的函數
Private Function getU() As Boolean

getUDone = New ManualResetEvent(False)
Dim getUbytes As Byte() = Encoding.Unicode.GetBytes(GETULIST)
ClientSocket.SendTo(getUbytes, ServerEP)

Dim data As [Byte]() = New Byte(4056) {}
Dim comStr As String = Encoding.Unicode.GetString(data, 0, 4)

Dim GUrecv As New myMethodDelegate(AddressOf recvGetU)
GUrecv.BeginInvoke(data, Nothing, Nothing)

getUDone.WaitOne(30000, True)

Dim recvStr As String = Encoding.Unicode.GetString(data, 0, 4)

If recvStr = comStr Then
Console.WriteLine("伺服器超時.或取好友名單失敗!!")
Return False
End If

If Encoding.Unicode.GetString(data, 0, 4) = GETUSER Then
getUserList(data, getUrecCount)
Console.WriteLine("獲取線上名單成功!!")
showUserList()
Return True
Else
Console.WriteLine("伺服器未知錯誤,獲取線上名單失敗!!")
Return False
End If

End Function

'登陸時用來非同步接收伺服器發送的消息
Sub recvLogin(ByRef inData As Byte())

ClientSocket.Receive(inData)
receiveDone.Set()

End Sub

'請求好友名單時用來非同步接收伺服器發送的消息
Sub recvGetU(ByRef inData As Byte())

getUrecCount = ClientSocket.Receive(inData)
getUDone.Set()

End Sub

'處理收到的線上使用者資訊
Private Sub getUserList(ByVal userInfobytes() As Byte, ByVal reccount As Integer)

Dim ustr As String = Encoding.Unicode.GetString(userInfobytes, 4, reccount - 4)

Dim splitStr() As String = Nothing

splitStr = Ustr.Split("|")

Dim IPEPSplit() As String = Nothing

Dim i As Integer = 0

Dim k As Integer
For k = 0 To splitStr.Length - 2 Step 2
ReDim Preserve OLUserName(i)
ReDim Preserve OLUserEP(i)

OLUserName(i) = splitStr(k)
IPEPSplit = splitStr(k + 1).Split(":")
OLUserEP(i) = New IPEndPoint(IPAddress.Parse(IPEPSplit(0)), IPEPSplit(1))

IPEPSplit = Nothing
i += 1
Next

End Sub

'顯示線上使用者
Private Sub showUserList()
Dim i As Integer
For i = 0 To OLUserName.Length - 1
If OLUserName(i) <> "" Then
Console.WriteLine("使用者名:" & OLUserName(i) & " 使用者IP:" & OLUserEP(i).ToString)
End If
Next
End Sub

'客戶程式監聽的函數
Sub listen()

While True

Try
Dim recv As Integer = 0 '收到的位元組數
Dim data As [Byte]() = New Byte(1024) {} '緩衝區大小
Dim sender As New IPEndPoint(IPAddress.Any, 0)
Dim tempRemoteEP As EndPoint = CType(sender, EndPoint)
recv = ClientSocket.ReceiveFrom(data, tempRemoteEP)

Dim msgHead As String = Encoding.Unicode.GetString(data, 0, 4) '獲得消息頭的內容
Select Case msgHead
Case MSGEND
msgSendEnd = True
sendDone.Set()
Case LOGININ
addOnLine(data, recv)
Case LOGINOUT
removeOnLine(data, recv)
Case MSGEND
msgSendEnd = True
sendDone.Set()
Case MAKHOLD
Console.WriteLine(Chr(10) & Chr(13) & "收到打洞消息.")
makeHold(data, recv)
Console.Write("Client>")
Case CHATMSG
showChatMsg(data, recv)
Case HOLDOK
testHold = True
holdDone.Set()
Case CHTMSGEND
testChat = True
chatDone.Set()
End Select

Catch
End Try

End While
End Sub

'發送聊天消息
Private Sub sendChatMsg(ByVal remoteUser As String, ByVal chatMsgStr As String)

If remoteUser = username Then
Console.WriteLine("豬頭,你想幹什麼!!!")
Exit Sub
End If

Dim i As Integer

Dim remoteUEP As IPEndPoint
For i = 0 To OLUserName.Length - 1
If remoteUser = OLUserName(i) Then
remoteUEP = OLUserEP(i)
Exit For
End If
If i = OLUserName.Length - 1 Then
Console.WriteLine("找不到你想發送的使用者.")
Exit Sub
End If
Next

Dim msgbytes() As Byte = Encoding.Unicode.GetBytes(CHATMSG & username & "|" & chatMsgStr)
Dim holdbytes() As Byte = Encoding.Unicode.GetBytes(P2PCONN & username & "|" & remoteUser)

chatDone = New ManualResetEvent(False)
ClientSocket.SendTo(msgbytes, remoteUEP)
chatDone.WaitOne(10000, True)
If testChat = True Then
testChat = False
Exit Sub
End If

testHold = False
While testHold <> True
Console.WriteLine("打洞ing.....")
holdDone = New ManualResetEvent(False)
ClientSocket.SendTo(holdbytes, remoteUEP)
ClientSocket.SendTo(holdbytes, ServerEP)
holdDone.WaitOne(10000, True)
If testHold = True Then
Exit While
Else
Console.WriteLine("打洞超時,發送消息失敗.")
Console.Write("是否重試,按Y重試,按任意值結束髮送:")
Dim YorN As String = Console.ReadLine().ToUpper
If YorN = "Y" Then
testHold = False
Else
Exit Sub
End If
End If
End While

While testChat <> True
Console.WriteLine("打洞成功,正在準備發送.....")
chatDone = New ManualResetEvent(False)
ClientSocket.SendTo(msgbytes, remoteUEP)
chatDone.WaitOne(10000, True)
If testChat = True Then
Console.WriteLine("消息發送成功!!")
Exit While
Else
Console.WriteLine("發送超時,發送消息失敗.")
Console.Write("是否重試,按Y重試,按任意值結束髮送:")
Dim YorN As String = Console.ReadLine().ToUpper
If YorN = "Y" Then
testChat = False
Else
Exit Sub
End If
End If
End While
testHold = False
testChat = False
End Sub

'處理聊天消息
Private Sub showChatMsg(ByVal indata() As Byte, ByVal recvcount As Integer)
Dim msgStr As String = Encoding.Unicode.GetString(indata, 4, recvcount - 4)
Dim splitStr() As String = msgStr.Split("|")
Dim fromUname As String = splitStr(0)
Dim msg As String = splitStr(1)
Console.WriteLine(Chr(10) & Chr(13) & "收到來自" & fromUname & "的消息:" & msg)
Console.Write("Client>")
Dim i As Integer
For i = 0 To OLUserName.Length - 1
If OLUserName(i) = fromUname Then
Exit For
End If
Next
Dim tempbytes() As Byte = Encoding.Unicode.GetBytes(CHTMSGEND)
ClientSocket.SendTo(tempbytes, OLUserEP(i))
End Sub

'處理打洞函數
Private Sub makeHold(ByVal indata() As Byte, ByVal recvcount As Integer)
Dim makholdstr As String = Encoding.Unicode.GetString(indata, 4, recvcount)
Dim ipepstr() As String = makholdstr.Split(":")
Dim holdEP As IPEndPoint = New IPEndPoint(IPAddress.Parse(ipepstr(0)), ipepstr(1))

Dim holdbytes() As Byte = Encoding.Unicode.GetBytes(HOLDOK & username)
ClientSocket.SendTo(holdbytes, holdEP)
Console.WriteLine("回送打洞消息.")
End Sub

'處理使用者上線的函數
Private Sub addOnLine(ByVal inData() As Byte, ByVal recvCount As Integer)
Dim inStr As String = Encoding.Unicode.GetString(inData, 4, recvCount - 4)
Dim userinfo() As String = inStr.Split("|")
Dim strUserEP() As String = userinfo(1).Split(":")

Dim i As Integer
For i = 0 To OLUserName.Length - 1
If OLUserName(i) = "" Then
OLUserName(i) = userinfo(0)
OLUserEP(i) = New IPEndPoint(IPAddress.Parse(strUserEP(0)), strUserEP(1))
Console.WriteLine(Chr(10) & Chr(13) & "使用者" & OLUserName(i) & "上線了. 使用者位址:" & OLUserEP(i).ToString)
Console.Write("Client>")
Exit Sub
End If
Next

ReDim Preserve OLUserName(i + 1)
ReDim Preserve OLUserEP(i + 1)

OLUserName(i + 1) = userinfo(0)
OLUserEP(i + 1) = New IPEndPoint(IPAddress.Parse(strUserEP(0)), strUserEP(1))

Console.WriteLine(Chr(10) & Chr(13) & "使用者" & OLUserName(i + 1) & "上線了. 使用者位址:" & OLUserEP(i + 1).ToString)
Console.Write("Client>")

End Sub

'處理使用者下線的函數
Private Sub removeOnLine(ByVal inData() As Byte, ByVal recvCount As Integer)
Dim offUname As String = Encoding.Unicode.GetString(inData, 4, recvCount - 4)

Dim i As Integer
For i = 0 To OLUserName.Length - 1
If OLUserName(i) = offUname Then
OLUserName(i) = ""
OLUserEP(i) = Nothing
Console.WriteLine(Chr(10) & Chr(13) & "使用者" & offUname & "下線了.")
Console.Write("Client>")
Exit Sub
End If
Next
End Sub

'發送消息的函數
Public Function sendmsg(ByVal msg As String, ByVal sendToIPEP As IPEndPoint) As String

Dim sendBytes As [Byte]() = Encoding.Unicode.GetBytes(msg)

'判斷發送的位元組數是否超過了伺服器緩衝區大小
If sendBytes.Length > 1024 Then
Return "W輸入的字數太多"
End If

'判斷消息是否發送成功
While msgSendEnd = False

sendDone = New ManualResetEvent(False)

Try

ClientSocket.SendTo(sendBytes, sendToIPEP)

sendDone.WaitOne(10000, True) '阻塞執行緒10秒

If msgSendEnd = False Then
Console.WriteLine("消息發送超時")
Else
Exit While
End If

Catch e As Exception

Console.WriteLine("發送消息失敗" & e.ToString)
Exit Function

End Try

Console.Write("是否重試?按Y重試,按任意鍵退出:")
Dim userInput As String = Console.ReadLine.ToUpper

If userInput = "Y" Then
Else
msgSendEnd = False
Exit Function
End If

End While

msgSendEnd = False

End Function

'用保持線上狀態的函數
Private Sub holdonline(ByVal state As [Object])
ClientSocket.SendTo(holdBytes, ServerEP)
End Sub

#End Region

End Module

vbnet 獲取資料庫表結構和表資料

參考引用來源:獲取資料庫表結構和表資料的小程式(VB.NET版本)
--
 採集資料庫中指定表的資料和指定表的結構。代碼如下:

'GetTableStuct 獲取表的結構
Private Function GetDataTableSchame(ByVal strTableName As String) As DataSet

On Error GoTo theError

InitialConnectionString()
Dim dba As New SqlDataProvider.DataBaseAccess(con_SPEC_DB)


Dim dsTableSchame As New DataSet
Dim strSql As String
'Get Table Schame
strSql = "SELECT syscolumns.name as columnname,systypes.name as columntype,syscolumns.isnullable," & _
"syscolumns.length FROM syscolumns, systypes " & _
"WHERE(syscolumns.xusertype = systypes.xusertype) " & _
" AND syscolumns.id = object_id('" & strTableName & "') "

dsTableSchame = dba.FillDataset(strSql, CommandType.Text)

Return dsTableSchame
Exit Function
theError:
MessageBox.Show("獲取表" & strTableName & "的結構失敗!")
Return Nothing
Exit Function

End Function


'GetTableData 獲取表的資料
Private Function GetTableData(ByVal strTableName As String) As DataSet

On Error GoTo theError

InitialConnectionString()
Dim dba As New SqlDataProvider.DataBaseAccess(con_SPEC_DB)


Dim dsTableData As New DataSet
Dim strSql As String
'Get Table Schame
strSql = "select * from " & strTableName

dsTableData = dba.FillDataset(strSql, CommandType.Text)

Return dsTableData
Exit Function
theError:
MessageBox.Show("獲取表" & strTableName & "的資料失敗!")
Return Nothing
Exit Function

End Function

'將表的結構寫入到檔中


Private Function WriteTableStruct(ByVal strTableName As String, ByVal fs As FileStream, ByVal sw As StreamWriter, ByVal ds As DataSet) As Boolean

If ds Is Nothing Then
Else
sw.WriteLine(ds.Tables(0).Columns(0).ColumnName & "," & ds.Tables(0).Columns(1).ColumnName & "," & _
ds.Tables(0).Columns(2).ColumnName & "," & ds.Tables(0).Columns(3).ColumnName)
Dim i As Int16
For i = 0 To ds.Tables(0).Rows.Count - 1
sw.WriteLine(ds.Tables(0).Rows(i)(0).ToString() & "," & ds.Tables(0).Rows(i)(1).ToString() & "," & _
ds.Tables(0).Rows(i)(2).ToString() & "," & ds.Tables(0).Rows(i)(3).ToString())
Next
sw.WriteLine("--------------------------------------")
sw.WriteLine()
End If

End Function

'將表的資料寫入到檔中
Private Function WriteTableData(ByVal strTableName As String, ByVal fs As FileStream, ByVal sw As StreamWriter, ByVal ds As DataSet) As Boolean

If ds Is Nothing Then
Else
Dim j As Int16
For j = 0 To ds.Tables(0).Columns.Count - 1
If j = ds.Tables(0).Columns.Count - 1 Then
sw.Write(ds.Tables(0).Columns(j).ColumnName)
sw.WriteLine()
Else
sw.Write(ds.Tables(0).Columns(j).ColumnName & ",")
End If
Next

Dim i As Int16
For i = 0 To ds.Tables(0).Rows.Count - 1
For j = 0 To ds.Tables(0).Columns.Count - 1
If j = ds.Tables(0).Columns.Count - 1 Then
sw.Write(ds.Tables(0).Rows(i)(j).ToString())
sw.WriteLine()
Else
sw.Write(ds.Tables(0).Rows(i)(j).ToString() & ",")
End If
Next
Next
sw.WriteLine("--------------------------------------")
sw.WriteLine()
End If

End Function




‘調用上面程式的Demo代碼如下:




’獲取表結構的代碼


Private Sub btnGetTableStruct_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGetTableStruct.Click

On Error GoTo theError

Dim strPath As String
strPath = System.Windows.Forms.Application.StartupPath

'Create New File
Dim strOutputFileName As String
strOutputFileName = "TableStruct-" + DateTime.Now.ToString("yyyyMMddhhmmss")
strOutputFileName = strPath & "\" & strOutputFileName
Dim fs As System.IO.FileStream = New System.IO.FileStream(strOutputFileName & ".csv", IO.FileMode.CreateNew, IO.FileAccess.Write)
Dim sw As System.IO.StreamWriter = New System.IO.StreamWriter(fs)

Dim ds As New DataSet
ds = Nothing
Dim strTableName As String
strTableName = "Test"
sw.WriteLine(strTableName & "表結構如下:")
ds = GetDataTableSchame(strTableName)
WriteTableStruct(strTableName, fs, sw, ds)
ds.Clear()




sw.Close()
fs.Close()

MessageBox.Show("生成表結構檔成功!")
Exit Sub

theError:
MessageBox.Show("生成表結構檔失敗!")
sw.Close()
fs.Close()
Exit Sub


End Sub





'獲取表資料的代碼

Private Sub btnGetTableData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click

On Error GoTo theError

Dim strPath As String
strPath = System.Windows.Forms.Application.StartupPath

'Create New File
Dim strOutputFileName As String
strOutputFileName = "TableData-" + DateTime.Now.ToString("yyyyMMddhhmmss")
strOutputFileName = strPath & "\" & strOutputFileName
Dim fs As System.IO.FileStream = New System.IO.FileStream(strOutputFileName & ".csv", IO.FileMode.CreateNew, IO.FileAccess.Write)
Dim sw As System.IO.StreamWriter = New System.IO.StreamWriter(fs)

Dim ds As New DataSet
ds = Nothing
Dim strTableName As String
strTableName = "Test"
sw.WriteLine(strTableName & "表資料如下:")
ds = GetTableData(strTableName)
WriteTableData(strTableName, fs, sw, ds)
ds.Clear()

sw.Close()
fs.Close()

MessageBox.Show("生成表資料檔案成功!")
Exit Sub

theError:
MessageBox.Show("生成表資料檔案失敗!")
sw.Close()
fs.Close()
Exit Sub

End Sub

C# Epson熱敏印表機列印 Pos機用

參考引用來源
--
 public class EpsopnPrinter
{
//列印文字(埠號 字元)
public static string PrintString(int Port, string val)
{
System.IO.Ports.SerialPort sp = new System.IO.Ports.SerialPort();
sp.PortName = "COM" + Port.ToString();
try
{
sp.Open();
}
catch
{
return "埠被佔用";
}
List data = new List();
string[] lines = val.Split('\n');
for (int i = 0; i < lines.Length; i++)
{
byte[] content = System.Text.Encoding.Default.GetBytes(lines[i].Replace("\r", ""));
byte[] wapbt ={ 0x0a };
data.AddRange(content);
data.AddRange(wapbt);
}
byte[] cutbt={0x1d,0x56,0x42,0x11};
data.AddRange(cutbt);
byte[] databt = data.ToArray();
sp.Write(databt, 0, databt.Length);
sp.Close();
return null;
}

//測試印表機是否接在這個埠
public static bool PrintTest(int Port)
{
System.IO.Ports.SerialPort sp = new System.IO.Ports.SerialPort();
sp.PortName = "COM" + Port.ToString();
sp.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(sp_DataReceived);
try
{
sp.Open();
}
catch
{
return false;
}
Recived = false;
byte[] testbt={0x1D,0x49,0x01};
sp.Write(testbt, 0, testbt.Length);
System.Threading.Thread.Sleep(100);
sp.Close();
return Recived;
}

static bool Recived = false;
static void sp_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
Recived = true;
}
}

C# 程式設計 - 免費電子書

請參考原站:C# 程式設計 - 免費電子書:C# 程式設計
--
還不錯唷! 要學 c# 的可看看

VBnet 跑馬燈建立

參考引用:VB.net 跑馬燈建立
--
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Timer1.Enabled = True
Timer1.Interval = 150
Timer1.Start()
End Sub

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Try
If intPos <= Integer.Parse(message.Length) * -10 Then
   intPos = StatusStrip1.Width
End If
   intPos -= 5
   StatusStrip1.Refresh()
   StatusStrip1.CreateGraphics.DrawString(" " & message, StatusStrip1.Font, Brushes.Red, intPos, 6)
Catch ex As Exception
End Try
End Sub

---
底下改寫:



改寫:
Public Class Form1

    Dim intPos As Integer
    Dim message As String = "這是跑碼燈"

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Timer1.Interval = 150
        Timer1.Enabled = True
        Timer1.Start()
    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        If intPos <= Integer.Parse(message.Length) * -10 Then
            intPos = Txt1.Width          
        End If
        intPos -= 5
        Txt1.Refresh()
        Txt1.CreateGraphics.DrawString(" " & message, Txt1.Font, Brushes.Red, intPos, 6)  
    End Sub
End Class

vbnet Ndde (Dynamic Data Exchange) 動態資料交換 (excel )

官網:NDde (下載)
--
請參考:NDde 的簡易教學 (Client 部份)
請參考:NDde 的簡易教學 (Client 完整範例)
--
官網下載有範例檔,可參考!  

vbnet DataGridView1.CurrentCellAddress紀錄


'----DataGridView在設計點選內容時,可用DataGridView1.CurrentCellAddress.X(或Y)來找到所選中的列或欄
Private Sub DataGridView1_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles DataGridView1.MouseClick

  TextBox1.Text = DataGridView1.Item(0, DataGridView1.CurrentCellAddress.Y).Value
  TextBox2.Text = DataGridView1.Item(1, DataGridView1.CurrentCellAddress.Y).Value
  DataGridView1.SendToBack()

End Sub

VBnet 將資料填進EXCEL,WORD中


WORD:
Imports Microsoft.Office.Interop

Dim wod_app As New Word.Application    '這邊要注意建立app時要用new
Dim wod_doc As Word.Document
Dim wod_tab As Word.Table

  wod_doc = wod_app.Documents.Open("C:\NEWS管理.doc", , True)
  wod_tab = wod_doc.Tables.Item(1)

  contSqlconn(1)    '個人的連接資料庫函式
  cmd.CommandText = "select * from hn_news where (流水號='" + 流水號.Text + "')"
  dr = cmd.ExecuteReader
  dr.Read()

    wod_tab.Cell(1, 1).Range.Text = dr("狀態旗標").ToString
    wod_tab.Cell(1, 2).Range.Text = dr("流水號").ToString
    wod_tab.Cell(1, 4).Range.Text = dr("標題").ToString
    wod_tab.Cell(2, 2).Range.Text = dr("內容").ToString
    wod_tab.Cell(4, 2).Range.Text = dr("回覆").ToString

  dr.Close()
  contSqlconn(-1)

  wod_app.Visible = True '預覽列印
  'wod_app.PrintOut(Copies:=1) '直接列印
  'wod_app.Quit(SaveChanges:=False) '關閉開啟的WORD

  wod_tab = Nothing

  wod_doc.Close()
  wod_doc = Nothing

  wod_app.Quit()
  wod_app = Nothing
  
  GC.Collect()


EXCEL:
Imports Microsoft.Office.Interop

  Dim exl_ap As New Excel.Application
  Dim exl_wkb As Excel.Workbook
  Dim exl_wks As Excel.Worksheet
  Dim i As Integer = 1

  exl_wkb = exl_app.Workbooks.Open("C:\驗購表.xls", , True) '這個TRUE是Readonly
  exl_wks = exl_wkb.Worksheets("sheet1") '或者 exl_wks = exl_wkb.Worksheets(1)

  contSqlconn(1)
  cmd.CommandText = "sql語法省略" + _
  dr = cmd.ExecuteReader
    With exl_wks
      .Name = "藥品驗購表"
      .Range("A" & i).Value = "藥品中文名"
      .Range("B" & i).Value = "藥品索引"
      .Range("C" & i).Value = "藥品簡稱"
      .Range("D" & i).Value = "驗收日期"
      .Range("E" & i).Value = "藥廠名稱"
      .Range("F" & i).Value = "藥廠代號"
      .Range("A1:F1").Interior.ColorIndex = 6
      .Cells().ColumnWidth = 7

    End With
  While dr.Read
    i += 1
    With exl_wks
      .Range("A" & i).Value = dr(0).ToString
      .Range("B" & i).Value = dr(1).ToString
      .Range("C" & i).Value = dr(2).ToString
      .Range("D" & i).Value = dr(3).ToString
      .Range("E" & i).Value = dr(4).ToString
      .Range("F" & i).Value = dr(5).ToString
    End With
  End While

  exl_app.SaveWorkspace()
  exl_app.Visible = True

  exl_wks = Nothing

  exl_wkb.Close()
  exl_wkb = Nothing

  exl_app.Quit()
  exl_app = Nothing

  contSqlconn(-1)
  GC.Collect()

VBNET 中寫入文件的同時,並覆蓋原文件內容


Dim strFilePath As String = "F:\\1.txt"
Dim sw As System.IO.StreamWriter = New System.IO.StreamWriter(strFilePath, False)
Dim temp As String = "1111111111111111111111111"
sw.WriteLine(temp)
sw.Flush()
sw.Close()
sw = Nothing

2014年5月5日 星期一

TcpClient.Connected 屬性

參考引用來源:取得值,指出 TcpClient 的基礎 Socket 是否已連接至遠端主機。
--


中斷 Tcp 連線

public System.Net.Sockets.TcpClient tcpClient;

            if (this.tcpClient != null)
            {
                this.tcpClient.Client.Shutdown(System.Net.Sockets.SocketShutdown.Both);
                this.tcpClient.Client.Close();
                this.tcpClient.Close();
                this.tcpClient = null;
            }      

//===========================================================
取得client端的ip

 System.Net.IPEndPoint p  = (System.Net.IPEndPoint)tcpClient.Client.RemoteEndPoint;
 string IP = p.Address.ToString();

vbnet 同時併存 update , insert

參考引用來源:VB.NET Excel匯入Oracle DB前判斷資料是否已經存在,如果已經存在就在時間欄位加上現在時間;如果不存在就直接insert新的一筆資料進去。
--
第一次看到這種的用法! 真是驚訝~~~

 Protected Sub Button3_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button3.Click
Dim strUrl As String
strUrl = FileUpload1.PostedFile.FileName.ToString()

If (strUrl = "") Then
Label1.Text = "請選擇上傳檔案路徑!"
Else
'--->連接Excel
Dim connString As String
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strUrl & ";Extended Properties=""Excel 8.0;HDR=YES;IMEX=1"""

Dim ExcelConn As New System.Data.OleDb.OleDbConnection(connString)
ExcelConn.Open()

Dim da As New System.Data.OleDb.OleDbDataAdapter("select * from [UNIT_PRICE$]", ExcelConn)

Dim dt As New DataTable
da.Fill(dt)

'--->連接Oracle DB
Dim connString1 As String = WebConfigurationManager.ConnectionStrings("xxxxx").ConnectionString
Dim conn As New OracleConnection(connString1)
conn.Open()

Try
Dim cmdUpd As New OracleCommand()
cmdUpd.Connection = conn
cmdUpd.CommandText = "UPDATE WEB_SHIP_UNIT_PRICE SET DISABLE_DATE = SYSDATE WHERE partno = :partno AND DISABLE_DATE IS NULL"
cmdUpd.Prepare()
cmdUpd.Parameters.Add(New OracleParameter("partno", OracleDbType.Varchar2, 30))

Dim cmd As New OracleCommand()
cmd.Connection = conn
cmd.CommandText = "insert into WEB_SHIP_UNIT_PRICE(doc_type, org_id, partno, so_price, crrency, creation_date, created_by, last_update_date, last_updated_by) values " & _
" (:doc_type, :org_id, :partno, :so_price, :crrency, :creation_date, :created_by, :last_update_date, :last_updated_by)"
cmd.Prepare()


cmd.Parameters.Add(New OracleParameter("doc_type", 0))
cmd.Parameters.Add(New OracleParameter("org_id", 1))
cmd.Parameters.Add(New OracleParameter("partno", OracleDbType.Varchar2, 30))
cmd.Parameters.Add(New OracleParameter("so_price", 3))
cmd.Parameters.Add(New OracleParameter("crrency", OracleDbType.Varchar2, 10))
cmd.Parameters.Add(New OracleParameter("creation_date", CType(System.DateTime.Now.ToShortDateString, Date)))
cmd.Parameters.Add(New OracleParameter("created_by", Session("UserID")))
cmd.Parameters.Add(New OracleParameter("last_update_date", CType(System.DateTime.Now.ToShortDateString, Date)))
cmd.Parameters.Add(New OracleParameter("last_updated_by", Session("UserID")))

Dim i As Integer
For i = 0 To (dt.Rows.Count - 1)
cmd.Parameters(0).Value = dt.Rows(i)("doc_type")
cmd.Parameters(1).Value = dt.Rows(i)("org_id")
cmd.Parameters(2).Value = dt.Rows(i)("partno")
cmd.Parameters(3).Value = dt.Rows(i)("so_price")
cmd.Parameters(4).Value = dt.Rows(i)("crrency")
cmdUpd.Parameters(0).Value = dt.Rows(i)("partno")
cmdUpd.ExecuteNonQuery()
cmd.ExecuteNonQuery()
Next

Catch ex As Exception
Response.Write(ex.Message.ToString())
End Try
Label1.Text = "上傳成功!"

End If
End Sub

vbnet Process.Close 幾秒後關閉

參考引用來源:MSDN Process.Close 方法
--

Imports System
Imports System.Diagnostics
Imports System.Threading

Namespace Process_Sample
   Class MyProcessClass

      Public Shared Sub Main()
         Try

            Dim myProcess As Process
            myProcess = Process.Start("Notepad.exe")
            ' Display physical memory usage 5 times at intervals of 2 seconds.
            Dim i As Integer
            For i = 0 To 4
               If not myProcess.HasExited Then

                  ' Discard cached information about the process.
                  myProcess.Refresh()
                  ' Print working set to console.
                  Console.WriteLine("Physical Memory Usage: " + _
                                              myProcess.WorkingSet.ToString())
                  ' Wait 2 seconds.
                  Thread.Sleep(2000)
               Else
                  Exit For
               End If

            Next i

           ' Close process by sending a close message to its main window.
           myProcess.CloseMainWindow()
           ' Free resources associated with process.
           myProcess.Close()

         Catch e As Exception
            Console.WriteLine("The following exception was raised: ")
            Console.WriteLine(e.Message)
         End Try
      End Sub 'Main
   End Class 'MyProcessClass
End Namespace 'Process_Sample

vbnet Process.Responding 運用

參考引用來源:MSDN Process.Responding 屬性
 --
Imports System
Imports System.Diagnostics

Namespace ProcessSample
    Class ProcessMonitorSample

        Public Shared Sub Main()

            ' Define variables to track the peak
            ' memory usage of the process.
            Dim peakPagedMem As Long = 0
            Dim peakWorkingSet As Long = 0
            Dim peakVirtualMem As Long = 0

            Dim myProcess As Process = Nothing

            Try

                ' Start the process.
                myProcess = Process.Start("NotePad.exe")

                ' Display process statistics until
                ' the user closes the program.
                Do

                    If Not myProcess.HasExited Then

                        ' Refresh the current process property values.
                        myProcess.Refresh()

                        Console.WriteLine()

                        ' Display current process statistics.

                        Console.WriteLine("{0} -", myProcess.ToString())
                        Console.WriteLine("-------------------------------------")

                        Console.WriteLine("  physical memory usage: {0}", _
                             myProcess.WorkingSet64)
                        Console.WriteLine("  base priority: {0}", _
                             myProcess.BasePriority)
                        Console.WriteLine("  priority class: {0}", _
                             myProcess.PriorityClass)
                        Console.WriteLine("  user processor time: {0}", _
                             myProcess.UserProcessorTime)
                        Console.WriteLine("  privileged processor time: {0}", _
                             myProcess.PrivilegedProcessorTime)
                        Console.WriteLine("  total processor time: {0}", _
                             myProcess.TotalProcessorTime)
                        Console.WriteLine("  PagedSystemMemorySize64: {0}", _
                            myProcess.PagedSystemMemorySize64)
                        Console.WriteLine("  PagedMemorySize64: {0}", _
                           myProcess.PagedMemorySize64)

                        ' Update the values for the overall peak memory statistics.
                        peakPagedMem = myProcess.PeakPagedMemorySize64
                        peakVirtualMem = myProcess.PeakVirtualMemorySize64
                        peakWorkingSet = myProcess.PeakWorkingSet64

                        If myProcess.Responding Then
                            Console.WriteLine("Status = Running")
                        Else
                            Console.WriteLine("Status = Not Responding")
                        End If
                    End If
                Loop While Not myProcess.WaitForExit(1000)

                Console.WriteLine()
                Console.WriteLine("Process exit code: {0}", myProcess.ExitCode)

                ' Display peak memory statistics for the process.
                Console.WriteLine("Peak physical memory usage of the process: {0}", _
                    peakWorkingSet)
                Console.WriteLine("Peak paged memory usage of the process: {0}", _
                    peakPagedMem)
                Console.WriteLine("Peak virtual memory usage of the process: {0}", _
                    peakVirtualMem)

            Finally
                If Not myProcess Is Nothing Then
                    myProcess.Close()
                End If
            End Try
        End Sub 'Main
    End Class
End Namespace

vbnet Process.HasExited 運用

參考引用來源:MSDN Process.HasExited 屬性
--
Imports System
Imports System.Diagnostics
Imports System.Threading

Namespace Process_Sample
   Class MyProcessClass

      Public Shared Sub Main()
         Try

            Dim myProcess As Process
            myProcess = Process.Start("Notepad.exe")
            ' Display physical memory usage 5 times at intervals of 2 seconds.
            Dim i As Integer
            For i = 0 To 4
               If not myProcess.HasExited Then

                  ' Discard cached information about the process.
                  myProcess.Refresh()
                  ' Print working set to console.
                  Console.WriteLine("Physical Memory Usage: " + _
                                              myProcess.WorkingSet.ToString())
                  ' Wait 2 seconds.
                  Thread.Sleep(2000)
               Else
                  Exit For
               End If

            Next i

           ' Close process by sending a close message to its main window.
           myProcess.CloseMainWindow()
           ' Free resources associated with process.
           myProcess.Close()

         Catch e As Exception
            Console.WriteLine("The following exception was raised: ")
            Console.WriteLine(e.Message)
         End Try
      End Sub 'Main
   End Class 'MyProcessClass
End Namespace 'Process_Sample

MSSQL 處理 XML

請參考來源 
---

一共有5頁! 值得參考一下 ! 採用 C #

MSSQL Fields datatype XML 運用

參考1: MSDN query() 方法 (xml 資料類型)
參考2:MSDN value() 方法 (xml 資料類型)
參考3:MSDN nodes() 方法 (xml 資料類型)
--
  

SQLite 大量insert

請參考來源:SQLite 大量insert
--
PRAGMA table_info( '" + TableName + "' )