You are on page 1of 79

Copyright http://vndownloads.

net Export v Import ra tp tin text t Access (VB)


Hin nay cc bn yu thch lp trnh s dng Access l ngun cha d liu kh ph bin v n gin, d qun tr v p ng c yu cu cng vic. Hm nay chng ti xin gii thiu mt on code export v import ra tp tin text t Access (VB)

Export Text (Flat file) t Access Ms-Access Option Explicit Public Sub Export_Table_2_TextFile() On Error GoTo LocalErrorHandler Dim dbCompany As Database Dim rsGeneral As Recordset Dim ExpGeneral As PubExpGeneral Dim blnTab_Text As Boolean Dim FullName As String Dim FileHandle As Byte Dim strFileToExport As String Dim chkFileExist As String 'Give Path with File name FullName = E:\General ' Thu muc chua du lieu, ban co the thay doi theo nhu cau ca minh blnTab_Text = False Set dbCompany = OpenDatabase(FullName) 'V d tn bang la Company Set rsGeneral = dbCompany.OpenRecordset(Company, dbOpenTable) With ExpGeneral .EmpNumber = No. .EmpName = Name .EmpAddress = Address .EmpCity = City S dng TAB hoc du phy If blnTab_Text Then .Delimiter1 = Chr(9) .Delimiter2 = Chr(9) .Delimiter3 = Chr(9) Else .Delimiter1 = Chr(44) .Delimiter2 = Chr(44) .Delimiter3 = Chr(44) End If .CRLF = vbCrLf End With FileHandle = FreeFile 'Tn tp tin strFileToExport = C:\Exported.txt chkFileExist = Dir(strFileToExport) If chkFileExist <> Then

Copyright http://vndownloads.net
Kill strFileToExport End If Open strFileToExport For Random As FileHandle Len = Len(ExpGeneral) Put FileHandle, , ExpGeneral Do Until rsGeneral.EOF With ExpGeneral .EmpNumber = rsGeneral(EmpNo) .EmpName = rsGeneral(EmpName) .EmpAddress = rsGeneral(EmpAddress) .EmpCity = rsGeneral(EmpCity) End With Put FileHandle, , ExpGeneral rsGeneral.MoveNext Loop rsGeneral.Close Set rsGeneral = Nothing Close FileHandle Exit Sub LocalErrorHandler: MsgBox Error Occured : & Err.Description, , Error End Sub

'Import Text vo Ms-Access Public Sub Import_TextFile_2_Table() On Error GoTo LocalErrorHandler Dim dbCompany As Database Dim rsGeneral As Recordset Dim FullName As String Dim FileHandle As Byte Dim ImportRecord As String Dim flnName As String Dim RowPosition As Double Dim EmpNumber As String Dim EmpName As String Dim EmpAddress As String Dim EmpCity As String Dim Delimiter As String flnName = C:\Exported.txt Delimiter = , FileHandle = FreeFile Open flnName For Input As FileHandle Line Input #FileHandle, ImportRecord FullName = C:\General Set dbCompany = OpenDatabase(FullName) Set rsGeneral = dbCompany.OpenRecordset(Company, dbOpenDynaset) Do Until EOF(FileHandle) Line Input #FileHandle, ImportRecord RowPosition = RowPosition + 1 EmpNumber = Trim(Mid(ImportRecord, 1, InStr(1, ImportRecord, Delimiter, 1) - 1)) EmpName = Trim(Mid(ImportRecord, 7, 10))

Copyright http://vndownloads.net
EmpAddress = Trim(Mid(ImportRecord, 18, 30)) EmpCity = Trim(Mid(ImportRecord, 49)) rsGeneral.AddNew rsGeneral(EmpNo) = EmpNumber rsGeneral(EmpName) = EmpName rsGeneral(EmpAddress) = EmpAddress rsGeneral(EmpCity) = EmpCity rsGeneral.Update Loop Close FileHandle rsGeneral.Close Set rsGeneral = Nothing dbCompany.Close Set dbCompany = Nothing Exit Sub LocalErrorHandler: MsgBox Error Occured : & Err.Description, , Error End Sub

K thut Subclass Listbox trong Visualbasic


Bi vit ny s gip bn hiu k thut subclassing trong VisualBasic. Bn c th p dng cho cc i tng khc khi lp trnh trong VB Windows gi thng ip l mt hng s ti cc form v cc control ca VB bo cho chng bit v tr chut u, khi no th cn v li, phm no ang c nhn v nhiu thng ip khc. K thut subclassing l x l chn nhng thng ip ny trc khi chng n c cc form v control. Bng cch chn cc thng ip ny v x l ''vi th'' trc khi chng n ch, chng ta c th c cc tnh nng ring (nh t v li cc control theo ring). Subclassing l mt k thut tinh vi, ch cn mt li nh (v d nh : do bn gii phng ti nguyn khng tt dn n vic tht thot ti nguyn ca h thng) l c th dn n vic h thng ca bn b thiu ti nguyn lm cho h thng hot ng khng cn tt na (chm i), nng hn l VB b shut down, thm ch treo my. Tuy nhin ni iu ny l bn thc c vn ch bn cng khng nn qu lo ngi v n. V thm 1 ch l bn cng khng nn bm nt stop ca VB khi chng trnh ang chy m bn nn ng form 1 cch thng thng (bm nt close) thc hin tt vic gii phng ti nguyn. Subclassing the Main Window: Chng ta bt u thc hin k thut subclassing bng cch bn m 1 project mi v thm 1 module vo project (project/add module/open). By gi bn c Form1 v Module1 trong project. Bn m Module1 ra v copy, paste on code sau vo : Public Const GWL_WNDPROC = (-4) Public oldWindowProc as Long Public Declare Function SetWindowLong Lib ''user32'' Alias ''SetWindowLongA'' ( _ ByVal hwnd As Long, _ ByVal nIndex As Long, _ ByVal dwNewLong As Long) As Long y l mt hm API ca Windows cho php bn thay i thuc tnh ca 1 ca s (hay control - t by gi chng ta coi nh control cng l mt window), trong trng hp ca chng ta l thay i hm WinProc (hm Winproc l hm m cc window dng x l cc thng ip do h thng (h iu hnh Windows) gi n).

Copyright http://vndownloads.net
hwnd - tham s ny c kiu l long integer dng xc nh 1 ca s (form) hay 1 control (bn c th coi n nh bng s xe dng xc nh tnh duy nht ca 1 xe vy). nIndex - tham s ny cng c kiu l long integer dng xc nh ''cn thay i ci g'' trong hm SetWindowLong ni trn (bn c th tham kho trong b MSDN), trong trng hp ca chng ta nIndex c gi tr l GWL_WNDPROC (v chng ta cn x l hm WinProc m). dwNewLong - hm ny c kiu long integer dng ch ra a ch ca th tc mi m chng ta cn x l. Hm WinProc mi phi c cc tham s ging ht cc tham s ca hm WinProc b thay th. Bn cng phi ch l bn phi gi tr cc thng ip m bn khng x l cho hm WinProc mc nh x l. Bn tip tc copy v dn on m sau vo Module1 : Private Declare Function CallWindowProc Lib ''user32'' Alias ''CallWindowProcA'' ( _ ByVal lpPrevWndFunc As Long, _ ByVal hwnd As Long, _ ByVal Msg As Long, _ ByVal wParam As Long, _ ByVal lParam As Long) As Long Public Function NewWindowProc( _ ByVal hWnd As Long, _ ByVal uMsg As Long, _ ByVal wParam As Long, _ ByVal lParam As Long) As Long Debug.Print ''&H'' & Hex(uMsg), wParam, lParam NewWindowProc = CallWindowProc(oldWindowProc, hWnd, uMsg, wParam, lParam) End Function CallWindowProc dng gi hm WinProc mc nh ra x l, hm NewWindowProc l hm thay th cho hm WinProc. Hm NewWindowProc khng lm bt c vic g ngoi tr vic in ra ca s Debug xem thng ip g c gi n cho ca s ny (ca s b subclassing). Hm NewWindowProc sau gi hm WinProc mc nh x l thng ip 1 cch bnh thng (bin oldWindowProc dng lu a ch hm WinProc mc nh).Tham s m h thng gi cho hm NewWindowProc l : hWnd - handle ca ca s s nhn thng ip; uMsg - thng ip c gi; v 2 tham s cn li (wParam v lParam) mang thng tin ca thng ip, ph thuc vo thng ip c gi. By gi bn c th chy project c, nhng cha c chuyn g xy ra c, ca s (form) ca bn cha b subclass. Mt ln na xin nhc li l bn khng nn bm vo nt stop dng chng trnh v bn cng nn lu project li trc khi chy. thc hin subclass ca s (form) ca bn, bn double vo form v copy, paste on code sau vo : Private Sub Form_Load() 'Subclass the window oldWindowProc = SetWindowLong(Me.hWnd, GWL_WNDPROC, AddressOf NewWindowProc) End Sub Private Sub Form_Unload(Cancel As Integer) 'Unsubclass (return the original window process) SetWindowLong Me.hWnd, GWL_WNDPROC, oldWindowProc End Sub By gi th ok, form ca bn b subclass ! Bn th chy project v xem iu g xy ra ? Ca s Debug

Copyright http://vndownloads.net
ca bn s trn ngp nhng thng tin v thng ip m h thng gi cho form ca bn, bn th di chuyn chut, thay i kch thc form ... m xem. (Hm AddressOf dng ly a ch ca 1 hm). How to put a background image into a Listbox: Bc 1 : Ko 1 ListBox v 1 Image control vo Form1. Bc 2 : Thm 1 s mc (item) vo Listbox (Mc list trong ListBox control). Bc 3 : Thm 1 picture vo Image1 (picture ny bn s dng lm background cho ListBox). Bc 4 : M Module1 ra v dn on code sau vo : Public gBGBrush As Long Public Declare Function CreatePatternBrush Lib ''gdi32'' ( _ ByVal hBitmap As Long) As Long Public Declare Function DeleteObject Lib ''gdi32'' ( _ ByVal hObject As Long) As Long Private Declare Function SetBkMode Lib ''gdi32'' ( _ ByVal hdc As Long, _ ByVal nBkMode As Long) As Long Private Const WM_CTLCOLORLISTBOX = &H134 Cc hm dng cho vic v nn cho ListBox, bn c th xem thm trong b MSDN. Bc 5 : Thay on code trong Form_Load v Form_Unload lc ny bng on code mi nh sau : Private Sub Form_Load() Image1.Visible = False gBGBrush = CreatePatternBrush(Image1.Picture.Handle) 'Subclass the window oldWindowProc = SetWindowLong(Me.hWnd, GWL_WNDPROC, AddressOf NewWindowProc) End Sub Private Sub Form_Unload(Cancel As Integer) 'Unsubclass (return the original window process) SetWindowLong Me.hWnd, GWL_WNDPROC, oldWindowProc DeleteObject gBGBrush End Sub Bc 6 : Vit li hm NewWindowProc trong Module 1 lm vic m chng ta mun (li copy v paste). Public Function NewWindowProc( _ ByVal hWnd As Long, _ ByVal uMsg As Long, _ ByVal wParam As Long, _ ByVal lParam As Long) As Long Debug.Print ''&H'' & Hex(uMsg), wParam, lParam If uMsg = WM_CTLCOLORLISTBOX And gBGBrush <> 0 Then

Copyright http://vndownloads.net
'Make the words print transparently SetBkMode wParam, 1 'allow the original process to set text color, etc. from the lbx properties. CallWindowProc oldWindowProc, hwnd, uMsg, wParam, lParam 'Return our custom brush instead of the default one NewWindowProc = gBGBrush Else NewWindowProc = CallWindowProc(oldWindowProc, hWnd, uMsg, wParam, lParam) End If End Function Bc 7 :Yeah ! Bn lu project li v chy th xem. By gi ListBox ca bn c background phi khng ? Ti sao ta lm c nh vy ? C vi im cn lu nh sau : iu 1 : Chng ta chn thng ip WM_CTLCOLORLISTBOX x l. Thng ip ny c gi cho parent window (ca s cha m, ca s cp cao hn cha ListBox) ca ListBox trc khi h thng v list box. Lc ny wParam mang gi tr l handle DC (devie context) dng v list box, lParam mang gi tr l handle ca list box cn v. V mt iu v cng quan trng l gi tr tr v ca hm WindowProc lc ny, gi tr ny s c h thng dng v nn cho list box, do trong NewWindowProc chng ta cho NewWindowProc ''ch'' n handle ca gBGBrush (NewWindowProc = gBGBrush) v trc chng ta to ra gBGBrush bng cch : gBGBrush = CreatePatternBrush(Image1.Picture.Handle). V tt c cc cng vic khc vn c x l bnh thng bng cch chng ta gi hm : CallWindowProc. iu 2 : Chng ta phi gii phng ti nguyn h thng bng cch, trong Form_Unload : DeleteObject gBGBrush. Nu chng ta khng lm vic ny s dn n hin tng memory leack - lm gim ti nguyn h thng, gy hi cho h thng. Bi ny ch demo vic subclass 1 list box, tuy nhin bn c th p dng k thut ny subclass mi control m bn mun, ch n gin thay i, cc tham s cho ph hp nh : hWnd - handle ca c s cn subclass, x l trong hm NewWindowProc cho ph hp vi tng control, tng thng ip.

Chy tp tin MPEG trong VB6


Chng ta s xy dng mt Class iu khin cc tp tin nh dng theo MPEG. Bn c th thao cc tc v c bn v cc thuc tnh ca tp tin MPEG bng Class ny. Private Declare Function mciGetErrorString Lib ''winmm.dll'' Alias ''mciGetErrorStringA'' (ByVal dwError As Long, ByVal lpstrBuffer As String, ByVal uLength As Long) As Long Private Declare Function GetShortPathName Lib ''kernel32'' Alias ''GetShortPathNameA'' (ByVal lpszLongPath As String, ByVal lpszShortPath As String, ByVal cchBuffer As Long) As Long Private Declare Function mciSendString Lib ''winmm.dll'' Alias ''mciSendStringA'' (ByVal lpstrCommand As String, ByVal lpstrReturnString As String, ByVal uReturnLength As Long, ByVal hwndCallback As Long) As Long Const m_def_FileName = '''' Dim m_FileName As String 'MappingInfo=UserControl,UserControl,-1,Enabled Public Property Get Enabled() As Boolean Enabled = UserControl.Enabled End Property Public Property Let Enabled(ByVal New_Enabled As Boolean)

Copyright http://vndownloads.net
UserControl.Enabled() = New_Enabled PropertyChanged ''Enabled'' End Property 'MemberInfo=13,0,0, Public Property Get FileName() As String FileName = m_FileName End Property Public Property Let FileName(ByVal New_FileName As String) m_FileName = New_FileName PropertyChanged ''FileName'' End Property 'Khi ng cc thuc tnh ca i tng Private Sub UserControl_InitProperties() m_FileName = m_def_FileName End Sub 'c thuc tnnh lu gi Private Sub UserControl_ReadProperties(PropBag As PropertyBag) UserControl.Enabled = PropBag.ReadProperty(''Enabled'', True) m_FileName = PropBag.ReadProperty(''FileName'', m_def_FileName) End Sub Private Sub UserControl_Terminate() mmStop End Sub Private Sub UserControl_WriteProperties(PropBag As PropertyBag) Call PropBag.WriteProperty(''Enabled'', UserControl.Enabled, True) Call PropBag.WriteProperty(''FileName'', m_FileName, m_def_FileName) End Sub Public Function IsPlaying() As Boolean Static s As String * 30 mciSendString ''status MPEGPlay mode'', s, Len(s), 0 IsPlaying = (Mid$(s, 1, 7) = ''playing'') End Function Public Function mmPlay() Dim cmdToDo As String * 255 Dim dwReturn As Long Dim ret As String * 128 Dim tmp As String * 255 Dim lenShort As Long Dim ShortPathAndFie As String If Dir(FileName) = '''' Then mmOpen = ''Error with input file'' Exit Function End If lenShort = GetShortPathName(FileName, tmp, 255) ShortPathAndFie = Left$(tmp, lenShort) glo_hWnd = hWnd

Copyright http://vndownloads.net
cmdToDo = ''open '' & ShortPathAndFie & '' type MPEGVideo Alias MPEGPlay Parent '' & UserControl.hWnd & '' Style 1073741824'' dwReturn = mciSendString(cmdToDo, 0&, 0&, 0&) If dwReturn <> 0 Then 'not success mciGetErrorString dwReturn, ret, 128 mmOpen = ret MsgBox ret, vbCritical Exit Function End If mmPlay = ''Success'' mciSendString ''play MPEGPlay'', 0, 0, 0 End Function Public Function mmPause() mciSendString ''pause MPEGPlay'', 0, 0, 0 End Function Public Function mmStop() As String mciSendString ''stop MPEGPlay'', 0, 0, 0 mciSendString ''close MPEGPlay'', 0, 0, 0 End Function Public Function PositionInSec() Static s As String * 30 mciSendString ''set MPEGPlay time format milliseconds'', 0, 0, 0 mciSendString ''status MPEGPlay position'', s, Len(s), 0 PositionInSec = Round(Mid$(s, 1, Len(s)) / 1000) End Function Public Function Position() Static s As String * 30 mciSendString ''set MPEGPlay time format milliseconds'', 0, 0, 0 mciSendString ''status MPEGPlay position'', s, Len(s), 0 sec = Round(Mid$(s, 1, Len(s)) / 1000) If sec < 60 Then Position = ''0:'' & Format(sec, ''00'') If sec > 59 Then mins = Int(sec / 60) sec = sec - (mins * 60) Position = Format(mins, ''00'') & '':'' & Format(sec, ''00'') End If End Function Public Function LengthInSec() Static s As String * 30 mciSendString ''set MPEGPlay time format milliseconds'', 0, 0, 0 mciSendString ''status MPEGPlay length'', s, Len(s), 0 LengthInSec = Round(Val(Mid$(s, 1, Len(s))) / 1000) 'Round(CInt(Mid$(s, 1, Len(s))) / 1000) End Function Public Function Length() Static s As String * 30 mciSendString ''set MPEGPlay time format milliseconds'', 0, 0, 0 mciSendString ''status MPEGPlay length'', s, Len(s), 0 sec = Round(Val(Mid$(s, 1, Len(s))) / 1000) 'Round(CInt(Mid$(s, 1, Len(s))) / 1000)

Copyright http://vndownloads.net
If sec < 60 Then Length = ''0:'' & Format(sec, ''00'') If sec > 59 Then mins = Int(sec / 60) sec = sec - (mins * 60) Length = Format(mins, ''00'') & '':'' & Format(sec, ''00'') End If End Function Public Function About() frmCtlAbout.Show vbModal, Me End Function Public Function SeekTo(Second) mciSendString ''set MPEGPlay time format milliseconds'', 0, 0, 0 If IsPlaying = True Then mciSendString ''play MPEGPlay from '' & Second, 0, 0, 0 If IsPlaying = False Then mciSendString ''seek MPEGPlay to '' & Second, 0, 0, 0 End Function

Truyn gi tr qua trang khc vi phng thc Server.Tranfer (ASP.NET)

ASP.NET validation controls rt hu dng kim tra gi tr ngi dng nhp vo khi posts back trn cng mt trang. Nhng lm th no s dng trong cc trang khc ?. V d bn c mt trang, WebPostAwayA1.aspx vi 2 textbox control, bn s dng 2 RequiredFieldValidator control. Bn mun chuyn d liu sang mt trang th 2, WebPostAway2.aspx, ch khi cc textbox c nhp gi tr WebPostAwayA1.aspx: <body> <form runat=''server''> <table border=''0''> <tbody> <tr> <td> <asp:Label id=''Label1'' runat=''server''>First Name:</asp:Label> </td> <td> <asp:TextBox id=''txtFirstName'' runat=''server''></asp:TextBox> <asp:RequiredFieldValidator id=''rfvFirstName'' runat=''server'' ErrorMessage=''First name is required.'' ControlToValidate=''txtFirstName''></asp:RequiredFieldValidator> </td> </tr> <tr> <td> <asp:Label id=''Label2'' runat=''server''>Last Name:</asp:Label> </td> <td> <asp:TextBox id=''txtLastName'' runat=''server''></asp:TextBox> <asp:RequiredFieldValidator id=''rfvLastName'' runat=''server'' ErrorMessage=''Last name is required.''

Copyright http://vndownloads.net
ControlToValidate=''txtLastName''></asp:RequiredFieldValidator> </td> </tr> <tr> <td> </td> <td> <asp:Button id=''cmdPost'' onclick=''cmdPost_Click'' runat=''server'' Text=''Submit''></asp:Button> </td> </tr> </tbody> </table> </form> </body>

WebPostAwayA1.aspx s chuyn n WebPostAway2.aspx nu cc gi tr c nhp vo 2 textbox: void cmdPost_Click(Object src, EventArgs e ) { if (Page.IsValid) { Response.Redirect(''WebPostAway2.aspx''); } }

Vn l dng code trn s khng truyn gi tr khi redirect sang trang WebPostAway2. Chng ta s dng Server.Transfer

void cmdPost_Click(Object src, EventArgs e ) { if (Page.IsValid) { Server.Transfer(''WebPostAway2.aspx''); } }

Trong ASP.NET, Server Tranfer mc nh s khng truyn form, query string collections t mt post back. Mc d vy bn c th nh tham s th 2 ca phng thc Tranfer thnh True cc gi tr trn c th c truyn sanh mt trang mi.

void cmdPost_Click(Object src, EventArgs e ) { if (Page.IsValid) { Server.Transfer(''WebPostAway2.aspx'', true); } }

To Font v Xoay Ch
Nhiu Control trong VB cung cp cho bn thuc tnh Font cho php bn thay i tn Font, c Font, in m, in nghing..v..v.. Hm CreateFont cho php bn lm c nhiu hn th na. C c th xoay ch theo mt gc bt k to ra nhng hiu ng th v.

10

Copyright http://vndownloads.net
Vi 14 tham s, c v nh CreateFont l mt hm phc tp nhng thc s n cng kh n gin. Private Declare Function CreateFont Lib ''gdi32'' Alias ''CreateFontA'' ( ByVal font_height As Long, ByVal font_width As Long, ByVal escapement As Long, ByVal orientation As Long, ByVal weight As Long, ByVal italic As Long, ByVal underscore As Long, ByVal strikeout As Long, ByVal character_set As Long, ByVal output_precision As Long, ByVal clipping_precision As Long, ByVal quality As Long, ByVal pitch_and_family As Long, ByVal face_name As String) As Long Bn c th t nhiu trong s cc tham s ny bng 0 s dng cc gi tr mc nh ca Windows. Bn ch cn nm mt s cc tham s l , cc tham s khc cc bn c th tham kho thm trn MSDN: font_height: Gi tr ny l chiu cao ca Font tnh theo n v pixels. font_width: B rng ca Font theo n v Pixel. Nu bng 0 th Windows s dng gi tr mc nh ph hp vi chiu cao ca Font. escapement: y l gc quay ca Font so vi ng nm ngang. Tnh theo . orientation: y l hng ca ch, nhng Windows xem hng ca ch l gc quay ca ch nn i s ny s b b qua. weight: Ch nh m ca Font, l mt s gia 0 -> 900. Bn chn 0 s dng gi tr mc nh, 400 l bnh thng, v 700 l m. italic: Nu gi tr ny khc 0, ch s nghing. underscore: Nu gi tr ny khc 0, ch s c gch di. strikeout: Nu gi tr ny khc 0, ch s c gch gia. character_set: Gi tr ny ch nh cc xc lp k t v d nh Russian, Greek, and Arabic. Thng thng bn nn t gi tr ny bng ANSI_CHARSET (0). face_name: Tn ca Font, v d: ''Times New Roman'' hoc ''Courier New.''..v..v.. Hm CreateFont tr v handle ca Font va mi c to. c th s dng Font ny bn phi dng hm SelectObject API chn Font mi cho mt i tng nh Form hoc PictureBox..v..v... SelectObject s tr v handle ca Font c. Chng trnh c th ''v ch'' dng Font chn. Khi chy xong nn dng hm SelectObject tr v gi tr mc nh v dng hm DeleteObject xa Font v gii phng b nh. By gi hy xem mt v d. Private Declare Function SelectObject Lib ''gdi32'' (ByVal hdc As Long, ByVal hObject As Long) As Long Private Declare Function CreateFont Lib ''gdi32'' Alias ''CreateFontA'' (ByVal H As Long, ByVal W As Long, ByVal E As Long, ByVal O As Long, ByVal W As Long, ByVal I As Long, ByVal u As Long, ByVal S As Long, ByVal C As Long, ByVal OP As Long, ByVal CP As Long, ByVal Q As Long, ByVal PAF As Long, ByVal F As String) As Long Private Declare Function DeleteObject Lib ''gdi32'' (ByVal hObject As Long) As Long Private Const PROOF_QUALITY = 2 Private Sub Form_Load() Me.AutoRedraw = True

11

Copyright http://vndownloads.net
Angle = 45 'Gc quay ca ch escapement = CLng(Angle * 10) Mod 3600 If escapement < 0 Then escapement = escapement + 3600 If escapement = 0 Then escapement = 3600 rfont = CreateFont(20, 20, escapement, escapement, 700, 0, 0, 0, 0, 0, 0, PROOF_QUALITY, 0, ''Verdana'' + Chr(0)) current = SelectObject(Me.hdc, rfont) 'Chn font va to Me.CurrentX = 700 Me.CurrentY = 1100 Me.Print ''Text'' SelectObject Me.hdc, curent 'Tr v Font mc nh DeleteObject (rfont) 'Gii phng b nh End Sub

Dy s v dy chui ngu nhin (PHP)


y l cc chc nng hay gp khi bn thc hin cc website, cn cc dy s hay chui bt k cung cp cho ngi s dng active acount hoc generate cc password... S ngu nhin <?php function randomdigit($digits) { static $startseed = 0; if (!$startseed) { $startseed = (double)microtime()*getrandmax(); srand($startseed); } $range = 8; $start = 1; $i = 1; while ($i<$digits) { $range = $range . 9; $start = $start . 0; $i++; } return (rand()%$range+$start); } ?> Dy chui ngu nhin <?php function randomPass($length = 6) { // all the chars we want to use $all = explode( '' '', ''a b c d e f g h i j k l m n o p q r s t u v w x y z '' . ''A B C D E F G H I J K L M N O P Q R S T U V W X Y Z '' . ''0 1 2 3 4 5 6 7 8 9''); for($i=0;$i<$length;$i++) { srand((double)microtime()*1000000); $randy = rand(0, 61);

12

Copyright http://vndownloads.net
$pass .= $all[$randy]; } return $pass; } ?>

PHP v Java
Mt iu kh th v cc cc chc nng ca PHP l kh nng s dng cc phng thc ca cc i tng Java, m ra kh nng tch hp cc ng dng PHP ca bn vi cc ng dng Java. Mi cc bn tham kho cc thc hin. s dng bn cn ci t Java Virtual Machine (JVM). Nu bn s dng JDKs t Sun, Kaffe, IBM, hay Blackdown, bn s li v mt tc . Khi bn ci t PHP, bn cn thm --with-java thm cc th vin dnh cho java, hoc sa tp tin php.ini [Java] java.library.path=/path/to/library java.class.path=/classpath/ extension_dir=/path/to/extensions extension=libphp_java.so bn cn a ng dn Java chnh xc. on script sau s ni v in ra mn hnh bng cc thuc tnh ca Java <? $system = new Java(''java.lang.System''); echo ''<P>Java version = '' . $system->getProperty(''java.version'') . ''<br>''; echo ''Java vendor = '' . $system->getProperty(''java.vendor'') . ''</p>''; ?> Nu bn c hiu bit v Java, bn s c th xy dng cc ng dng tch hp vi kh nng khng gii hn.

Chuyn mc chn trn Menu chnh sang gc phi


Theo mc nh th thanh menu chnh lun nm gc bn phi. V VB cng khng cung cp cho chng ta bt c thuc tnh g a n sang bn phi. Nhng vi API bn c th d dng lm c iu ny. 1.Hy to mt Form mi, Sau Click vo Tools --> Menu Editor thm vo chng trnh 3 menu chnh cn cc menu con th ty . 2. Dng on Code sau : Private Declare Function GetMenu Lib ''user32'' (ByVal hwnd As Long) As Long Private Declare Function ModifyMenu Lib ''user32'' Alias ''ModifyMenuA'' (ByVal hMenu As Long, ByVal nPosition As Long, ByVal wFlags As Long, ByVal wIDNewItem As Long, ByVal lpString As Any) As Long Private Declare Function DrawMenuBar Lib ''user32'' (ByVal hwnd As Long) As Long Private Const MF_BYPOSITION = &H400& Private Const MF_HELP = &H4000& Private Sub Form_Load() res = GetMenu(Me.hwnd) ' Ly Handle ca Menu ModifyMenu res, 2, MF_BYPOSITION Or MF_HELP, 2, ''&Help'' DrawMenuBar Me.hwnd ' V li Menu Bar End Sub

13

Copyright http://vndownloads.net
Khng kh lm nhng kt qu tht tuyt vi phi khng

V hiu DeskTop
Hm nay chng ti tip tc gii thiu vi cc bn mt v d v cch s dng hm API trong VB.Bn c mun lm cho Desktop b ''t lit'' khng? Bn hon ton c th v Desktop cng l mt ca s nh bao chng trnh khc, iu bn cn bit l class name ca n ''Progman''.

Bn thm vo mt Module : Option Explicit DefLng A-Z Declare Function FindWindowEx Lib ''user32'' _ Alias ''FindWindowExA'' (ByVal hWnd As Long, _ ByVal hWndChild As Long, ByVal lpszClassName As String, _ ByVal lpszWindow As String) As Long Declare Function ShowWindow Lib ''user32'' _ (ByVal hWnd As Long, ByVal nCmdShow As Long) As Long Public Const SW_HIDE = 0 Public Const SW_SHOW = 5 Public Const g_cstrShellViewWnd As String = ''Progman'' Sau thm vo Project hai button v on code sau: Option Explicit DefLng A-Z Private Function FindShellWindow() As Long 'Hm dng ly Handle ca Desktop Dim hWnd As Long On Error Resume Next hWnd = FindWindowEx(0&, 0&, g_cstrShellViewWnd, vbNullString) If hWnd <> 0 Then FindShellWindow = hWnd End If End Function Private Sub HideShowWindow(ByVal hWnd As Long, Optional ByVal Hide As Boolean = False) Dim lngShowCmd As Long On Error Resume Next If Hide = True Then lngShowCmd = SW_HIDE Else lngShowCmd = SW_SHOW End If Call ShowWindow(hWnd, lngShowCmd) End Sub Private Sub command2_Click() Dim hWnd As Long On Error Resume Next

14

Copyright http://vndownloads.net
hWnd = FindShellWindow() If hWnd <> 0 Then Call HideShowWindow(hWnd) End If End Sub Private Sub command1_Click() Dim hWnd As Long On Error Resume Next hWnd = FindShellWindow() If hWnd <> 0 Then Call HideShowWindow(hWnd, True) End If End Sub Private Sub Form_Load() Command1.Caption = ''Hide Desktop'' Command2.Caption = ''Show Desktop'' End Sub

Lm n nt Start ca Window
Cc sc mnh tim n ca VB nm vic thao tc vi cc hm WinAPI. Bn c th lm bt c vic g nu hiu v nm c cch s dng cc hm API. V d bn c th lm cho nt Start ca Windows bin mt mt cch d dng

Const SWP_HIDEWINDOW = &H80 Const SWP_SHOWWINDOW = &H40 Const GW_CHILD = 5 Const GW_HWNDNEXT = 2 Private Declare Function SetWindowPos Lib ''user32'' (ByVal hwnd As Long, ByVal hWndInsertAfter As Long, ByVal x As Long, ByVal y As Long, ByVal cx As Long, ByVal cy As Long, ByVal wFlags As Long) As Long Private Declare Function FindWindow Lib ''user32'' Alias ''FindWindowA'' (ByVal lpClassName As String, ByVal lpWindowName As String) As Long Private Declare Function GetWindow Lib ''user32'' (ByVal hwnd As Long, ByVal wCmd As Long) As Long Private Declare Function GetClassName Lib ''user32'' Alias ''GetClassNameA'' (ByVal hwnd As Long, ByVal lpClassName As String, ByVal nMaxCount As Long) As Long Dim tWnd As Long, bWnd As Long, sSave As String * 250 Private Sub Form_Load() tWnd = FindWindow(''Shell_traywnd'', vbNullString) bWnd = GetWindow(tWnd, GW_CHILD) Do GetClassName bWnd, sSave, 250 If LCase(Left$(sSave, 6)) = ''button'' Then Exit Do bWnd = GetWindow(bWnd, GW_HWNDNEXT) Loop 'n start button SetWindowPos bWnd, 0, 0, 0, 0, 0, SWP_HIDEWINDOW End Sub Private Sub Form_Unload(Cancel As Integer) 'hin li start button SetWindowPos bWnd, 0, 0, 0, 0, 0, SWP_SHOWWINDOW

15

Copyright http://vndownloads.net
End Sub

Gii hn ca bin trong VB.NET


Trong VB.6 bn c th khai bo gi tr kiu nh Public, Private, Friend, v (the local) Dim. Hin nay trong VB.NET, c mt cch khai bo l c gi tr trong block (block-level scope). C ngha l nu bn khai bo mt bin trong mt cu lnh dng block (nh For Next, While, Select Case, If Then... ) , cc bin ch c hiu trong phm vi ca block . Bn s thy v d sau y s bo li khi bin dch Private Sub DoSomething() Dim bln As Boolean = True If bln Then Dim x As Long = 10 End If x = 100 's gy ra mt li (Nu Option Explicit c khai bo) End sub Bn nn lu khi lp trnh VB.NET

Du m ngun ASP
Chng ti thng nhn c cc cu hi ''Lm th no ti c th gi b mt c code ca ti khi host cc Server ca ISP ?'' Vi cc component rt d, vi cc script bng ASP khng n gin nhng vn lm c. B mt y l mt tin ch nh c tn l Windows Script Encoder ca Microsoft. Script Encoder l mt tool dng ln n gin cho php ngi ngi thit k m ho code ca h cc Web Host v Web Client khng th thay i source ca mnh. V d bn c mt on code nh sau: <%@ Language=''VBScript'' %> <% Option Explicit %> <html> <head> <title>V d Windows Script Encoding</title> </head> <body> <p> By gi l: <% Response.Write Time() %> vo ngy <% Response.Write Date() %>. </p> </body> </html> Sau khi m ho <%@ Language=''VBScript.Encode'' %> <%#@~^EQAAAA==~}wObWP2Xw^rmbY~GwYAAA==^#~@%> <html> <head> <title>V d Windows Script Encoding Sample</title> </head> <body> <p> By gi l <%#@~^FwAAAA==~''+daW/+cMrYPPks+cb,yAcAAA==^#~@%>

16

Copyright http://vndownloads.net
vo ngy<%#@~^FwAAAA==~''+daW/+cMrYP9lD+cb,twcAAA==^#~@%>. </p> </body> </html> Bn thy VBScript chuyn VBScript.Encode v cc dng code ASP khng cn kh nng c. C php cu lnh

SCRENC [/s] [/f] [/xl] [/l defLanguage ] [/e defExtension] input file output file /s : t dng thc hin khngt hin trn mn hnh /f : Chp chng nu c file cng tn tn ti /xl : Xc nh ngn ng @language khng c u cc trang ASP /l defLanguage: ngn g mc nh(JScript hoc VBScript) /e defExtension: kiu tp tin xut ra inputfile : tn tp tin xut cn m m ho outputfile: tn tp tin sau khi m ho Sau y l 4 loi tp tin c th c m ho bi Script Encoder ASP. HTML. Plain text Scriptlet. V d screnc test.html encode.html

Mt s mo vt ca ASP.NET
Hm nay chng ta s tm hiu cc k thut sau: Hin th cc hp thoi cnh bo trn WEB (Displaying Web Warning Messages), to mt nt Default, cc b n sau cc User Control.

Hin th cc Web Warning Message: y l cc bc n gin to mt cnh bo bng Javascript, bn ch cn mt mt dng lnh v t bt c du trn ASP.NET

1. t cc dng script sau <body> tag: 2. <script> 3. <asp:Literal id=''ltlAlert'' runat=''server'' 4. EnableViewState=''False''> 5. </asp:Literal> 6. </script> 7. K tha cc s kin 8. Protected WithEvents ltlAlert _ 9. As System.Web.UI.WebControls.Literal 10. 11. Thm cc dng code sau Web form ca bn. 12. Private Sub Say(ByVal Message As String) 13. ' Format string properly 14. Message = Message.Replace(''''', ''\''') 15. Message = Message.Replace(Convert.ToChar(10), ''\n'') 16. Message = Message.Replace(Convert.ToChar(13), '''')

17

Copyright http://vndownloads.net
17. ' Display as JavaScript alert 18. ltlAlert.Text = ''alert(''' & Message & ''')'' 19. End Sub 20. Bt c khi no bn mun hin th mt message, ch n gin gi hm say 21. Say(''Sorry, your password is invalid! '' & _ 22. Microsoft.VisualBasic.vbNewLine & _ 23. ''Please try again, or click the Signup button to _ 24. register now.'') To mt nt Default 'Enter' Tng tng bn c mt trang ASP.NET vi mt nt search. Ngi s dng nh vo mt on text v nhn Enter. Form s submit v kt qu c tr v. Ni cch khc, nt search c set l default. Lm cch no? n gin thm mt dng vo s kin Page Load, gi phng thc RegisterHiddenField Page.RegisterHiddenField(''__EVENTTARGET'', ''tnntcabn'') Cc b mt sau cc User Control

Cc User Control thng l cc mnh code dng nh v ngha khi bn nhn. N khng qu kh, v rt hu ch trong cc website ln v tit kim cng sc lm vic ca bn. Chnh xc l chng lm g? Nu bn tng s dng ASP trc y, mt user control nh mt include file. Bn c th c mt menu xanh vi cc icon p mt, mi cc link n cc phn khc nhau ca site. Bn khng mun mi trang u phi thit k menu ny, bn to menu nh mt user control v th vo bt c ni u bn thy cn thit. 1. Trong Web application project, chn Project, Add Web User Control t menu. Chn mt ci tn v click Open. 2. Thit k user control.V ng qun y khng phi l mt trang Web hon chnh, ch l mt phn nh, nh mt login box hoc copyright notice. To code bnh thng 3. Khi kt thc ng v lu li 4. Trn trang bn mun th, ko v th tp tin .acx t ca s Solution Explorer Bn thy rng c th d dng s dng bt c ni u bn mun

Gn (binding) d liu vo DropDownList (ASP.NET)


binding mt SqlDataReader chng ta c th s dng mt hm in d liu vo DropDownList. C th bn c th to hm nh sau: public static bool FillDropDownList(DropDownList dDl,string Select) { SqlConnection m_SqlConnection = new SqlConnection(CRbvDB.RbvWebDSN); SqlCommand m_SqlCommand = new SqlCommand(Select,m_SqlConnection); try { dDl.DataValueField = ''Id''; //trng ny bn c th chnh sa cho ph hp dDl.DataTextField = ''Name''; //trng ny bn c th chnh sa cho ph hp m_SqlConnection.Open(); SqlDataReader m_SqlDataReader = m_SqlCommand.ExecuteReader(); dDl.DataSource = m_SqlDataReader; dDl.DataBind();

18

Copyright http://vndownloads.net
m_SqlDataReader.Close(); // Close DataReader } // try catch // (Exception e) // Exception Removed { return false; //throw new Exception(''C li khi in DropDownLit -> '' + e.ToString()); } // catch finally { m_SqlCommand.Dispose(); m_SqlConnection.Close(); // ng kt ni m_SqlConnection.Dispose(); } return true; } Trong v d DropDownList s in vi cc trng trong database.Bn c th truyn bin s dng hm nh sau: string selectCmd = ''SELECT Id,LastName +', '+ FirstName AS Name ''; //(cc trng d liu trn y l gi lp) selectCmd += ''FROM aRepresentative WHERE Id=SLS ORDER BY LastName ''; dDl.FillDropDownList(sslSlsId,selectCmd);

To Control kim tra Credit Card (ASP.NET + DLL)


u tin chng ta s to mt lp bao gm cc hm chnh ca chng ta (thut ton nhn din s credit card chng ti trnh by phn trc)

1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25:

using System; using System.Web.UI; using System.Web.UI.WebControls; namespace CustomValidators { /// <summary> /// Summary description for Class1. /// </summary> public class CreditCardValidator : BaseValidator { protected override bool EvaluateIsValid() { //-- Ly gi tr string valueToValidate = this.GetControlValidationValue(this.ControlToValidate); int indicator = 1; int firstNumToAdd = 0; int secondNumToAdd = 0; string num1; string num2;

19

Copyright http://vndownloads.net
26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69: 70: 71: 72: 73: 74: 75: 76: 77: //-- chuyn s credit sang mng k t char[] ccArr = valueToValidate.ToCharArray(); for (int i=ccArr.Length-1;i>=0;i--) { char ccNoAdd = ccArr[i]; int ccAdd = Int32.Parse(ccNoAdd.ToString()); if (indicator == 1) { firstNumToAdd += ccAdd; indicator = 0; } else {

if ((ccAdd + ccAdd) >= 10) { int temporary = (ccAdd + ccAdd); num1 = temporary.ToString().Substring(0,1); num2 = temporary.ToString().Substring(1,1); secondNumToAdd += (Convert.ToInt32(num1) + Convert.ToInt32(num2)); } else { secondNumToAdd += ccAdd + ccAdd; } indicator = 1; } } bool isValid = false; if ((firstNumToAdd + secondNumToAdd) % 10 == 0) { isValid = true; } else { isValid = false; } return isValid; } } }

Bin dch thnh Dll:

20

Copyright http://vndownloads.net
csc /target:library /out:c:\inetpub\wwwroot\bin\Validator.dll *.cs /r:System.dll,System.Web.dll S dng Dll trong d n ca chng ta

1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14:

<%@ Register TagPrefix=''custom'' Namespace=''CustomValidators'' Assembly=''Validator'' %> <html> <body> <form runat=''server''> <asp:TextBox ID=''CCNumber'' Runat=''server'' /> <custom:CreditCardValidator ControlToValidate=''CCNumber'' Runat=''server'' ErrorMessage=''Credit Card Number Invalid!'' /> <asp:Button Text=''Validate'' Runat=''server'' /> </form> </body> </html>

Thao tc cc s kin ca Web User Control


Trc khi c ASP.NET bn s dng cc code chung bng tag kha <#include>. Trong ASP.NET cho php bn to cc Web user control, mt khi bn to c mt Web user control bn c th ko th n bt c u. Mt cu hi t ra l l khi s dng cc Web user control, lm th no nm gi cc s kin pht sinh t cc control cha trong trang ASPX .

Trong Visual Studio .NET, to mt user control tn MyToolbar vi 2 button controltrn n. nh thuc tnh button ID l btnSave v btnCancel v mi thuc tnh text button l Save v Cancel. AutoEventWireup=''false'' Codebehind=''MyToolbar.ascx.vb'' Inherits=''WebApplication2.MyToolbar'' TargetSchema=http://schemas. microsoft.com/intellisense/ie5%> < asp:Button id=''btnSave'' Text=''Save'' runat=''server''> < asp:Button id=''btnCancel'' Text=''Save'' runat=''server''> to toolbar trn trang ASP bng cch ko control trn ca s Solution Explorer vo trang. thm label vo trang ASPX, tn label lblEvent, v tnh thuc tnh Text l ''''. Tip theo bn thm code x l s kin t cc control. chn ''(Overrides)'' t ca s code view trong Class Name. Chn OnBubbleEvent trong Method Name. Bn s c mt s kin sau: Protected Overrides Function _ OnBubbleEvent(ByVal source As _ Object, ByVal args As _ System.EventArgs) As Boolean End Function OnBubbleEvent x l tt c cc s kin pht sinh t control. i s source l control pht sinh s kin. i s args cha bt c i s chuyn vo khi s kin pht sinh. Khi bn bit control no pht sinh

21

Copyright http://vndownloads.net
bn c th c nhng cch thch hp x l trn Web ca bn. Trong v d toolbar, kim tra source l mt button; s dng thuc tnh id xc nh button. Thm on code vo OnBubbleEvent: If source.GetType.Equals _ (GetType(Button)) Then Dim oButton As Button = source Select Case oButton.ID Case ''btnSave'' lblEvent.text = ''Saved record'' Case ''btnCancel'' lblEvent.text = ''Canceled changes'' Case Else '...... End Select End If

Email Attachment (ASP.NET)


y l mt on code nh gip bn gi mail c km (attach) tp tin. Hy vng on code gip ch cho cc bn trong cng vic. <%@ Page Language=''VB'' ClientTarget=''downlevel'' %> <%@ Import Namespace=''System.Web.Mail'' %> <script language=''VB'' runat=''server''>

Sub btnSendMail_OnClick(Source As Object, E As EventArgs) Dim myMessage As New MailMessage Dim myAttachment As MailAttachment Dim myMail As SmtpMail Dim strEmail As String If Page.IsValid() Then strEmail = txtEmail.Text myMessage.From = ''webmaster@'' & Request.ServerVariables(''SERVER_NAME'') myMessage.To = strEmail myMessage.Subject = ''E-mail Sample from VASC!'' myMessage.Body = ''This message was sent from sample code '' myAttachment = New MailAttachment(Server.MapPath(''attachment.txt'')) ' tp tin bn chn myMessage.Attachments.Add(myAttachment) myMail.SmtpServer = ''localhost'' ' hoc SMTP Server no bn nh myMail.Send(myMessage) frmEmail.Visible = False lblUserMessage.Text = ''Your message (with attachment) has been sent to '' & strEmail & ''.'' End If End Sub </script> <html> <head> <title>ASP.NET Email (with Attachment) Sample</title> </head> <body>

22

Copyright http://vndownloads.net

<asp:Label id=''lblUserMessage'' text=''Enter your e-mail address:'' runat=''server'' /> <form method=''post'' id=''frmEmail'' runat=''server''> <asp:TextBox id=''txtEmail'' size=''30'' runat=''server'' /> <asp:RequiredFieldValidator runat=''server'' id=''validEmailRequired'' ControlToValidate=''txtEmail'' errormessage=''Please enter an email address.'' display=''Dynamic'' /> <asp:RegularExpressionValidator runat=''server'' id=''validEmailRegExp'' ControlToValidate=''txtEmail'' ValidationExpression=''^[\w-]+@[\w-]+\.(com|net|org|edu|mil)$'' errormessage=''Please enter a valid email address.'' Display=''Dynamic'' /> <asp:Button id=''btnSendMail'' text=''Send Mail!'' OnClick=''btnSendMail_OnClick'' runat=''server'' /> </form> </body> </html>

Ly kch thc mn hnh ca client trong ASP.NET


Bn mun xc nh kch thc mn hnh ca client dn trang web t ng theo cu hnh. Cc dng code sau s gip bn ly rng v cao ca client v gi tr li v Server Chng ti s dng 2 tp tin start.aspx <html> <body onload=''storeWidthAndHeightToTheServer()''> <form id=''resolution'' method=''post'' action=''default.aspx''> </form> <script language=''javascript''> function storeWidthAndHeightToTheServer() with (document.getElementById('resolution')) { var InitStr; InitStr = ''default.aspx?ScreenWidth=''; InitStr += screen.width; InitStr += ''&ScreenHeight=''; InitStr += screen.height; action = InitStr; submit(); } } </script> </body> </html>

default.aspx <html> <head> <script language=''C#'' runat=''server''> void Page_Load(object s, EventArgs e)

23

Copyright http://vndownloads.net
{ string width = HttpContext.Current.Request.QueryString[''ScreenWidth'']; string height = HttpContext.Current.Request.QueryString[''ScreenHeight'']; Session[''width''] = width; Session[''height''] = height; Label1.Text = ''Width= '' + width + '' Height= '' + height; } </script> </head> <body> <form runat=''server'' ID=''Form1''> <asp:Table Width=''100%'' Runat=''server'' ID=''Table1''> <asp:TableRow> <asp:TableCell HorizontalAlign=''Center''> <asp:Label ID=''Label1'' Runat=''server''></asp:Label> </asp:TableCell> </asp:TableRow> </asp:Table> </form> </body> </html> By gi bn c th c cc gi tr v lu vo session v s dng cc gi tr bt c u trong web application

p cc kiu cho cc ASP.NET Web Control


C nhiu cch khc nhau s dng cc kiu cho cc Web control. Mt trong cc cc thng dng nht l s dng cc style sheet. Bn c th p dng cc ca ca Web control mt cch t ng v .NET Framework class library c cung cp cc lp thc hin vic ny. The System.Web.UI.WebControls.Style Class Lp Style c nh ngha trong System.Web.UI.WebControls namespace th hin kiu ca mt Web server control. Lp ny cung cp cc thuc tnh c th c s dng p dng cho mt hoc nhiu Web control. S dng cc thuc tnh trn bn c th t mu background, foreground, rng border v kiu v kch thc ca Web server controlcontrols to provide a common appearance. Using these properties, you can set the . Table 1 describes the Style class properties. Cc thuc tnh ca lp Style BackColor BorderColor BorderStyle BorderWidth CssClass Font ForeColor Height Width Ly v nh mu background ca Web server control Ly v nh mu border ca Web server control Ly v nh kiu border ca the Web server control Ly v nh rng border ca Web server control Ly v nh render CSS class ca Web server control trn my client. Ly v nh cc thuc tnh lin quan font ca the Web server control Ly v nh mu foreground ca Web server control. Ly v nh chiu cao ca Web server control. Ly v nh chiu rng ca Web server control.

The System.Web.UI.WebControls.WebControl.ApplyStyle Method

24

Copyright http://vndownloads.net

Phng thc ApplyStyle ca lp WebControl dng p kiu mt i tng Style cho mt Web control. Phng thc ny s dng i s l mt Style object.V d: WebControl ctrl; Style s; ctrl.ApplyStyle(s); V d c th: Bn to mt Web application s dng Visual Studio .NET v thm 3 control vo Form - mt Button, mt TextBox, v mt ListBox. By gi bn to 2 phng thc - CreateStyle v SetControStyle. Phng thc CreateStyle ly cc i s ca nh mu background , mu foreground, rng border,v cc kiu font. private Style CreateStyle(Color backClr, Color foreClr, int borderWidth, string fntName, int fntSize, bool fntBold, bool fntItalic /* Bn c th thm nhiu i s */ { Style s = new Style(); s.BackColor = backClr; s.ForeColor = foreClr; s.BorderWidth = borderWidth; s.Font.Name = fntName; s.Font.Size = fntSize; s.Font.Bold = fntBold; s.Font.Italic = fntItalic; return s; } // Phng thc p kiu n mt Web cotrol private void SetControlStyle(System.Web.UI.WebControls.WebControl ctrl,Style s) { ctrl.ApplyStyle(s); } private void Button1_Click(object sender, System.EventArgs e) { Style st = CreateStyle(Color.Green, Color.Yellow, 3,''Verdana'', 10, true, true); SetControlStyle(TextBox1, st); st = CreateStyle(Color.Red, Color.Black, 2,''Verdana'', 12, true, true); SetControlStyle(SetStyleBtn, st); st = CreateStyle(Color.Blue, Color.Yellow, 2,''Verdana'', 12, true, true); SetControlStyle(ListBox1, st); }

Truy cp cc gi tr ca Server t trong Web Service


Mt trong cc cu hi thng gp trong cc newsgroup l '' Lm th no ti ly c a ch IP ca client browser trong mt web service ?''. Cu tr li rt n gin. S dng lp Context trong System.Web.Services. Bn c th hiu c cc lm thng qua cc v d sau ca chng ti. Chng ta s xem hai v d kh n gin

25

Copyright http://vndownloads.net
1. Nhn IP address ca client browser 2. Nhn tt c cc gi tr ca web server <%@ Webservice Language=''C#'' class=''httpvars'' %> using System; using System.Collections; using System.Web.Services; public class httpvars : WebService { // Phng thc ny tr v a ch IP ca client [WebMethod] public String ipAddress () { return Context.Request.ServerVariables[''REMOTE_ADDR'']; } // Phng thc tr v tt c cc gi tr ca Server [WebMethod] public String allHttpVars () { NameValueCollection serverVars; String returnValue = ''''; serverVars = Context.Request.ServerVariables; String[] arVars = serverVars.AllKeys; for (int x = 0; x < arVars.Length; x++) { returnValue+= ''<b>'' + arVars[x] + ''</b>: ''; returnValue+= serverVars[arVars[x]] + ''<br>''; } return returnValue; } }

Nhiu runat=server forms trn cng mt trang (ASP.NET)


ASP.NET khng h tr nhiu runat=server forms trn cng mt trang. khc phc vic ny, bn c th t mi form trong mi Panel control ring bit, v cho php ngi dng d dng chuyn gia cc panel bng click mt radio button. Bn c th tham kho v d sau: 2FormExample.aspx <%@ Page language=''c#'' Codebehind=''2FormExample.cs'' AutoEventWireup=''false'' Inherits=''_3leaf_app.C2FormExample'' %> <html><head> <meta name=vs_targetSchema content=''HTML 4.0''> <meta name=''GENERATOR'' Content=''Microsoft Visual Studio 7.0''> <meta name=''CODE_LANGUAGE'' Content=''C#''></head> <body>

26

Copyright http://vndownloads.net
<form method=''post'' runat=''server'' ID=Form1> <p>Lookup by <asp:RadioButton id=RadioButton1 runat=''server'' Text=''First Name'' AutoPostBack=''True'' groupname=g1 checked=True></asp:RadioButton> <asp:RadioButton id=RadioButton2 runat=''server'' Text=''Last Name'' AutoPostBack=''True'' groupname=g1></asp:RadioButton></p> <p></p> <p> <asp:Panel id=Panel1 runat=''server'' visible=True> First Name : <asp:TextBox id=TextBox1 runat=''server''></asp:TextBox> <asp:RequiredFieldValidator id=RequiredFieldValidator1 runat=''server'' ErrorMessage=''*'' ControlToValidate=''TextBox1''></asp:RequiredFieldValidator> <asp:Button id=Button1 runat=''server'' Text=''Submit''></asp:Button> </asp:Panel> <asp:Panel id=Panel2 runat=''server'' visible=False> Last Name : <asp:TextBox id=TextBox2 runat=''server''></asp:TextBox> <asp:RequiredFieldValidator id=RequiredFieldValidator2 runat=''server'' ErrorMessage=''*'' ControlToValidate=''TextBox2''></asp:RequiredFieldValidator> <asp:Button id=Button2 runat=''server'' Text=''Submit''></asp:Button> </asp:Panel> <p></p> <p> <asp:label id=Label1 runat=''server''></asp:label> </p> </form> </body></html>

2FormExample.cs namespace _3leaf_app { using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; /// <summary> /// Summary Description for C2FormExample. /// </summary> public class C2FormExample : System.Web.UI.Page { protected System.Web.UI.WebControls.Button Button2; protected System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator2; protected System.Web.UI.WebControls.TextBox TextBox2; protected System.Web.UI.WebControls.Button Button1;

27

Copyright http://vndownloads.net
protected System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator1; protected System.Web.UI.WebControls.TextBox TextBox1; protected System.Web.UI.WebControls.Label Label1; protected System.Web.UI.WebControls.Panel Panel2; protected System.Web.UI.WebControls.Panel Panel1; protected System.Web.UI.WebControls.RadioButton RadioButton2; protected System.Web.UI.WebControls.RadioButton RadioButton1; public C2FormExample() { Page.Init += new System.EventHandler(Page_Init); } protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { } } protected void Page_Init(object sender, EventArgs e) { // // CODEGEN: This call is required by the ASP+ Windows Form Designer. // InitializeComponent(); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { RadioButton1.CheckedChanged += new System.EventHandler (this.RadioButton1_Checke dChanged); Button1.Click += new System.EventHandler (this.Button1_Click); RadioButton2.CheckedChanged += new System.EventHandler (this.RadioButton2_CheckedChanged); Button2.Click += new System.EventHandler (this.Button2_Click); this.Load += new System.EventHandler (this.Page_Load); } public void Button2_Click (object sender, System.EventArgs e) { Label1.Text = ''You want to search on last name''; } public void Button1_Click (object sender, System.EventArgs e) { Label1.Text = ''You want to search on first name''; } public void RadioButton2_CheckedChanged (object sender, System.EventArgs e) { Panel1.Visible = false;

28

Copyright http://vndownloads.net
Panel2.Visible = true; } public void RadioButton1_CheckedChanged (object sender, System.EventArgs e) { Panel1.Visible = true; Panel2.Visible = false; } } }

Chuyn i gi tr t s sang ch (.NET)


y l mt v d n gin dng chuyn i s sang ch tng ng (ting Anh). Rt hu dng trong k ton v cc ho n. V d bao gm c trang ASPX s dng service ny Numerals.asmx <%@ WebService Language=''VB'' Class=''NumberToWord'' %> Imports System Imports System.Web.Services Public Class NumberToWord : Inherits WebService Public Function <WebMethod()> Int(num As double) As double return(num-(num mod 1)) end function Public Function <WebMethod()> BritishNumerals(numstr As double) As String Dim tempstr as string Dim newstr as string numstr = Cdbl(numstr) If numstr > 10 ^ 24 Then return ''Too big'' Exit Function End If If numstr >= 10 ^ 7 Then newstr = BritishNumerals(Int(numstr / (10^7))) numstr = ((numstr / 10 ^ 7) - Int(numstr / 10 ^ 7)) * 10 ^ 7 If numstr = 0 Then tempstr = tempstr & newstr & ''Crore '' Else tempstr = tempstr & newstr & ''Crore, '' End If End If If numstr >= 10 ^ 5 Then newstr = BritishNumerals(Int(numstr / 10 ^ 5)) numstr = ((numstr / 10 ^ 5) - Int(numstr / 10 ^ 5)) * 10 ^ 5 If numstr = 0 Then tempstr = tempstr & newstr & ''Lakh '' Else

29

Copyright http://vndownloads.net
tempstr = tempstr & newstr & ''Lakh, '' End If End If If numstr >= 10 ^ 3 Then newstr = BritishNumerals(Int(numstr / 10 ^ 3)) numstr = ((numstr / 10 ^ 3) - Int(numstr / 10 ^ 3)) * 10 ^ 3 If numstr = 0 Then tempstr = tempstr & newstr & ''Thousand '' Else tempstr = tempstr & newstr & ''Thousand, '' End If End If If numstr >= 10 ^ 2 Then newstr = BritishNumerals(Int(numstr / 10 ^ 2)) numstr = ((numstr / 10 ^ 2) - Int(numstr / 10 ^ 2)) * 10 ^ 2 If numstr = 0 Then tempstr = tempstr & newstr & ''Hundred '' Else tempstr = tempstr & newstr & ''Hundred And '' End If End If If numstr >= 20 Then Select Case Int(numstr / 10) Case 2 tempstr = tempstr & ''Twenty '' Case 3 tempstr = tempstr & ''Thirty '' Case 4 tempstr = tempstr & ''Forty '' Case 5 tempstr = tempstr & ''Fifty '' Case 6 tempstr = tempstr & ''Sixty '' Case 7 tempstr = tempstr & ''Seventy '' Case 8 tempstr = tempstr & ''Eighty '' Case 9 tempstr = tempstr & ''Ninety '' End Select numstr = ((numstr / 10) - Int(numstr / 10)) * 10 End If numstr=Int(numstr+0.5) If numstr > 0 Then Select Case NUMSTR MOD 100 Case 1 tempstr = tempstr & ''One '' Case 2 tempstr = tempstr & ''Two '' Case 3

30

Copyright http://vndownloads.net
tempstr = tempstr & ''Three '' Case 4 tempstr = tempstr & ''Four '' Case 5 tempstr = tempstr & ''Five '' Case 6 tempstr = tempstr & ''Six '' Case 7 tempstr = tempstr & ''Seven '' Case 8 tempstr = tempstr & ''Eight '' Case 9 tempstr = tempstr & ''Nine '' Case 10 tempstr = tempstr & ''Ten '' Case 11 tempstr = tempstr & ''Eleven '' Case 12 tempstr = tempstr & ''Twelve '' Case 13 tempstr = tempstr & ''Thirteen '' Case 14 tempstr = tempstr & ''Fourteen '' Case 15 tempstr = tempstr & ''Fifteen '' Case 16 tempstr = tempstr & ''Sixteen '' Case 17 tempstr = tempstr & ''Seventeen '' Case 18 tempstr = tempstr & ''Eighteen '' Case 19 tempstr = tempstr & ''Nineteen '' End Select numstr = ((numstr / 10) - Int(numstr / 10)) * 10 End If return tempstr End Function Public Function <WebMethod()> AmericanNumerals(numstr As double) As String Dim tempstr as string Dim newstr as string numstr = Cdbl(numstr) If numstr > 10 ^ 24 Then return ''Too big'' Exit Function End If If numstr >= 10 ^ 9 Then newstr = AmericanNumerals(Int(numstr / (10^9))) numstr = ((numstr / 10 ^ 9) - Int(numstr / 10 ^ 9)) * 10 ^ 9 If numstr = 0 Then tempstr = tempstr & newstr & ''Billion '' Else

31

Copyright http://vndownloads.net
tempstr = tempstr & newstr & ''Bullion, '' End If End If If numstr >= 10 ^ 6 Then newstr = AmericanNumerals(Int(numstr / 10 ^ 6)) numstr = ((numstr / 10 ^ 6) - Int(numstr / 10 ^ 6)) * 10 ^ 6 If numstr = 0 Then tempstr = tempstr & newstr & ''Million '' Else tempstr = tempstr & newstr & ''Million, '' End If End If If numstr >= 10 ^ 3 Then newstr = AmericanNumerals(Int(numstr / 10 ^ 3)) numstr = ((numstr / 10 ^ 3) - Int(numstr / 10 ^ 3)) * 10 ^ 3 If numstr = 0 Then tempstr = tempstr & newstr & ''Thousand '' Else tempstr = tempstr & newstr & ''Thousand, '' End If End If If numstr >= 10 ^ 2 Then newstr = AmericanNumerals(Int(numstr / 10 ^ 2)) numstr = ((numstr / 10 ^ 2) - Int(numstr / 10 ^ 2)) * 10 ^ 2 If numstr = 0 Then tempstr = tempstr & newstr & ''Hundred '' Else tempstr = tempstr & newstr & ''Hundred And '' End If End If If numstr >= 20 Then Select Case Int(numstr / 10) Case 2 tempstr = tempstr & ''Twenty '' Case 3 tempstr = tempstr & ''Thirty '' Case 4 tempstr = tempstr & ''Forty '' Case 5 tempstr = tempstr & ''Fifty '' Case 6 tempstr = tempstr & ''Sixty '' Case 7 tempstr = tempstr & ''Seventy '' Case 8 tempstr = tempstr & ''Eighty '' Case 9 tempstr = tempstr & ''Ninety '' End Select numstr = ((numstr / 10) - Int(numstr / 10)) * 10 End If

32

Copyright http://vndownloads.net
numstr=Int(numstr+0.5) If numstr > 0 Then Select Case NUMSTR MOD 100 Case 1 tempstr = tempstr & ''One '' Case 2 tempstr = tempstr & ''Two '' Case 3 tempstr = tempstr & ''Three '' Case 4 tempstr = tempstr & ''Four '' Case 5 tempstr = tempstr & ''Five '' Case 6 tempstr = tempstr & ''Six '' Case 7 tempstr = tempstr & ''Seven '' Case 8 tempstr = tempstr & ''Eight '' Case 9 tempstr = tempstr & ''Nine '' Case 10 tempstr = tempstr & ''Ten '' Case 11 tempstr = tempstr & ''Eleven '' Case 12 tempstr = tempstr & ''Twelve '' Case 13 tempstr = tempstr & ''Thirteen '' Case 14 tempstr = tempstr & ''Fourteen '' Case 15 tempstr = tempstr & ''Fifteen '' Case 16 tempstr = tempstr & ''Sixteen '' Case 17 tempstr = tempstr & ''Seventeen '' Case 18 tempstr = tempstr & ''Eighteen '' Case 19 tempstr = tempstr & ''Nineteen '' End Select numstr = ((numstr / 10) - Int(numstr / 10)) * 10 End If return tempstr End Function End Class

NumberToWord.vb ' <autogenerated> ' This class was generated by a tool. ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated.

33

Copyright http://vndownloads.net
' </autogenerated> '-----------------------------------------------------------------------------Imports System.Xml.Serialization Imports System.Web.Services.Protocols Imports System.Web.Services Public Class NumberToWord Inherits System.Web.Services.Protocols.SoapClientProtocol Public Sub New() MyBase.New Me.Url = ''numerals.asmx'' End Sub Public Function <System.Web.Services.Protocols.SoapMethodAttribute(''http://tempuri.org/Int'')> Int(ByVal num As Double) As Double Dim results() As Object = Me.Invoke(''Int'', New Object() {num}) Return CType(results(0),Double) End Function Public Function BeginInt(ByVal num As Double, ByVal callback As System.AsyncCallback, ByVal asyncState As Object) As System.IAsyncResult Return Me.BeginInvoke(''Int'', New Object() {num}, callback, asyncState) End Function Public Function EndInt(ByVal asyncResult As System.IAsyncResult) As Double Dim results() As Object = Me.EndInvoke(asyncResult) Return CType(results(0),Double) End Function Public Function <System.Web.Services.Protocols.SoapMethodAttribute(''http://tempuri.org/BritishNumerals'')> BritishNumerals(ByVal numstr As Double) As String Dim results() As Object = Me.Invoke(''BritishNumerals'', New Object() {numstr}) Return CType(results(0),String) End Function Public Function BeginBritishNumerals(ByVal numstr As Double, ByVal callback As System.AsyncCallback, ByVal asyncState As Object) As System.IAsyncResult Return Me.BeginInvoke(''BritishNumerals'', New Object() {numstr}, callback, asyncState) End Function Public Function EndBritishNumerals(ByVal asyncResult As System.IAsyncResult) As String Dim results() As Object = Me.EndInvoke(asyncResult) Return CType(results(0),String) End Function Public Function <System.Web.Services.Protocols.SoapMethodAttribute(''http://tempuri.org/AmericanNumerals'')> AmericanNumerals(ByVal numstr As Double) As String Dim results() As Object = Me.Invoke(''AmericanNumerals'', New Object() {numstr}) Return CType(results(0),String) End Function Public Function BeginAmericanNumerals(ByVal numstr As Double, ByVal callback As System.AsyncCallback, ByVal asyncState As Object) As System.IAsyncResult Return Me.BeginInvoke(''AmericanNumerals'', New Object() {numstr}, callback, asyncState) End Function Public Function EndAmericanNumerals(ByVal asyncResult As System.IAsyncResult) As String Dim results() As Object = Me.EndInvoke(asyncResult) Return CType(results(0),String) End Function

34

Copyright http://vndownloads.net

End Class

NumberToWord.aspx <html> <script language=''VB'' runat=''server''> Dim Op1 As Double = 0 Public Sub Submit_Click(Sender As Object, E As EventArgs) Try Op1 = Double.Parse(Operand1.Text) Catch Exp As Exception End Try Dim Service As NumberToWord = New NumberToWord() Select (CType(sender,Control).ID) Case ''English'' : Result.Text = ''<b>Result</b> = '' & Service.BritishNumerals(Op1).ToString() Case ''US'' : Result.Text = ''<b>Result</b> = '' & Service.AmericanNumerals(Op1).ToString() End Select End Sub </script> <body style=''font: 10pt verdana''> <h4>Using a Simple Number Service </h4> <form runat=''server''> <div style=''padding:15,15,15,15;background-color:beige;width:300;border-color:black;borderwidth:1;border-style:solid''> Enter any number: <br><asp:TextBox id=''Operand1'' Text=''15'' runat=''server''/><br> <input type=''submit'' id=''English'' value=''Show English Numeral Text'' OnServerClick=''Submit_Click'' runat=''server''> <input type=''submit'' id=''US'' value=''Show Americal Numeral Text'' OnServerClick=''Submit_Click'' runat=''server''> <p> <asp:Label id=''Result'' runat=''server''/> </div> </form> </body> </hNhn thng tin ca tp tin t ASP.NET Trong ASP Chun chng ta vn c th thc hin vic ny thng qua i tng Scripting.FileSystemObjec. Trong .NET chng ta thay th bng System.IO namespace. fileinfo.aspx (C#) <%@ Page Language=''c#'' %> <script runat=''server''> protected System.IO.FileInfo objFI; protected String filename; protected void Page_Load(){ if(!IsPostBack){ // Ly tn ng dn ca tp tin filename = Request.ServerVariables[''PATH_TRANSLATED'']; // To FileInfo object mi cho tp tin ny

35

Copyright http://vndownloads.net
objFI = new System.IO.FileInfo(filename); // Cc trng thng tin cn thit fullname.Text = objFI.FullName; name.Text = objFI.Name; size.Text = objFI.Length.ToString(); created.Text = objFI.CreationTime.ToString(); accessed.Text = objFI.LastAccessTime.ToString(); modified.Text = objFI.LastWriteTime.ToString(); directory.Text = objFI.DirectoryName; extension.Text = objFI.Extension; } } </script> <HTML> <HEAD> </head> </HEAD> <BODY> <form runat=''server''> <b>File Information</b> <table class=''articlelist''> <tr> <td class=''header''>Full Name</td> <td> <asp:Label id=''fullname'' runat=''server''/> </td> </tr> <tr> <td class=''header''>Name</td> <td> <asp:Label id=''name'' runat=''server''/> </td> </tr> <tr> <td class=''header''>Extension</td> <td> <asp:Label id=''extension'' runat=''server''/> </td> </tr> <tr> <td class=''header''>Size</td> <td> <asp:Label id=''size'' runat=''server''/> </td> </tr> <tr> <td class=''header''>Created</td> <td> <asp:Label id=''created'' runat=''server''/> </td> </tr> <tr> <td class=''header''>Modified</td> <td> <asp:Label id=''modified'' runat=''server''/>

36

Copyright http://vndownloads.net
</td> </tr> <tr> <td class=''header''>Accessed</td> <td> <asp:Label id=''accessed'' runat=''server''/> </td> </tr> <tr> <td class=''header''>Parent Folder</td> <td> <asp:Label id=''directory'' runat=''server''/> </td> </tr> </table> </form> </BODY> </HTML>

tml>

c v ghi vo Cookies trong ASP.Net


Cookie l mt khi nim kh quen thuc trong trong lp trnh Web, tuy nhin khi .NET ra i rt nhiu ngi khng hiu cch s dnh chng c g thay i v cc thc lm vic c cn nh xa? C rt nhiu cch nh danh trong ASP.NET nh web.config v global.asax, nhng cn v cookie ? y l mt cookie vi mt gi tr: Response.Cookies(''MakCookie'').Value = ''Welcome to VASC''

y l mt cookie vi mt cp tn:

Response.Cookies(''Makovision'')(''Username'') = ''VASC'' Response.Cookies(''Makovision'')(''Option'') = ''Restricted''

Tht n gin chng ta vit cookie thnh cng. By gi chng ta s c gi tr trong ASP.NET

37

Copyright http://vndownloads.net

Response.Cookies(''Makovision'')(''Username'') = ''VASC'' Response.Cookies(''Makovision'')(''Option'') = ''Restricted'' Dim strValue as String for each strValue in Response.Cookies(''Makovision'').values MakCookie.Text +=''<b>'' & strValue & ''</b>: '' & Request.Cookies(''Makovision'')(strValue) & ''<BR>'' next

trong Body

<form runat=''server''> <asp:label id=''MakCookie'' runat=''server'' /> </form>

c Pop3 E-mail bng ASP.NET


Vi sc mnh ca .NET bn c th lm c nhiu vic trc kia vi ASP chun bn rt kh thc hin v i lc khng th thc hin c. i-Today hm nay s hng dn cc bn cch c Pop3 Email bng ASP.NET pop3.aspx <%@page%> <HTML><HEAD><title>Pop3 mail check</title></HEAD> <body bgcolor=white>

<%

if isPostback then readMail(host.text,user.text,pass.text) else %> <form id=calc method=post runat=''server''>

38

Copyright http://vndownloads.net
<P> Host <asp:TextBox id=host runat=''server''></asp:TextBox> <P> User <asp:TextBox id=user runat=''server''></asp:TextBox> <P> Pass <asp:TextBox TextMode=Password id=pass runat=''server''></asp:TextBox> <P> <asp:Button id=Button1 runat=''server'' Text=''Login''></asp:Button> </FORM>

<%

end if

%>

</body></HTML>

<script language=''vb'' runat=''server''> dim tcpC as New system.net.sockets.TcpClient() Function SendCommand(byRef netstream as System.Net.Sockets.NetworkStream,byVal sToSend as String)

dim bData() as Byte = Encoding.ASCII.GetBytes(sToSend.ToCharArray) netstream.Write(bData,0,bData.Length()) Return GetResponse(netstream) End Function Function GetResponse(byRef netstream as System.Net.Sockets.NetworkStream)

dim bytes(tcpC.ReceiveBufferSize) As Byte dim ret as integer = netStream.Read(bytes, 0, bytes.length) dim returndata As String = Encoding.ASCII.GetString(bytes) return returndata End Function

39

Copyright http://vndownloads.net

Function ReadMail(host as string, user as string, pass as string) dim netstream as System.Net.Sockets.NetworkStream dim thisResponse as string try tcpC.Connect(host,110) catch ex as exception response.write(''Error connecting to host: '' & ex.message & '' - Please check your details and try again'') response.end end try netstream = tcpC.GetStream() thisResponse=GetResponse(netstream) thisResponse=SendCommand(netstream,''user '' & user & vbCrLF) thisResponse=SendCommand(netstream,''pass '' & pass & vbCrLf) if not left(thisResponse,4)=''-ERR'' then response.write(''<font face=courier>Logged in OK <BR>'') else response.write(''Error logging in, check your user details and try again<BR>'') response.write(''<P>'' & thisresponse) response.end end if thisResponse=SendCommand(netstream,''stat'' & vbCrLf)

dim tmpArray() as string tmpArray = split(thisResponse,'' '')

dim thisMess as integer dim numMess as string = tmpArray(1) response.write(''<p><hr>'') thisResponse = '''' if cint(numMess) > 0 then response.write(''Messages: '' & numMess & ''<br>'') for thisMess = 1 to cint(numMess) thisResponse += replace(SendCommand(netstream,''top '' & thisMess & '' 10'' & vbCrLf),vbcrlf,''<br>'')

40

Copyright http://vndownloads.net
next else response.write(''Messages: None'' & ''<br>'') end if thisResponse += replace(SendCommand(netstream,''stat'' & vbCrLf),vbcrlf,''<br>'')

tmpArray = split(thisResponse,''+OK'') response.write(thisresponse)

dim msg as integer for msg = 1 to tmpArray.length-1

response.write(''<h3>#'' & msg & ''</h1>'' & tmpArray(msg) & ''<p>'')

next thisResponse=SendCommand(netstream,''QUIT'' & vbCrLF) tcpC.close End Function

</script>

K thut lm m hnh (blur) vi GDI + System.Drawing (.NET)


y l mt k thut c thc hin ht sc d dng trn Web, bng sc mnh ca .NET. Chng ta s dng mt thut ton ht sc n gin, gi tr ca mi pixel bng gi tr trung bnh ca cc pixel trn, tri, phi ca n. blur.aspx <%@ Page Language=''vb'' %> <%@ import namespace=''system.drawing'' %> <%@ import namespace=''system.drawing.imaging'' %> <%@ import namespace=''system.drawing.drawing2d'' %> <% dim b as New system.drawing.bitmap(server.mappath(''example1.jpg''))

dim x,y,cnt dim addR, addB, addG as integer

41

Copyright http://vndownloads.net
dim incAmount = Request.QueryString(''increase'') addR = 0 addG = 0 addB = 0

for y = 3 to b.height-3 for x = 3 to b.width-3 addR = b.GetPixel(x,y-1).r addR += b.GetPixel(x,y+1).r addR += b.GetPixel(x,y).r addR += b.GetPixel(x+1,y).r addR += b.GetPixel(x-1,y).r addR = addR / 5 addG = b.GetPixel(x,y-1).g addG += b.GetPixel(x,y+1).g addG += b.GetPixel(x,y).g addG += b.GetPixel(x+1,y).g addG += b.GetPixel(x-1,y).g addG = addG / 5 addB = b.GetPixel(x,y-1).b addB += b.GetPixel(x,y+1).b addB += b.GetPixel(x,y).b addB += b.GetPixel(x+1,y).b addB += b.GetPixel(x-1,y).b addB = addB / 5 b.SetPixel(x,y,color.fromARGB(addR,addG,addB)) addR = 0 addG = 0 addB = 0 next next

response.contenttype=''image/jpeg'' b.save(response.outputstream, imageformat.jpeg)

42

Copyright http://vndownloads.net
b.dispose()

%>

Mo lin quan n vic chuyn d liu quan h sang XML (.NET)


The DataSet Class Vi s gii thiu ca ADO.NET v lp DataSet, l cng c tuyt vi xem d liu c dng quan h ln XML. C nhiu phng thc trong lp DataSet n GetXml() hoc WriteXml(). Mc d GetXml() ch n gin tr li mt chui th hin cho d liu XML, bn c th s dng WriteXml() ghi XML n cc i tng khc nhau: Streams TextWriters XmlWriters Files

Nu d liu quan h cn c chuyn v cu trc DOM, trong thc t vic chuyn d liu quan h v cu trc DOM n gin nh truyn DataSet trong XmlDataDocument's constructor: XmlDataDocument doc = new XmlDataDocument(myDataSet); SQL Server 2000 SQL Server 2000 cung cp nhiu k thut chuyn d liu quan h sang XML. Khi bn s dng chung vi .NET platform, bn c th s dng nhiu tnh nng mnh ca c hai. u tin bn c th kt ni n d liu ca SQL 2000 thng qua HTTP hn ADO.NET. Thng qua s dng URL, bn c th np d liu trc tip vo XmlDocument hoc XmlTextReader. Vec ny hon ton c kh nng bng cc hm c bit c tch hp vo SQL Server 2000. V d, cu SQL ny s chuyn d liu sang XML mt cch t ng SELECT * FROM Customers FOR XML AUTO Nu bn cn xc nh thnh phn ca XML mt cch ring bit, thm kho ELEMENTS: SELECT * FROM Customers FOR XML AUTO, ELEMENTS Nu bn c nh cu s dng ADO.NET Connection Class kt ni n CSDL nh thng qua HTTP, bn c th s dng phng thc ExecuteXmlReader() ca lp Command. Vicny cho php d liu XML c np trc tip vo lp XmlTextReader. SQLXML Managed Classes Cc lp XML mi ca .NET dng cho SQL Server 2000 cso th s dng khi bn ci t SQL Server 2000 Web Release. Web Release bao gm Microsoft.Data.SqlXml namespace (bao gm cc lp SqlXmlCommand, SqlXmlParameter, v SqlXmlAdapter) cho php bn s dng kt ni n CSDL v xem XML c xut. V d: SqlXmlCommand cmd = new SqlXmlCommand(connString); cmd.CommandText = ''Customer''; cmd.CommandType = SqlXmlCommandType.XPath;

43

Copyright http://vndownloads.net
cmd.RootTag = ''Customers''; cmd.SchemaPath = ''customersSchema.xml''; DataSet ds = new DataSet(); SqlXmlAdapter adapter = new SqlXmlAdapter(cmd); adapter.Fill(ds);

Gi mt .NET Component t mt COM Component


Trong hm nay i-Today s to mt d n demo lm r cc gi .NET Component t COM client. Bc 1: To mt Strong Namecho .NET Component (Strong name l mt tn khng trng c to bi hashing mt kho 128 bit v tn ca Assembly (chng ta t tn l COMInterOp)). to Strong name bn dng tool sn. to mt tp tin kho tn l COMInterOp.snk, bn thc hin dng lnh: sn -k COMInterOp.snk Bc 2: By gi chng ta s to mt .NET Assembly ch bao ggm mt class CEmp vi cc thuc tnh (FirstName, LastName, DOB) v pht sinh cc s kin. Sau y l dng lnh to mt assembly s dng strong name vbc /out:COMInterOp.dll /t:library /keyfile:COMInterOp.snk CEmp.vb VB.NET CEmp class code Imports System Imports Microsoft.VisualBasic Imports System.Runtime.InteropServices <InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)> _ Public Interface evtSenior Sub Senior() End Interface <ComSourceInterfacesAttribute(''evtSenior'')> _ Public Class CEmp Private mstrFirstName As String Private mstrLastName As String Private mdtDOB As Date Public Event Senior() Public Property FirstName() As String Get FirstName = mstrFirstName End Get Set(ByVal Value As String) mstrFirstName = Value End Set End Property Public Property LastName() As String

44

Copyright http://vndownloads.net

Get LastName = mstrLastName End Get Set(ByVal Value As String) mstrLastName = Value End Set End Property Public Property DOB() As Date Get DOB = mdtDOB End Get Set(ByVal Value As Date) mdtDOB = Value If DateDiff(DateInterval.Year, Value, Now) > 60 Then RaiseEvent Senior() End If End Set End Property End Class Bc 3: Mt khi assembly c to chng ta to mt Type libry COM Client c th s dng Assembly. Chng ta theo cc option sau cho COM: Type Library Exporter S dng Type Library Exporter (Tlbexp.exe) cc lp v giao din (interface) c cha trong mt assembly c chuyn thnh dng mt COM Lib. Mt khi TypeLib c to, COM client c th to mt instance ca cc lp .NET v gi cc phng thc nh chng l mt i tng COM. TypeLibConverter Class TypeLibConverter Class ca System.Runtime.InteropServices namespace cung cp cc phng thc chuyn mt assembly thnh mt TypeLib. Assembly Registration Tool Assembly Registration Tool (Regasm.exe), c metadata trong mt assembly v thm cc mc cn thit vo registry. Assembly Registration tool c th generate v ng k mt loi th vin khi bn s dng /tlb: option. COM clients yu cu cc loi th vin khi ci t vo trong Windows registry. Nu khng s dng option ny, Regasm.exe ch ng knh l mt assembly, khng nh type library. The .NET Services Installation Tool (Regsvcs.exe) (xem thm MSDN )

Trong v d ca chng ta s s dng RegAsm.exe to TypeLib t cc class v Interface c nh ngha trong COMInterOp.dll. regasm ComInterOp.dll /tlb:ComInterOp.tlb Bc 4: By gi .NET component (COMInterOp.dll) nn c ci vo GAC (global assembly cache) lm vic vi COM Code dir>Gacutil -i COMInterOp.dll Bc 5: S dng

45

Copyright http://vndownloads.net

COM Component 'Class Emps Option Explicit Private Emps As Scripting.Dictionary Private Sub Class_Initialize() Set Emps = New Scripting.Dictionary Dim objEmp As CEmp Set objEmp = New CEmp objEmp.InitMe ''John'', ''Doe'', ''01/01/1970'' Emps.Add 0, objEmp Set objEmp = New CEmp objEmp.InitMe ''Mike'', ''Edwards'', ''01/01/1941'' Emps.Add 1, objEmp Set objEmp = New CEmp objEmp.InitMe ''Debra'', ''Bunn'', ''01/01/1930'' Emps.Add 2, objEmp End Sub Public Function PrintEmps() As String PrintEmps = PrintBool(True) & PrintBool(False) End Function Public Function PrintBool(ByVal xblnSeniors As Boolean) As String Dim intCount As Integer Dim objEmp As CEmp Dim strPrint As String For intCount = 0 To Emps.Count - 1 Set objEmp = Emps(intCount) If xblnSeniors = objEmp.IsSenior Then strPrint = strPrint & PrintEmp(objEmp) & Chr(13) End If Next intCount PrintBool = strPrint End Function Private Function PrintEmp(ByVal xobjEmp As CEmp) As String Dim strPrint As String strPrint = xobjEmp.FirstName & Chr(9) & xobjEmp.LastName PrintEmp = strPrint End Function 'End Class Emps 'Class Emp Option Explicit Private mblnIsSenior As Boolean Private WithEvents mobjEmp As ComInterOp.CEmp Public Sub InitMe(ByVal xstrFName As String, _ ByVal xstrLName As String, ByVal xdtDOB As Date) Set mobjEmp = New ComInterOp.CEmp

46

Copyright http://vndownloads.net

With mobjEmp .FirstName = xstrFName .LastName = xstrLName .DOB = xdtDOB End With End Sub Public Property Get FirstName() As String FirstName = mobjEmp.FirstName End Property Public Property Get LastName() As String LastName = mobjEmp.LastName End Property Public Property Get IsSenior() As Boolean IsSenior = mblnIsSenior End Property Private Sub mobjEmp_Senior() mblnIsSenior = True End Sub 'End Class Emp

Xut(Generate) ng (Dynamically ) tp tin PDF s dng ASP.NET


Hin nay c rt nhiu cch xut ng cc tp tin PDF. Cch ph bin c bit l s dng ASP vi Acrobat Full Vesion (4.0 hoc 5.0) v Acrobat FDF Toolkit. Vi Microsoft.NET rt nhiu lp trnh vin ang lng tng thc hin cng vic ny. i-Today xin hng dn cc bn cch lm. Cc cng c

1. Adobe Acrobat 5.0 Full Version, khng phi Acrobat Reader 5.0 2. Acrobat FDF Toolkit Version 5, free downloaded 3. Microsoft .NET Framework SDK with Service Pack 1
Platform Windows 2000 Server (Service Pack 2), Internet Information Server 5.0 Ci t

1. Ci t Adobe Acrobat 5.0 Full Version. 2. Go to http://partners.adobe.com/asn/developer/acrosdk/forms.html download the Acrobat FDF
Toolkit package.

3. Ci t theo hng dn http://partners.adobe.com/asn/developer/acrosdk/docs/fdftk/FDFtkRef.pdf.


Gin nn Acrobat FDF Toolkit package, tm files: FdfAcX.dll v FdfTk.dll. Chp vo th mc \WINNT\system32 , v ng k Regsvr32 FdfAcX.dll. 4. To .NET compatible wrapper cho FdfAcX.dll dng TlbImp.exe(Type Library Importer). Trong ca s Command Window, nh: tlbimp FdfAcX.dll /out:FdfAcX_NET.dll 5. t FdfAcx_NET.dll c generated CLR assembley vo th mc bin ca chng trnh ca bn. Nn nh

47

Copyright http://vndownloads.net
cc tp tin c gen bi Tlbimp.exe cn t trong th mc chng trnh\bin ca ASP.NET. Trong ASP, dng VBScript Set FdfAcX = Server.CreateObject(FdfApp.FdfApp) FdfAcX.FDFSetFile http://www.yourserver.com/test.pdf FdfAcX.FDFSetValue txtMemo, This is a test, false FdfAcX.FDFSaveToFile C:\temp\test.fdf FdfAcX.FDFClose Set FdfAcX = nothing ASP.NET

<%@ Import Namespace=FdfAcX_NET %> FdfAppClass FdfAcX_App = new FdfAppClass(); FdfDoc FdfAcX_Doc = (FdfDoc)FdfAcX_App.FDFCreate(); FdfAcX_Doc.FDFSetFile(http://www.yourserver.com/test.pdf); FdfAcX_Doc.FDFSetValue(txtMemo, This is a test, false); FdfAcX_Doc.FDFSaveToFile(@c:\temp\test.fdf); FdfAcX_Doc.FDFClose();

VB.NET: Dim FdfAcX_App As FdfAppClass FdfAcX_App = new FdfAppClass() Dim FdfAcX_Doc As FdfDoc FdfAcX_Doc = FdfAcX_App.FDFCreate FdfAcX_Doc.FDFSetFile(http://www.yourserver.com/test.pdf) FdfAcX_Doc.FDFSetValue(txtMemo, This is a test , false) FdfAcX_Doc.FDFSaveToFile(c:\temp\test.fdf) FdfAcX_Doc.FDFClose

Truyn file c gen n ngi s dng

<script language=C# runat=server> protected void Page_Load(Object Src, EventArgs E) { if (!IsPostBack) { Response.ContentType=Application/vnd.fdf; Response.WriteFile(@c:\temp\test.fdf); Response.End(); } }

To mt Pop-up Canlendar (ASP.NET, VB.NET)


Bn s dng Calender Control v Panel Control. Panel Control c s dng to hiu ng float trn trang. Bng cch t calendar control trong Panel Control, bn c th th d dng xc nh v tr v thi im hin th Panel Control.

48

Copyright http://vndownloads.net
To User Class iu u tin cn lm l to mt tp tin class c cha Panel v Calendar Server control. [popUpCalendar.ascx] <%@ Control Language=''vb'' AutoEventWireup=''false'' Codebehind=''popUpCalendar.ascx.vb'' Inherits=''CalendarExample.popUpCalendar'' %> <asp:panel id=''pnlCalendar'' style=''Z-INDEX: 101; LEFT: 0px; POSITION: absolute; TOP: 0px'' runat=''server'' Height=''86px'' Width=''145px''> <asp:Calendar id=''Calendar1'' runat=''server'' Height=''86'' Width=''145'' BackColor=''White'' BorderColor=''Black'' BorderStyle=''Solid'' NextMonthText=''<IMG src='monthright.gif' border='0'>'' PrevMonthText=''<IMG src='monthleft.gif' border='0'>''> <TodayDayStyle BackColor=''#FFFFC0''></TodayDayStyle> <DayStyle Font-Size=''8pt'' Font-Names=''Arial''></DayStyle> <DayHeaderStyle Font-Size=''10pt'' Font-Underline=''True'' Font-Names=''Arial'' BorderStyle=''None'' BackColor=''#E0E0E0''></DayHeaderStyle> <SelectedDayStyle Font-Size=''8pt'' Font-Names=''Arial'' Font-Bold=''True'' ForeColor=''White'' BackColor=''Navy''></SelectedDayStyle> <TitleStyle Font-Size=''10pt'' Font-Names=''Arial'' Font-Bold=''True'' ForeColor=''White'' BackColor=''Navy''></TitleStyle> <OtherMonthDayStyle ForeColor=''Gray''></OtherMonthDayStyle> </asp:Calendar> </asp:panel> Sau l to code phc v vic hin th [popUpCalendar.ascx.vb] Public Class popUpCalendar : Inherits System.Web.UI.UserControl Protected WithEvents Calendar1 As System.Web.UI.WebControls.Calendar Protected WithEvents pnlCalendar As System.Web.UI.WebControls.Panel #Region '' Web Form Designer Generated Code '' 'This call is required by the Web Form Designer. <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent() End Sub Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init InitializeComponent() End Sub #End Region Public Sub displayCalendar(ByVal sCalToolText As String, _ ByVal dSelectedDate As Date, _ ByVal sDateFieldName As String, _ ByVal iTop As Integer, _

49

Copyright http://vndownloads.net
ByVal iLeft As Integer) '************************************************************************ 'Hin th v du calendar '************************************** ********************************** If pnlCalendar.Visible = True And Calendar1.Attributes.Item(''selectedfield'') <> sDateFieldName Then hideCalendar() End If If pnlCalendar.Visible = False Then pnlCalendar.Style.Item(''top'') = iTop pnlCalendar.Style.Item(''left'') = iLeft If IsDate(dSelectedDate) Then Calendar1.SelectedDate = dSelectedDate Calendar1.VisibleDate = dSelectedDate Else Calendar1.SelectedDate = #12:00:00 AM# Calendar1.VisibleDate = Now End If Calendar1.ToolTip = sCalToolText Calendar1.Attributes.Item(''SelectedField'') = sDateFieldName pnlCalendar.Visible = True Else hideCalendar() End If End Sub Public Sub Calendar1_SelectionChanged(ByVal sender As System.Object, ByVa e As l System.EventArgs) Handles Calendar1.SelectionChanged Dim txtDate As TextBox txtDate = Page.FindControl(Calendar1.Attributes.Item(''SelectedField'')) txtDate.Text = Calendar1.SelectedDate hideCalendar() End Sub Public Sub hideCalendar() pnlCalendar.Visible = False End Sub End Class

Sau y l v d v cch s dng User Control trn [dispCalendar.aspx] <%@ Register TagPrefix=''sk'' TagName=''popUpCalendar'' src=''popUpCalendar.ascx''%> <%@ Page Language=''vb'' AutoEventWireup=''false'' Codebehind=''dispCalendar.aspx.vb'' Inherits=''CalendarExample.dispCalendar'' %> <!DOCTYPE HTML PUBLIC ''-//W3C//DTD HTML 4.0 Transitional//EN''> <HTML> <HEAD> <title>dispCalendar</title> <meta name=''GENERATOR'' content=''Microsoft Visual Studio.NET 7.0''> <meta name=''CODE_LANGUAGE'' content=''Visual Basic 7.0''>

50

Copyright http://vndownloads.net
<meta name=''vs_defaultClientScript'' content=''JavaScript''> <meta name=''vs_targetSchema'' content=''http://schemas.microsoft.com/intellisense/ie5''> </HEAD> <body MS_POSITIONING=''GridLayout''> <form id=''Form1'' method=''post'' runat=''server''> <sk:popUpCalendar id=''myCalendar'' runat=''server'' /> <H3>Example Use of Custom Calendar Control</H3> <table> <tr> <td width=''75''> Start Date: </td> <td> <asp:TextBox id=''txtStartDate'' runat=''server'' Width=''86px''></asp:TextBox> </td> <td> <asp:ImageButton id=''btnStartDate'' runat=''server'' ImageUrl=''calendar.gif''></asp:ImageButton> </td> </tr> <tr> <td width=''75''> End Date: </td> <td> <asp:TextBox id=''txtEndDate'' runat=''server'' Width=''86px''></asp:TextBox> </td> <td> <asp:ImageButton id=''btnEndDate'' runat=''server'' ImageUrl=''calendar.gif''></asp:ImageButton> </td> </tr> </table> </form> </body> </HTML> [dispCalendar.aspx.vb] Public Class dispCalendar Inherits System.Web.UI.Page Protected WithEvents txtStartDate As System.Web.UI.WebControls.TextBox Protected WithEvents btnEndDate As System.Web.UI.WebControls.ImageButton Protected WithEvents btnStartDate As System.Web.UI.WebControls.ImageButton Protected WithEvents txtEndDate As System.Web.UI.WebControls.TextBox Protected WithEvents myCalendar As popUpCalendar #Region '' Web Form Designer Generated Code '' 'This call is required by the Web Form Designer. <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent() End Sub Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles

51

Copyright http://vndownloads.net
MyBase.Init 'CODEGEN: This method call is required by the Web Form Designer 'Do not modify it using the code editor. InitializeComponent() End Sub #End Region Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load If Not IsPostBack Then 'Hide the calendar on initial page load myCalendar.hideCalendar() End If End Sub Private Sub btnStartDate_Click(ByVal sender As System.Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnStartDate.Click Dim dSelDate As Date If IsDate(txtStartDate.Text) Then dSelDate = txtStartDate.Text End If myCalendar.displayCalendar(''Select a start date'', dSelDate, ''txtStartDate'', 59, 220) End Sub Private Sub btnEndDate_Click(ByVal sender As System.Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnEndDate.Click Dim dSelDate As Date If IsDate(txtEndDate.Text) Then dSelDate = txtEndDate.Text End If myCalendar.displayCalendar(''Select an end date'', dSelDate, ''txtEndDate'', 86, 220) End Sub End Class

i a ch IP ca my Local s dng VB.NET v C#


Tt c cc thng tin setting thng s mng u c lu trong Registry v thay i khng c g d hn l chng ta thay i cc thng tin trong Registry. Bc 1: M HKEY_LOCAL_MACHINE v m kho SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkCards\1. 1l card mng u tin. Nu bn nhiu card trn my chng s hin th bng cc con s. Trong kho ny c gi tr gi lm chng ta cn lu bc tip theo. By gi bn ng kho ny li. Bc 2: M li HKEY_LOCAL_MACHINE v m kho SYSTEM\CurrentControlSet\Services\#SERVICENAME#\Parameters\Tcpip. V chc bn m kho ny vi quyn Write.

52

Copyright http://vndownloads.net
Bc 3: By gi cc bn c th thay i a ch IP, DefaultGateway...cc gi tr u lu di gi tr nh phn v vy bn phi chuyn thnh nh phn trc khi lu vo Registry. (Dng hm GetBytes) Now you can change the IP address for the IPAddress, DefaultGateway keys etc. The value type of these keys is binary so you must make sure that you do not write a string to the registry or it will change its value type. Instead, use the GetBytes() method of the Encoding class to write the bytes. Imports System Imports System.Text Imports Microsoft.Win32 Module ChangeIP Sub Main() Dim regKey As RegistryKey Dim strServiceName As String regKey = Registry.LocalMachine.OpenSubKey(SOFTWARE\Microsoft\WindowsNT\CurrentVersion\NetworkCards\1 ) strServiceName = regKey.GetValue(ServiceName) regKey.Close() regKey = Registry.LocalMachine.OpenSubKey(SYSTEM\CurrentControlSet\Services\ & strServiceName & \Parameters\Tcpip, True) regKey.SetValue(IPAddress, Encoding.ASCII.GetBytes(10.1.1.1\0\0)) regKey.Close() End Sub End Module Sau y l nhng lu khi thc hin k thut ny: 1. Bn phi c quyn c v vit vo Registry. Nu trong trng hp bn cn xc nhn quyn thc thi th s dng lp RegistryPermission. 2. Nu bn khng s dng Windows NT/2000 th i 'Windows NT' thnh 'Windows' trong bc 1 3. Nu bn ang dng DHCPth bn lu rng IPAddress s l 0.0.0.0 v bn s cn thay i gi tr ca EnableDHCP thnh 0 4. Khi bn xc nh mt a ch IP ghi vo Registry, nh thm 2 gi tr null vo cui ca chng 5. Cn boot li my trc khi c tc dng.

S dng SQL Server Images trong cc trang ASP.NET (C#,ASP.NET)


Thng khi chng ta hin th cc hnh ng trong trang ASP.NET ch s dng tag <img>. Cn cc hnh nh c lu trong cc trng blod ca SQL Server? Chng ti hng dn cc bn cch hin th cc hnh trong ASP. Nay chng ti s hng dn cc bn s dng ASP.NET. <img src=<%# ''image.aspx?id='' + DataBinder.Eval (Container.DataItem, ''employeeid'') %> /> Tp tin image.aspx s to v output mt graphic stream da vo cc kho chnh c truyn bi id. Trong .NET, bn c th nhn trng blod qua byte [] img = (byte[]) command.ExecuteScalar(); Khi bn c cc bits, bn c th gi chng n nh mt graphic object. Nhng u tin phi set Response.ContentType = ''image/gif''; MemoryStream ms = new MemoryStream(); ms.Write(img, 0, img.Length); Bitmap bmp = null; bmp = new Bitmap(ms);

53

Copyright http://vndownloads.net
n thi im ny, bn hu nh lm xong. Bn cn chuyn sang dng format dng hnh nh mong mun bmp.Save(Response.OutputStream,ImageFormat.Gif); Ton b tp tin image.aspx (s dng database Northwind th nghim) <%@ Page Language=''C#'' %> <%@ Import Namespace=''System'' %> <%@ Import Namespace= ''System.Data.SqlClient'' %> <%@ Import Namespace=''System.IO'' %> <%@ Import Namespace=''System.Drawing.Imaging'' %> <%@ Import Namespace=''System.Drawing'' %> <html> <script runat=''server''> private void Page_Load(object sender, System.EventArgs e) { SqlConnection cn; cn = new SqlConnection(''DATABASE=northwind;SERVER =localhost;UID=sa;''); String cmdText = ''SELECT photo FROM Employees WHERE employeeid='' + Request[''id''].ToString(); SqlCommand cmd = new SqlCommand(cmdText, cn); MemoryStream ms = new MemoryStream(); int offset = 78; cn.Open(); byte [] img = (byte[]) cmd.ExecuteScalar(); ms.Write(img, offset, img.Length-offset); cn.Close(); Bitmap bmp = null; bmp = new Bitmap(ms); Response.ContentType = ''image/gif''; bmp.Save(Response.OutputStream, ImageFormat.Gif); ms.Close(); } </script> </html>

Ghi vo Event Log (ASP.NET)


Chng ti gii thiu cho cc bn cch c t Event Log. Hm nay chng ti xin hng dn cc bn cch ghi vo Event Log. Chng ta s to mt trang qun l cc li khi trang ASP.NET sinh li <%@ Import Namespace=''System.Data'' %> <%@ Import Namespace=''System.Data.SQL'' %> <%@ Import Namespace=''System.Diagnostics'' %> <script language=''c#'' runat=''server''> void Page_Load(Object source, EventArgs e) { try { SQLConnection objConn; objConn = new SQLConnection(''server=localhost;uid=foo;pwd=bar;database=pubs''); objConn.Open(); }

54

Copyright http://vndownloads.net
catch (Exception eError) { RecordError(eError, EventLogEntryType.Error); } } void RecordError(Exception eError, EventLogEntryType enumType) { const String strSource = ''ASP.NET'', strLogName = ''System''; EventLog objLog = new EventLog(strLogName); objLog.Source = strSource; objLog.WriteEntry(eError.Message, enumType); } </script> on code s ghi vo Event Log khi khng kt ni vo SQL Server (d nhin l khng c v chng ta ang th bo li)

c t Event Log (ASP.NET)


.NET Framework c mt s lp dng c v vit vo event log. Tt c c lu trong System.Diagnostics namespace. Sau y chng ti xin trnh by mt on code ASP.NET n gin hin th cc mc li trong event log trong c lu gi trong System Log. <%@ Import Namespace=''System.Diagnostics'' %> <%@ Import Namespace=''System.Drawing'' %> <script language=''VB'' runat=''server''> Sub Page_Load(source as Object, e as EventArgs) If Not Page.IsPostBack Then DisplayEventLog(''System'') End If End Sub Sub btnSubmit_OnClick(source as Object, e as EventArgs) DisplayEventLog(lstLog.SelectedItem.Value) End Sub Sub btnClear_OnClick(source as Object, e as EventArgs) Dim objEventLog as New EventLog(lstLog.SelectedItem.Value) objEventLog.Clear() End Sub Sub DisplayEventLog(strLogName as String) Dim objRow as New TableRow Dim objCell as New TableCell objCell.BackColor = Color.Bisque objCell.HorizontalAlign = HorizontalAlign.Center objCell.Text = ''Type'' objRow.Cells.Add(objCell) objCell = New TableCell objCell.BackColor = Color.Bisque

55

Copyright http://vndownloads.net
objCell.HorizontalAlign = HorizontalAlign.Center objCell.Text = ''Date'' objCell = New TableCell objCell.BackColor = Color.Bisque objCell.HorizontalAlign = HorizontalAlign.Center objCell.Text = ''Time'' objRow.Cells.Add(objCell) objCell = New TableCell objCell.BackColor = Color.Bisque objCell.HorizontalAlign = HorizontalAlign.Center objCell.Text = ''Source'' objRow.Cells.Add(objCell) objCell = New TableCell objCell.BackColor = Color.Bisque objCell.HorizontalAlign = HorizontalAlign.Center objCell.Text = ''User'' objRow.Cells.Add(objCell) objCell = New TableCell objCell.BackColor = Color.Bisque objCell.HorizontalAlign = HorizontalAlign.Center objCell.Text = ''Computer'' objRow.Cells.Add(objCell) tblLog.Rows.Add(objRow) Dim objEventLog as EventLog = New EventLog(strLogName) Dim objEntry as EventLogEntry For Each objEntry in objEventLog.Entries objRow = New TableRow objCell = New TableCell If objEntry.EntryType = EventLogEntryType.Error Then objCell.BackColor = Color.Red objCell.ForeColor = Color.White objCell.Text = ''Error'' ElseIf objEntry.EntryType = EventLogEntryType.Information Then objCell.Text = ''Information'' ElseIf objEntry.EntryType = EventLogEntryType.Warning Then objCell.BackColor = Color.Yellow objCell.Text = ''Warning'' ElseIf objEntry.EntryType = EventLogEntryType.SuccessAudit Then objCell.Text = ''Success Audit'' ElseIf objEntry.EntryType = EventLogEntryType.FailureAudit Then objCell.ForeColor = Color.Red objCell.Text = ''Failure Audit'' End If objCell.HorizontalAlign = HorizontalAlign.Center objRow.Cells.Add(objCell) objCell = New TableCell objCell.Text = objEntry.TimeGenerated.ToShortDateString() objRow.Cells.Add(objCell) objCell = New TableCell objCell.Text = objEntry.TimeGenerated.ToLongTimeString() objRow.Cells.Add(objCell) objCell = New TableCell objCell.Text = objEntry.Source

56

Copyright http://vndownloads.net
objRow.Cells.Add(objCell) objCell = New TableCell If objEntry.UserName <> Nothing then objCell.Text = objEntry.UserName Else objCell.Text = ''N/A'' End If objRow.Cells.Add(objCell) objCell = New TableCell objCell.Text = objEntry.MachineName objRow.Cells.Add(objCell) tblLog.Rows.Add(objRow) Next End Sub </script> <html> <body> <form runat=''server''> <h1>Event Log Viewer</h1> <asp:listbox runat=''server'' id=''lstLog'' Rows=''1''> <asp:listitem>Application</asp:listitem> <asp:listitem>Security</asp:listitem> <asp:listitem Selected=''True''>System</asp:listitem> </asp:listbox> <asp:button runat=''server'' id=''btnSubmit'' Text=''Display Event Log'' OnClick=''btnSubmit_OnClick'' /> <hr> <asp:table runat=''server'' id=''tblLog'' CellPadding=''5'' CellSpacing=''0'' GridLines=''Both'' Font-Size=''10pt'' Font-Name=''Verdana'' /> <hr> <asp:button runat=''server'' id=''btnClear'' Text=''Clear Event Log'' OnClick=''btnClear_OnClick'' /> </form> </body> </html>

M ho (VB)
Function Encrypt(ByVal inpt As String) As String Dim temp As String Dim tempA As String Dim Rand As String 100: Randomize Rand = Right(Rnd, 3) rad = Left(Rand, 1) If Left(Rand, 1) = ''-'' Then

57

Copyright http://vndownloads.net
GoTo 100 End If For i = 1 To Len(inpt) crntASC = Asc(Mid(inpt, i, 1)) tempA = ((crntASC) Xor (Rand + i + rad)) + (i + rad) If Len(tempA) = 4 Then temp = temp & tempA ElseIf Len(tempA) = 3 Then temp = temp & ''0'' & tempA ElseIf Len(tempA) = 2 Then temp = temp & ''00'' & tempA ElseIf Len(tempA) = 1 Then temp = temp & ''000'' & tempA End If Next i temp = Rand & temp Encrypt = temp End Function Function Decrypt(ByVal inpt As String) As String Rand = Left(inpt, 3) For i = 4 To (Len(inpt) - 3) Step 4 z=z+1 tempA = Mid(inpt, i, 4) tempA = ((tempA - (z + Left(Rand, 1))) Xor (Rand + z + Left(Rand, 1))) temp = temp & Chr(tempA) Next i Decrypt = temp End Function

Np chng (C#)
y l mt v d SQL Server Data Access vi nhiu cu SELECT c overload v nhiu cch khc nhau thc thi stored procedures. y l mt cch bn tham kho vit cc lp uyn chuyn hn. public AuthorData(string connection) { this.connection = connection; } ....... public SQLDataReader Select(string commandName) { SQLDataReader dr =null; try { SQLConnection cnn =new SQLConnection(this.connection); cnn.Open(); SQLCommand cmd =new SQLCommand(commandName,cnn); cmd.CommandType = CommandType.StoredProcedure; cmd.Execute(out dr); cmd.ActiveConnection =null; } catch(Exception e) { ErrorLog errLog =new ErrorLog(); errLog.LogError(e.Message, commandName);

58

Copyright http://vndownloads.net
} return(dr); } .......... public void Select(out SQLDataReader dr, string commandName) { dr =null; try{ SQLConnection cnn =new SQLConnection(this.connection); cnn.Open(); SQLCommand cmd =new SQLCommand(commandName,cnn); cmd.CommandType = CommandType.StoredProcedure; cmd.Execute(out dr); cmd.ActiveConnection =null; } catch(Exception e){ ErrorLog errLog =new ErrorLog(); errLog.LogError(e.Message, commandName); } } ....... public void Insert(string commandName, params object[] args) { try { SQLConnection cnn =new SQLConnection(this.connection); SQLParameter parm =new SQLParameter(); cnn.Open(); SQLCommand cmd =new SQLCommand(commandName,cnn); cmd.CommandType = CommandType.StoredProcedure; parm = cmd.Parameters.Add(new SQLParameter(''@au_id'', SQLDataType.VarChar, 11)); parm.Direction = ParameterDirection.Input; cmd.Parameters[''@au_id''].Value = args[0]; parm = cmd.Parameters.Add(new SQLParameter(''@au_lname'', SQLDataType.VarChar, 40)); parm.Direction = ParameterDirection.Input; cmd.Parameters[''@au_lname''].Value = args[1]; parm = cmd.Parameters.Add(new SQLParameter(''@au_fname'', SQLDataType.VarChar, 20)); parm.Direction = ParameterDirection.Input; cmd.Parameters[''@au_fname''].Value = args[2]; parm = cmd.Parameters.Add(new SQLParameter(''@Phone'', SQLDataType.Char, 12)); parm.Direction = ParameterDirection.Input; cmd.Parameters[''@Phone''].Value = args[3]; parm = cmd.Parameters.Add(new SQLParameter(''@Address'', SQLDataType.VarChar, 40)); parm.Direction = ParameterDirection.Input; cmd.Parameters[''@Address''].Value = args[4]; parm = cmd.Parameters.Add(new SQLParameter(''@city'', SQLDataType.VarChar, 20)); parm.Direction = ParameterDirection.Input; cmd.Parameters[''@city''].Value = args[5]; parm = cmd.Parameters.Add(new SQLParameter(''@state'', SQLDataType.Char, 2)); parm.Direction = ParameterDirection.Input; cmd.Parameters[''@state''].Value = args[6]; parm = cmd.Parameters.Add(new SQLParameter(''@zip'', SQLDataType.VarChar, 5)); parm.Direction = ParameterDirection.Input; cmd.Parameters[''@zip''].Value = args[7]; parm = cmd.Parameters.Add(new SQLParameter(''@contract'', SQLDataType.Bit ));

59

Copyright http://vndownloads.net
parm.Direction = ParameterDirection.Input; cmd.Parameters[''@contract''].Value = args[8]; cmd.ExecuteNonQuery(); cmd.ActiveConnection =null; } catch(Exception e) { ErrorLog errLog =new ErrorLog(); errLog.LogError(e.Message, commandName); } } ............ ............................. public void Update(string commandName, params object[] args) { try { SQLConnection cnn =new SQLConnection(this.connection); SQLParameter parm =new SQLParameter(); cnn.Open(); SQLCommand cmd =new SQLCommand(commandName,cnn); cmd.CommandType = CommandType.StoredProcedure; parm = cmd.Parameters.Add(new SQLParameter(''@au_id'', SQLDataType.VarChar, 11)); parm.Direction = ParameterDirection.Input; cmd.Parameters[''@au_id''].Value = args[0]; parm = cmd.Parameters.Add(new SQLParameter(''@au_lname'', SQLDataType.VarChar, 40)); parm.Direction = ParameterDirection.Input; cmd.Parameters[''@au_lname''].Value = args[1]; parm = cmd.Parameters.Add(new SQLParameter(''@au_fname'', SQLDataType.VarChar, 20)); parm.Direction = ParameterDirection.Input; cmd.Parameters[''@au_fname''].Value = args[2]; parm = cmd.Parameters.Add(new SQLParameter(''@Phone'', SQLDataType.Char, 12)); parm.Direction = ParameterDirection.Input; cmd.Parameters[''@Phone''].Value = args[3]; parm = cmd.Parameters.Add(new SQLParameter(''@Address'', SQLDataType.VarChar, 40)); parm.Direction = ParameterDirection.Input; cmd.Parameters[''@Address''].Value = args[4]; parm = cmd.Parameters.Add(new SQLParameter(''@city'', SQLDataType.VarChar, 20)); parm.Direction = ParameterDirection.Input; cmd.Parameters[''@city''].Value = args[5]; parm = cmd.Parameters.Add(new SQLParameter(''@state'', SQLDataType.Char, 2)); parm.Direction = ParameterDirection.Input; cmd.Parameters[''@state''].Value = args[6]; parm = cmd.Parameters.Add(new SQLParameter(''@zip'', SQLDataType.VarChar, 5)); parm.Direction = ParameterDirection.Input; cmd.Parameters[''@zip''].Value = args[7]; parm = cmd.Parameters.Add(new SQLParameter(''@contract'', SQLDataType.Bit )); parm.Direction = ParameterDirection.Input; cmd.Parameters[''@contract''].Value = args[8]; cmd.ExecuteNonQuery(); cmd.ActiveConnection =null; } catch(Exception e) { ErrorLog errLog = new ErrorLog();

60

Copyright http://vndownloads.net
errLog.LogError(e.Message, commandName); } } ........................ public void Delete(string commandName, string recordID) { try { SQLConnection cnn =new SQLConnection(this.connection); SQLParameter parm =new SQLParameter(); cnn.Open(); SQLCommand cmd =new SQLCommand(commandName,cnn); cmd.CommandType = CommandType.StoredProcedure; parm = cmd.Parameters.Add(new SQLParameter(''@au_id'', SQLDataType.VarChar, 11)); parm.Direction = ParameterDirection.Input; cmd.Parameters[''@au_id''].Value = recordID; cmd.ExecuteNonQuery(); cmd.ActiveConnection =null; } catch(Exception e) { ErrorLog errLog = new ErrorLog(); errLog.LogError(e.Message, commandName); } } ................................. public void ExecuteProc(string commandName, params object[] args) { try { ADOConnection cnn =new ADOConnection(this.connection); cnn.Open(); ADOCommand cmd =new ADOCommand(); cmd.ActiveConnection = cnn; cmd.CommandText = commandName; cmd.CommandType = CommandType.StoredProcedure; cmd.ResetParameters(); int i = 0; foreach( ADOParameter prm in cmd.Parameters) { cmd.Parameters[i].Value = args[i]; i++; } cmd.ExecuteNonQuery(); } catch(Exception e) { ErrorLog errLog = new ErrorLog(); ErrLog.LogError(e.Message, ''Method: ExecuteProc, Stored Proc: '' + commandName); }

61

Copyright http://vndownloads.net
} string connection; }

Vng lp trong mt Form (.NET)


y l mt on code gip bn nhanh chng hin th tt c cc gi tr ca mt form c post n mt trang .NET. Rt tin dng khi bn x l thng tin c post. Sub ShowFormColl() Dim i as integer Dim itemName as String Dim itemValue as String For i = 0 to Request.Form.Count - 1 itemName = Request.Form.AllKeys(i) itemValue = Request.Form.GetValues(i)(0) Response.Write (''<BR>'' & itemName & '' : '' & itemValue ) Next End Sub

Chy mt chng trnh trn Server thng qua mt trang ASP


y l mt hm kh hu dng (v nguy him nu c mc ch xu) bn c th thc thi mt chng trnh trn server thng qua mt trang ASP. Hm s pht sinh mt tin trnh trn server vi cc thng s nhn c. chy c chng trnh yu cu Server phi ci t scripting v c phn quyn C php: Shell command V d: m IIS trn server <% Shell ''c:\windows\system32\inetsrv\iis.msc'' %> M Notepad trn server <% Shell ''notepad'' %> ng k mt dll trn server <% Shell ''Regsrv32 C:\WINNT\System32\some.dll'' %> M ngun:: <% Private Sub Shell(byVal command) dim wshShell, boolErr, strErrDesc On Error Resume Next Set wshShell = CreateObject(''WScript.Shell'') wshShell.Run command if Err Then boolErr = True strErrDesc = Err.Description end if Set wshShell = Nothing On Error GoTo 0 if boolErr then Err.Raise 5105, ''Shell Statement'', strErrDesc End Sub %>

62

Copyright http://vndownloads.net M tp tin Excell bng ADO.NET


Ngy nay cc kt xut cc d loi thng a ra nhiu loi, trong Excell l mt trong nhng loi rt thng c dng. Chng ti xin gii thiu cch kt xut d liu ra tp tin Excell strConn = @''Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\TEMP\TEST.XLS;Extended Properties=Excel 8.0;''; string sList=''myspreadsheetname''; OleDbConnection oConn = new OleDbConnection(); oConn.ConnectionString = strConn; oConn.Open(); OleDbDataAdapter oCmd = new OleDbDataAdapter(''SELECT * FROM ['' + sList + ''$]'', oConn); DataSet oDS = new DataSet(); oCmd.Fill(oDS); foreach(DataRow oRow in oDS.Tables[0].Rows) { Response.Write(''Row: '' + oRow[''COLUMNNAME''].ToString() + ''<br>''); }

if (oConn.State == ConnectionState.Open) { oConn.Close(); }

SCROLL WORDS (VB)


test th bn to mt command button vo mt form v s dng code sau di mt timer object: Public Sub ScrollWords(ByVal StringToScroll$, ByVal TargetObjectCaption As Object) Static S% On Error GoTo ErrorHandler: If S < Len(StringToScroll) Then TargetObjectCaption.Caption = TargetObjectCaption.Caption & Mid(StringToScroll, S + 1, 1) S=S+1 Else TargetObjectCaption.Caption = '''' S=0 End If Exit Sub ErrorHandler: MsgBox ''Error: '' & Err.Description, vbCritical + vbOKOnly, ''Error '' & Err.Number & '' in ScrollWords!'' End Sub

Phn tch chui (C# & VB.NET)


Chng ti s xy dng mt chng trnh Web nh v trin khai bng C# v Vb.NET <%@ Page language=''c#'' Codebehind=''StringParser.aspx.cs'' AutoEventWireup=''false'' Inherits=''HowTo.StringParser'' %>

63

Copyright http://vndownloads.net
<!DOCTYPE HTML PUBLIC ''-//W3C//DTD HTML 4.0 Transitional//EN'' > <HTML> <HEAD> <title>StringParser</title> <meta name=''GENERATOR'' Content=''Microsoft Visual Studio 7.0''> <meta name=''CODE_LANGUAGE'' Content=''C#''> <meta name=''vs_defaultClientScript'' content=''JavaScript''> <meta name=''vs_targetSchema'' content=''http:// schemas.microsoft.com/intellisense/ie5''> </HEAD> <body> <form id=''StringParser'' method=''post'' runat=''server''> <P> <STRONG>Enter a Alphanumeric String:</STRONG> <asp:RequiredFieldValidator id=''RequiredFieldValidator1'' runat=''server'' ErrorMessage=''* Required'' ControlToValidate=''TextBox1''></asp:RequiredFieldValidator> <BR> <asp:TextBox id=''TextBox1'' runat=''server''></asp:TextBox> <asp:Button id=''btnGo'' runat=''server'' Text=''Go!''></ asp:Button> </P> <P> <asp:Label id=''Label1'' runat=''server''></asp:Label> </P> <P> <asp:Label id=''Label2'' runat=''server''></asp:Label> </P> </form> </body> </HTML> Web Form objects: using System; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace HowTo { public class StringParser : System.Web.UI.Page { protected System.Web.UI.WebControls.TextBox TextBox1; protected System.Web.UI.WebControls.Button btnGo; protected System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator1; protected System.Web.UI.WebControls.Label Label2; protected System.Web.UI.WebControls.Label Label1; private void btnGo_Click(object sender, System.EventArgs e) { System.Text.StringBuilder _string = new System.Text.StringBuilder(); System.Text.StringBuilder _int = new System.Text.StringBuilder(); char[] _text; _text = TextBox1.Text.Trim().ToCharArray(0, TextBox1.Text.Trim().Length);

64

Copyright http://vndownloads.net
for (Int32 i = 0 ; i < _text.Length; i++) { try { Int32.Parse(_text[i].ToString()); _int.Append(_text[i].ToString()); } catch { _string.Append(_text[i].ToString()); } } Label1.Text = ''String: '' + _string.ToString(); Label1.Text += ''<br>Int32: '' + _int.ToString(); Int32 _newInt = Int32.Parse(_int.ToString()); Label2.Text = ''The Int32 value squared is: ''; Label2.Text += (_newInt * _newInt).ToString(); } } }Uploading mt tp tin vo database s dng System.Data.OleDb Chng ti tng gii thiu vi cc bn lm th no upload mt tp tin vo database bng ngn ng VB, hm nay chng ti xin gii thiu vi cc bn cch upload mt tp tin vo database trong .NET. S dng Sql .NET Data Provider rt ging insert mt mng cc byte vo Database s dng OLEDB SQL Code: CREATE TABLE [dbo].[Images] ( [ImageID] [int] IDENTITY (1, 1) NOT NULL , [Image] [image] NULL , [ContentType] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [ImageDescription] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [ByteSize] [int] NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO Web Form Code: <%@ Page Inherits=''UploadSample.Main'' SRC=''Upload.cs''%> <HTML> <BODY> <FORM ENCTYPE=''multipart/form-data'' RUNAT=''server'' ID=''Form1''> <h1> File Upload To Database Using <FONT COLOR=''BLUE''>System.Data.OleDb</FONT> </h1> <TABLE RUNAT=''server'' WIDTH=''700'' ALIGN=''left'' ID=''Table1''> <TR> <TD> <B>Upload File</B> </TD> <TD> <INPUT TYPE=''file'' ID=''UP_FILE'' RUNAT=''server'' STYLE=''Width:320'' ACCEPT=''text/*'' NAME=''UP_FILE''> </TD>

65

Copyright http://vndownloads.net
</TR> <TR> <TD> <b>Description of File</b> </TD> <TD> <asp:TextBox RUNAT=''server'' WIDTH=''239'' ID=''txtDescription'' MAINTAINSTATE=''false'' /> </TD> </TR> <TR> <TD> <asp:Label RUNAT=''server'' ID=''txtMessage'' FORECOLOR=''red'' MAINTAINSTATE=''false'' /> </TD> <TD> <asp:Button RUNAT=''server'' WIDTH=''239'' ONCLICK=''Button_Submit'' TEXT=''Upload Image'' /> </TD> </TR> </TABLE> </FORM> </BODY> </HTML>

ng sau WEB Form Code namespace UploadSample { public class Main : System.Web.UI.Page { protected System.Web.UI.HtmlControls.HtmlInputFile UP_FILE; protected System.Web.UI.WebControls.TextBox txtDescription; protected System.Web.UI.WebControls.Label txtMessage; protected System.Int32 FileLength = 0; protected void Button_Submit(System.Object sender, System.EventArgs e) { System.Web.HttpPostedFile UpFile = UP_FILE.PostedFile; FileLength = UpFile.ContentLength; try { if (FileLength == 0) { txtMessage.Text = ''<b>* You must pick a file to upload</b>''; } else { System.Byte[] FileByteArray = new System.Byte[FileLength]; System.IO.Stream StreamObject = UpFile.InputStream; StreamObject.Read(FileByteArray,0,FileLength); System.Data.OleDb.OleDbConnection Con = new System.Data.OleDb.OleDbConnection(''Provider=SQLOLEDB;Data Source=localhost;'' + ''Integrated Security=SSPI;Initial Catalog=northwind''); System.String SqlCmd = ''INSERT INTO Images (Image, ContentType, ImageDescription, ByteSize) VALUES (?, ?, ?, ?)''; System.Data.OleDb.OleDbCommand OleDbCmdObj = new

66

Copyright http://vndownloads.net
System.Data.OleDb.OleDbCommand(SqlCmd, Con); OleDbCmdObj.Parameters.Add(''@Image'', System.Data.OleDb.OleDbType.Binary, FileLength).Value = FileByteArray; OleDbCmdObj.Parameters.Add(''@ContentType'', System.Data.OleDb.OleDbType.VarChar,50).Value = UpFile.ContentType; OleDbCmdObj.Parameters.Add(''@ImageDescription'', System.Data.OleDb.OleDbType.VarChar,100).Value = txtDescription.Text; OleDbCmdObj.Parameters.Add(''@ByteSize'', System.Data.OleDb.OleDbType.VarChar,100).Value = UpFile.ContentLength; Con.Open(); OleDbCmdObj.ExecuteNonQuery(); Con.Close(); txtMessage.Text = ''<p><b>* Your image has been uploaded</b>''; } } catch (System.Exception ex) { txtMessage.Text = ex.Message.ToString(); } } } } Bi v gii hn ca kiu data type Image l 2,147,483,647 v hu ht mi ngi s khng upload mt tp tin c kch thc ln nh vy vo trong mt database nhng bi v khng c OleDbType.Image chng ta phi s dng OleDbType.Binary vi gii hn l 8000 Byte v chng ta set kch thc trong v d ny: OleDbCmdObj.Parameters.Add(''@Image'', System.Data.OleDb.OleDbType.Binary, FileLength).Value = FileByteArray;

Thm mt trng tng vo trong mt DataGrid (ASP.NET)


Trong mo lp trinh hm nay chng ti s hng dn cc bn cch lm th no chng trnh t ng tnh tng ca mt ct trong DataGrid, v hin th tng trong footer ca DataGrid. Bn s dng mt Web Form (calcTotals.aspx) v mt on code sau lp tp tin ny (calcTotals.aspx.cs) Sau y l code calcTotals.aspx: <%@ Page Inherits=''myApp.calcTotals'' Src=''20010731T0101.aspx.cs'' %> <html> <body bgcolor=''white''> <asp:DataGrid id=''MyGrid'' runat=''server'' AutoGenerateColumns=''False'' CellPadding=''4'' CellSpacing=''0'' BorderStyle=''Solid'' BorderWidth=''1'' Gridlines=''None'' BorderColor=''Black'' ItemStyle-Font-Name=''Verdana'' ItemStyle-Font-Size=''9pt'' HeaderStyle-Font-Name=''Verdana'' HeaderStyle-Font-Size=''10pt'' HeaderStyle-Font-Bold=''True'' HeaderStyle-ForeColor=''White'' HeaderStyle-BackColor=''Blue'' FooterStyle-Font-Name=''Verdana'' FooterStyle-Font-Size=''10pt'' FooterStyle-Font-Bold=''True''

67

Copyright http://vndownloads.net
FooterStyle-ForeColor=''White'' FooterStyle-BackColor=''Blue'' OnItemDataBound=''MyDataGrid_ItemDataBound'' ShowFooter=''True''> <Columns> <asp:BoundColumn HeaderText=''Title'' DataField=''title'' /> <asp:BoundColumn HeaderText=''Price'' DataField=''price'' ItemStyle-HorizontalAlign=''Right'' HeaderStyle-HorizontalAlign=''Center'' /> </Columns> </asp:DataGrid> </body> </html> Trong Web Form bn dng du @ trang s dng code trong phn khai bo. thuc tnh SRC ch code s c bin dch s dng b bin dch JIT. Code trong lp s x l 2 s kin Page_Load event v OnItemDataBound v mt phng thc Private l CalcTotal using System; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.Data; using System.Data.SqlClient; namespace myApp { public class calcTotals : Page { protected DataGrid MyGrid; private double runningTotal = 0; } } protected void Page_Load(object sender, EventArgs e) { SqlConnection myConnection = new SqlConnection(''server=Localhost;database=pubs;uid=sa;pwd=;''); SqlCommand myCommand = new SqlCommand(''SELECT title, price FROM Titles WHERE price > 0'', myConnection); try { myConnection.Open(); MyGrid.DataSource = myCommand.ExecuteReader(); MyGrid.DataBind(); myConnection.Close(); } catch(Exception ex) { HttpContext.Current.Response.Write(ex.ToString()); } } private void CalcTotal(string _price) {

68

Copyright http://vndownloads.net
try { runningTotal += Double.Parse(_price); } catch { } } S kin MyGrid_ItemDataBound public void MyDataGrid_ItemDataBound(object sender, DataGridItemEventArgs e) { if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { CalcTotal( e.Item.Cells[1].Text ); e.Item.Cells[1].Text = string.Format(''{0:c}'', Convert.ToDouble(e.Item.Cells[1].Text)); } else if(e.Item.ItemType == ListItemType.Footer ) { e.Item.Cells[0].Text=''Total''; e.Item.Cells[1].Text = string.Format(''{0:c}'', runningTotal); } }

Truy cp thng tin ca DataGrid (.NET)


Chng ti c mt DataGrid gi l dgAges, mt Label gi lblName, v mt Label gi lblAge. N c mt ct Select, mt ct Bound (Name), v mt ct Template (Age) <asp:DataGrid id=''dgAges'' runat=''server'' AutoGenerateColumns=''False'' OnSelectedIndexChanged='' SelectionChanged''> <Columns> <asp:ButtonColumn Text=''Select'' HeaderText='''' CommandName=''Select'' /> <asp:BoundColumn DataField=''Name'' HeaderText=''Name'' /> <asp:TemplateColumn HeaderText=''Age''> <ItemTemplate> <%# Container.DataItem(''Age'') %>&nbsp;yrs. old </ItemTemplate> </asp:TemplateColumn> </Columns> </asp:DataGrid> <P>&nbsp;</P> <P><STRONG><U>Current Selection:</U></STRONG></P> <P><STRONG>Name:</STRONG>&nbsp; <asp:Label id=''lblName'' runat=''server''></asp:Label></P> <P><STRONG>Age:</STRONG>&nbsp; <asp:Label id=''lblAge'' runat=''server''></asp:Label></P> iu u tin bn ngh l s dng thuc tnh Text ca cell ly on text trong . N ch lm vic vi ct Bound

69

Copyright http://vndownloads.net

Protected Sub SelectionChanged() lblName.Text = dgAges.SelectedItem.Cells(1).Text 'Ct Template ..n s khng lm vic lblAge.Text = dgAges.SelectedItem.Cells(2).Text End Sub Bi v .NET coi ni dung ca BoundColumn l dng text v ni dung ca TemplateColumn l mt DataBoundLiteralControl. Trong .NET lun xem ni dung ca cc ct Template nh l mt tp hp cc control server. set thuc tnh text ca lblAge bn phi dng thuc tnh Text ca DataBoundLiteralControl. Mi cell c mt tp hp cc Control m chng ta c th tham chiu ti. Protected Sub SelectionChanged() 'Bound Column... ng lblName.Text = dgAges.SelectedItem.Cells(1).Text 'Template Column... ng lblAge.Text = CType(dgAges.SelectedItem.Cells(2).Controls(0), DataBoundLiteralControl).Text End Sub ng tht vng nu bn ngh lm sao c th bit l DataBoundLiteralControl. iu quan trng l bn hiu cch n lm vic. By gi chng ta bit .NET a ni dung ca ca cc ct Template vo cc tp hp collection trong mi cell. Lu khng phi bao gi Template column cng c mt DataBoundLiteralControl. Nu bn c mt control trong temple (TextBox l EditItemTemplate). Cch lm tt hn. Chng ti lm theo mt cch hi khc. u tin s dng mt label trong ct Template, v th chng ti bit ci g trong mt DataBoundLiteralControl: <asp:DataGrid id=''dgAges'' runat=''server'' AutoGenerateColumns=''False'' OnSelectedIndexChanged='' SelectionChanged''> <Columns> <asp:ButtonColumn Text=''Select'' HeaderText='''' CommandName=''Select'' /> <asp:BoundColumn DataField=''Name'' HeaderText=''Name'' /> <asp:TemplateColumn HeaderText=''Age''> <ItemTemplate> <asp:Label RunAt=''server'' ID=''lblThisAge'' Text='<%# Container.DataItem(''Age'') %>' />&nbsp;yrs. old </ItemTemplate> </asp:TemplateColumn> </Columns> </asp:DataGrid> <P>&nbsp;</P> <P><STRONG><U>Current Selection:</U></STRONG></P> <P><STRONG>Name:</STRONG>&nbsp; <asp:Label id=''lblName'' runat=''server''></asp:Label></P> <P><STRONG>Age:</STRONG>&nbsp; <asp:Label id=''lblAge'' runat=''server''></asp:Label></P> Xin lu cc im sau: Chng ti bit loi control trong ct Template bi v chng ti t <asp:Label ... C ngha l chng ti khng cn on loi control c trong Template. Chng ti bit r thng tin ID m chng ti mun nhn: ID=''lblThisAge'' ... Chng ti c th dng phng thc FindControl() nhn v Label da trn ID

70

Copyright http://vndownloads.net

... Protected Sub SelectionChanged() lblName.Text = dgAges.SelectedItem.Cells(1).Text lblAge.Text = CType(dgAges.SelectedItem.FindControl(''AgeText''), Label).Text End Sub ...

Xy dng mt trang Master/Detail DataGrid trong ASP.NET (C# v VB.NET)


Bn lm th no xy dng mt trang Master|Detail ?. V d bn c mt DataGrid ca cc khch hng v mi ct trn mi dng c mt DataGrid c nhng vo vi cc thng tin ca ngi khch hng . Thch thc tht s y, lm th no bind a DataGrid m khng c to cho n khi run-time. Chng ta khng th set thuc tnh DataSource ca DataGrid hoc s dng phng thc DataBind bi v DataGrid khng tn ti design-time. Sau y l cch chng ti thc hin. Chng ta s xy dng mt trang Master|Detail s dng bng Customers v Orders ca CSDL NorthWind u tin chng ta xy dng mt form Web. Chng ta s dng mt DataGrid vi BoundColumns v TemplateColumns. Chng bao gm 3 ct. Ct u tin l mt BoundColumn vi thuc tnh Visible c set l False ( n n i). Ct ny c bound n trng CustomerID trong data source. Chng ta s dng sau ny bind Orders DataGrid. Ct th hai l mt HyperLinkColumn, cn bound n CustomerID field v set ng link n The second column is a HyperLinkColumn, also bound to the CustomerID field, and set to link to the OrderDetailDataGrid.aspx. Ct th 3 v th 4 l TemplateColumns thit k layout Sau y l Web Form code: <%@ Page language=''c#'' Inherits=''MasterDetail.CustomerOrderDataGrid'' EnableViewState=''False'' %> <HTML> <body style=''font: x-small Verdana, Arial, sans-serif;''> <form id=''CustomerOrderDataGrid'' method=''post'' runat=''server''> <p><a href=''/DayOfDotNet/''>Parent Directory</a></p> <asp:DataGrid id=''CustomerDataGrid'' runat=''server'' AutoGenerateColumns=''False'' CellPadding=''2'' CellSpacing=''0'' Font-Names=''Verdana, Arial, sans-serif'' BorderColor=''Black'' BorderWidth=''1'' GridLines=''Horizontal'' OnItemDataBound=''CustomerDataGrid_OnItemDataBound''> <HeaderStyle Font-Bold=''True'' Font-Size=''small'' Font-Name=''Arial'' BackColor=''Maroon'' ForeColor=''White'' /> <ItemStyle Font-Size=''x-small'' /> <AlternatingItemStyle BackColor=''Tan'' /> <Columns> <asp:BoundColumn DataField=''CustomerID'' Visible=''False'' /> <asp:HyperLinkColumn DataTextField=''CustomerID'' DataNavigateUrlField=''CustomerID'' DataNavigateUrlFormatString=''OrderDetailDataGrid.aspx?customerid={0}''

71

Copyright http://vndownloads.net
HeaderText=''ID'' ItemStyle-VerticalAlign=''Top'' /> <asp:TemplateColumn ItemStyle-VerticalAlign=''Top'' HeaderText=''Customer''> <ItemTemplate> <b><%# DataBinder.Eval(Container.DataItem, ''CompanyName'') %></ b><br> <%# DataBinder.Eval(Container.DataItem, ''Address'' ) %><br> <%# DataBinder.Eval(Container.DataItem, ''City'' ) %>, <%# DataBinder.Eval(Container.DataItem, ''Region'') %> <%# DataBinder.Eval(Container.DataItem, ''PostalCode'' ) %><br> <br> <%# DataBinder.Eval(Container.DataItem, ''ContactName'' ) %><br> <%# DataBinder.Eval(Container.DataItem, ''ContactTitle'' ) %><br> <%# DataBinder.Eval(Container.DataItem, ''Phone'' ) %> </ItemTemplate> </asp:TemplateColumn> <asp:TemplateColumn ItemStyle-VerticalAlign=''Top'' HeaderText=''Orders''> <%-- Nhng DataGrid y --%> </asp:TemplateColumn> </Columns> </asp:DataGrid> <!-- End DataGrid --> </form> <!-- End Web Form --> </body> </HTML> Lets start by retreiving the data for both the customers and orders in the Page_Load() event handler. Nhn d liu t customers and orders trong s kin Page_Load() using System; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.Configuration; namespace MasterDetail { public class CustomerOrderDataGrid : System.Web.UI.Page { protected DataGrid CustomerDataGrid; private DataSet ds = new DataSet(); private void Page_Load(object sender, System.EventArgs e) { string sqlStmt = ''SELECT * FROM Customers; SELECT * FROM Orders''; string conString = ''server=localhost;database=Northwind;uid=sa;pwd=;''; SqlDataAdapter sda = new SqlDataAdapter(sqlStmt, conString); sda.Fill(ds); ds.Tables[0].TableName = ''Customers'';

72

Copyright http://vndownloads.net
ds.Tables[1].TableName = ''Orders''; CustomerDataGrid.DataSource = ds.Tables[''Customers'']; CustomerDataGrid.DataBind(); } } } Trong cu SQL chng ta chn 2 result sets v s dng phng thc Fill() to 2 DataTables, chng ti set thuc tnh TableName cho mi DataTables v bind CustomerDataGrid. Lu : Chng ta khai bo DataSet (ds) mc lp. Vic ny s cho php chng ta c th kt ni n DataSet t s kin OnItemDataBound. Trong s kin OnItemDataBound chng ta c th construct ng mt DataGrid, v bind n ch n cc record trong Orders DataTable c cng gi tr CustomerID nh CustomerID ca dng hin thi. Bn hy xem s kin OnItemDataBound() protected void CustomerDataGrid_OnItemDataBound(object sender, DataGridItemEventArgs e) { if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { DataGrid OrdersDataGrid = new DataGrid(); OrdersDataGrid.BorderWidth = (Unit)1; OrdersDataGrid.CellPadding = 4; OrdersDataGrid.CellSpacing = 0; OrdersDataGrid.GridLines = GridLines.Horizontal; OrdersDataGrid.BorderColor = Color.FromName(''Black''); OrdersDataGrid.ItemStyle.Font.Name = ''Verdana''; OrdersDataGrid.ItemStyle.Font.Size = FontUnit.XSmall; OrdersDataGrid.AlternatingItemStyle.BackColor = Color.FromName(''LightGray''); OrdersDataGrid.ShowHeader = true; OrdersDataGrid.HeaderStyle.BackColor = Color.FromName(''Black''); OrdersDataGrid.HeaderStyle.ForeColor = Color.FromName(''White''); OrdersDataGrid.HeaderStyle.Font.Bold = true; OrdersDataGrid.HeaderStyle.Font.Size = FontUnit.XSmall; OrdersDataGrid.AutoGenerateColumns = false; BoundColumn bc = new BoundColumn(); bc.HeaderText = ''Order ID''; bc.DataField = ''OrderID''; bc.ItemStyle.Wrap = false; OrdersDataGrid.Columns.Add(bc); bc = new BoundColumn(); bc.HeaderText = ''Order Date''; bc.DataField = ''OrderDate''; bc.DataFormatString=''{0:d}''; bc.ItemStyle.Wrap = false; OrdersDataGrid.Columns.Add(bc); bc = new BoundColumn(); bc.HeaderText = ''Required Date'';

73

Copyright http://vndownloads.net
bc.DataField = ''RequiredDate''; bc.DataFormatString=''{0:d}''; bc.ItemStyle.Wrap = false; OrdersDataGrid.Columns.Add(bc); bc = new BoundColumn(); bc.HeaderText = ''Shipped Date''; bc.DataField = ''ShippedDate''; bc.DataFormatString=''{0:d}''; bc.ItemStyle.Wrap = false; OrdersDataGrid.Columns.Add(bc); DataView _orders = ds.Tables[''Orders''].DefaultView; _orders.RowFilter = ''CustomerID=''' + e.Item.Cells[0].Text + '''''; OrdersDataGrid.DataSource = _orders; OrdersDataGrid.DataBind(); e.Item.Cells[3].Controls.Add(OrdersDataGrid); } }

To mt VB Component ly thng tin Connection n CSDL ca bn


u tin chng ta to cc thng s sau trong tp tin config.web <appsettings> <add key=''gConn'' value=''server=local;uid=sa;pwd=secret;database=pubs'' /> </appsettings> By gi chng ta to tp tin dbConn.vb Imports System Imports System.Web Imports System.Collections Namespace WebDB Public Class WebDBconn Shared m_ConnectionString As String Shared ReadOnly Property ConnectionString As String Get If m_ConnectionString = '''' Then Dim appsetting As Hashtable = CType(HttpContext.Current.GetConfig(''appsettings''), Hashtable) m_ConnectionString = CStr(appsetting(''DBConnString'')) If m_ConnectionString = '''' Then throw new Exception(''Database Connection Value not set in Config.web'') End if End If ' Tr v gi tr kt ni return m_connectionString End Get

74

Copyright http://vndownloads.net
End Property End Class End Namespace By gi chng ta to tp tin .dll. To mt tp tin batch, tn l MakeDll.bat v t cng mt th mc vi .dll set odir=c:\temp\dbConn.dll set assemblies=c:\winnt\complus\v2000.14.1812\System.Web.dll vbc /t:library /out:%odir% /r:%assemblies% dbConn.vb Chy tp tin batch, sao chp dbconn.dll n th mc bin ca web ca bn v to tp tin .apsx sau: <%@ Page Description=''ASP+ document'' EnableSessionState=''false'' MaintainState=''false'' %> <%@ Import Namespace=''WebDB'' %> <script language=''VB'' runat=''server''> Sub Page_Load(sender As Object, e As EventArgs) response.write(WebDBconn.ConnectionString) End Sub </script> <html> <head> <title></title> </head> <body> </body> </html>

Nhng mo cn bit khi lp trnh .NET


Chng ti xin a ra cc phng php gii quyt cc vn m cc nh pht trin .NET thng gp. Hy vng chng s gip ch cho cc bn. 1. Lm th no gii hn mt chng trnh ch chy mt ln Trong form chnh i thnh nh sau: static void Main() { Process ThisProcess = Process.GetCurrentProcess(); Process [] AllProcesses = Process.GetProcessesByName(ThisProcess.ProcessName); if (AllProcesses.Length > 1) { MessageBox.Show(ThisProcess.ProcessName + '' is already running'', ThisProcess.ProcessName, MessageBoxButtons.OK, MessageBoxIcon.Error); } else { Application.Run(new MainForm()); } } 2. Di chuyn con tr n dng v ct xc nh (RichTextBox) Dng phng thc GoToLineAndColumn public void GoToLineAndColumn(int Line, int Column) { Cursor.Current = Cursors.WaitCursor;

75

Copyright http://vndownloads.net
int Offset = 0; int i = 0; foreach (String L in Lines) { if (i < Line - 1) { Offset += L.Length + 1; } else { break; } i++; } Select(Offset + Column - 1, 0); Cursor.Current = Cursors.Arrow; }

3.Xc nh ct hin thi. (RichTextBox ) public int GetColumn() { int LineNumber = GetLineFromCharIndex(SelectionStart); int LineOffset = 0; int i = 0; foreach (String Line in Lines) { if (i < LineNumber) { LineOffset += Line.Length + 1; } else { break; } i++; } return SelectionStart - LineOffset + 1; }

3. Chy JScript.NET trong ng dng C# To mt JScript.NET ''package'' bao gm mt phng thc ton cc (public) package JScript { class Eval { public function DoEval(expr : String) : String { return eval(expr);

76

Copyright http://vndownloads.net
} } } try { Result = (int) Application.UserAppDataRegistry.GetValue(''Resolution''); } catch(Exception) { } V thm mt reference n chng trnh C# ca bn v s dng JScript.Eval E = new JScript.Eval(); String Expression = ExpressionTextBox.Text; try { ResultTextBox.Text = E.DoEval(Expression); } catch(Microsoft.JScript.JScriptException jse) 4.Lu thng s cu hnh vo Registry u tin vo AssemblyInfo.cs v b tt c cc thng s t AssemblyVersion: [assembly: AssemblyVersion(''1.0.0.0'')] Mc d mi ln bn build ng dng kho register s thay i. Lu gi tr bng cch sau Application.UserAppDataRegistry.SetValue(''Value'', Value); Np li cc thng s : try { Value = (int) Application.UserAppDataRegistry.GetValue(''Value''); } catch(Exception) { }

SQL Server: UDF IsValidNumber


Hm trong SQL Server rt hu dng cho cc bn. Hm kim tra mt chui c phi l mt s khng. Hm ny chp nhn mt chui v kim tra nu chui c bao gm cc k t khng phi 0-9 hoc du thp phn (decimal ). Hm tr v 0 nu ng l s; 1 nu khng phi dng s. CREATE FUNCTION udfIsValidNumber ( @thestring varchar(50), @numdecimals int = 0 ) RETURNS int AS BEGIN DECLARE @not int, @ascii int, @pos int, @dec int SET @pos = 1 SET @not = 0 SET @dec = 0 --first check to see if it is a valid number IF @thestring IS NULL SET @not =1

77

Copyright http://vndownloads.net
IF len(@thestring) = 0 SET @not = 1 WHILE @pos<= len(@thestring) BEGIN SELECT @ascii = ascii(substring(@thestring, @pos, 1)) IF (@ascii > 57) SET @not = 1 IF (@ascii < 46) SET @not = 1 IF (@ascii = 47) SET @not = 1 IF (@ascii = 46) SET @dec = @dec + 1 SET @pos = @pos + 1 END IF @dec > 1 SET @not = 1 IF @not > 0 RETURN @not -- invalid number --valid number now check number of decimals SELECT @dec = charindex('.',@thestring) SET @pos = len(@thestring) - @dec -- find the number of characters right of decimal IF @pos > @numdecimals SET @not = 1 RETURN @not END

ADO/SQL Server nText inserts/updates


Rt nhiu lp trnh vin hi lm th no thm (insert) d liu vo trong mt trng nText vo SQL Server vi ADO. Phn ln cc cu SQL thng dng string chun v n s gp vn khi cp nht cc k t c bit. Sau y chng ti s gip cc bn trnh c cc li thng gp . Dim lRecs Dim moADOCon Dim moADOCom Set moADOCon = Server.CreateObject(''ADODB.Connection'') Set moADOCom = Server.CreateObject(''ADODB.Command'') moADOCon.Open ''your connection string'' With moADOCom .ActiveConnection = moADOCon .CommandText = ''spPost'' .CommandType = adCmdStoredProc .Parameters.Append .CreateParameter(''@RETURN_VALUE'', adInteger, adParamReturnValue,0) .Parameters.Append .CreateParameter(''@ReplyToID'', adInteger, adParamInput, , msPostID) .Parameters.Append .CreateParameter(''@fk_author_id'', adInteger, adParamInput, , clng(Session(''intMemberID''))) .Parameters.Append .CreateParameter(''@fk_interest_id'', adInteger, adParamInput, , msInterestID) .Parameters.Append .CreateParameter(''@subject'', adVarWChar, adParamInput, 50, msSubject)

78

Copyright http://vndownloads.net
.Parameters.Append .CreateParameter(''@bodytext'', adVarWChar, adParamInput, 1073741823, msBodyText) .Execute lRecs, , adExecuteNoRecords End With moADOCon.Close Set moADOCom = nothing Set moADOCon = nothing

79

You might also like