You are on page 1of 14

'Simple VB code to know the date and time when a file was created

'or last modified.

'No Declarations
'Simple VB code to know the date and time when a file was created
'or last modified.

Sub FileCreatedDateTime()

Dim filename As String

On Error GoTo errHandler

filename = InputBox("Please enter file name ?", "Input")


If Trim(filename) <> "" Then
MsgBox FileDateTime(filename)
Else
MsgBox "Invalid filename !!!", vbCritical + vbOKOnly, "Error!!!"
End If

errHandler:

If Err.Number <> 0 Then


MsgBox "Error Description :" & Err.Description & vbCrLf & " Error No : " &
Err.Number, vbCritical + vbOKOnly, "Error!!!"
End If

End Sub

Change Password Code:


No declarations
If Me.txtoldpassword.Text = PWord Then
If Me.txtconfirm = Me.txtnewpassword Then
SQL = " UPDATE users SET [Password]='" & Me.txtnewpassword.Text & "' where
UserName like '" & Me.txtusername.Text & "' and [Password] like '" &
txtoldpassword.Text & "'"
PWord = Me.txtnewpassword.Text
conn.Execute SQL
MsgBox "Your Password have been Changed Successfully!", , "Success"
'Me.txtusername.Text = ""
Me.txtconfirm.Text = ""
Me.txtnewpassword.Text = ""
Me.txtoldpassword.Text = ""
Me.txtoldpassword.SetFocus
Else
MsgBox "Invalid Password confirmation!"
End If
Else
MsgBox "Invalid Old Password"
End If

Show Time And Date:

Open the form, add one label as lbltime for time to show the other lable2 as lbldate, add
tow buttons to control each. You may add one more Command button to end the program.

Command1
lbldate.text =datestring
end sub
Command2
lbltime.text =timestring
end sub
Command3
End
end sub
end class

VB.Net - Unique Oracle Data Connection:


Imports System.Data.OracleClient
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click

Me.Cursor = Cursors.WaitCursor

If oracon Is Nothing Then


oracon = New OracleClient.OracleConnection("Data
Source=DATASERVER;Persist Security Info=True;User
ID=USERNAME;PWD=PASSWORD;Unicode=True")
End If

If oracon.State = ConnectionState.Closed Then


oracon.Open()
MessageBox.Show("Oracle Connection Is Now Avalilabe")
Me.Cursor = Cursors.Default
Exit Sub
End If
If oracon.State = ConnectionState.Open Then
MessageBox.Show("Oracle Connection Already Open No Need To Open Again")
End If

Me.Cursor = Cursors.Default
End Sub
Determines whether the input number is a perfect square or not

Dim a As Double, b As Double, c As Double, d As Integer


Private Sub Command1_Click()
d=0
a = CDbl(Text1.Text)
For b = 1 To a
c=b*b
If c = a Then
d=1
End If
Next b
If d = 1 Then
MsgBox "Perfect Square", vbInformation
Else
MsgBox "Not Perfect Square", vbInformation
End If
End Sub

Task: Save Text To A Text File.

Will need:
1 x text box
1 x command button
Lay out - however you like.

Private Sub Command1_Click()


Open App.Path & ("\data.txt") For Output As #1
Print #1, Text1.Text 'The saved text will be saved in the same folder that
the EXE is located - Must be EXE.
Close #1 'See my web browser.
End Sub

Task: How to take the particular string from a sentence?

String:02:245:4254-25
String I have to clip is 4254 using 'instrrev'method
copy the following code and paste it in V.B 6 it will work.
Private Sub Form_Load()
a = InStrRev("02:245:4254-253", ":", Len("02:245:4254-253"))
b = InStr(1, "02:245:4254-253", "-", vbTextCompare)
MsgBox Mid("02:245:4254-253", (a + 1), ((b - a) - 1))
End Sub

Task: Export DataGridView to Excel

No declarations
private static void exportToExcel( DataGridView dg, string fileName)
{
System.IO.StreamWriter excelDoc;
excelDoc = new System.IO.StreamWriter(fileName);
const string startExcelXML = "<xml version>\r\n<Workbook " +
"xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"\r\n" +
" xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\n " +
"xmlns:x=\"urn:schemas- microsoft-com:office:" +
"excel\"\r\n xmlns:ss=\"urn:schemas-microsoft-com:" +
"office:spreadsheet\">\r\n <Styles>\r\n " +
"<Style ss:ID=\"Default\" ss:Name=\"Normal\">\r\n " +
"<Alignment ss:Vertical=\"Bottom\"/>\r\n <Borders/>" +
"\r\n <Font/>\r\n <Interior/>\r\n <NumberFormat/>" +
"\r\n <Protection/>\r\n </Style>\r\n " +
"<Style ss:ID=\"BoldColumn\">\r\n <Font " +
"x:Family=\"Swiss\" ss:Bold=\"1\"/>\r\n </Style>\r\n " +
"<Style ss:ID=\"StringLiteral\">\r\n <NumberFormat" +
" ss:Format=\"@\"/>\r\n </Style>\r\n <Style " +
"ss:ID=\"Decimal\">\r\n <NumberFormat " +
"ss:Format=\"0.0000\"/>\r\n </Style>\r\n " +
"<Style ss:ID=\"Integer\">\r\n <NumberFormat " +
"ss:Format=\"0\"/>\r\n </Style>\r\n <Style " +
"ss:ID=\"DateLiteral\">\r\n <NumberFormat " +
"ss:Format=\"mm/dd/yyyy;@\"/>\r\n </Style>\r\n " +
"</Styles>\r\n ";
const string endExcelXML = "</Workbook>";

int rowCount = 0;
int sheetCount = 1;

excelDoc.Write(startExcelXML);
excelDoc.Write("<Worksheet ss:Name=\"Sheet" + sheetCount + "\">");
excelDoc.Write("<Table>");
excelDoc.Write("<Row>");
for(int x = 0; x <= dg.Columns.Count -1 ; x++)
{
excelDoc.Write("<Cell ss:StyleID=\"BoldColumn\"><Data
ss:Type=\"String\">");
excelDoc.Write(dg.Columns[x].HeaderText);
excelDoc.Write("</Data></Cell>");
}
excelDoc.Write("</Row>");
for (int i = 0; i <= dg.Rows.Count - 1; i++)
{
rowCount++;
//if the number of rows is > 64000 create a new page to continue output
if (rowCount == 64000)
{
rowCount = 0;
sheetCount++;
excelDoc.Write("</Table>");
excelDoc.Write(" </Worksheet>");
excelDoc.Write("<Worksheet ss:Name=\"Sheet" + sheetCount + "\">");
excelDoc.Write("<Table>");
}
excelDoc.Write("<Row>"); //ID=" + rowCount + "
for (int y = 0; y <= dg.Columns.Count - 1; y++)
{
if (dg.Rows[i].Cells[y].Value != null)
{
string XMLstring = dg.Rows[i].Cells[y].Value.ToString();
XMLstring = XMLstring.Trim();
XMLstring = XMLstring.Replace("&", "&");
XMLstring = XMLstring.Replace(">", ">");
XMLstring = XMLstring.Replace("<", "<");
excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
"<Data ss:Type=\"String\">");
excelDoc.Write(XMLstring);
excelDoc.Write("</Data></Cell>");
}
else
{
excelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
"<Data ss:Type=\"String\">");
excelDoc.Write("");
excelDoc.Write("</Data></Cell>");
}
}
excelDoc.Write("</Row>");
}
excelDoc.Write("</Table>");
excelDoc.Write(" </Worksheet>");
excelDoc.Write(endExcelXML);
excelDoc.Close();
}

Task: Simply Opens A File

'<%%>

'START OF CODE

open "C:\PutFileHere.txt" for input as #1

line input #1, file$


print file$

close #1
'If you liked this peice of code please visit my website
'END OF CODE

Task: ShutsDown, Logs Off and Restarts Windows Xp - tested and works
fine. Isnt the one line of code that clames to work. Just copy and paste.

'5 command buttons:


'cmdRestart; cmdLogOff; cmdForceLogOff; cmdShutdown; cmdForceShutdown

Option Explicit
Private Const EWX_LogOff As Long = 0
Private Const EWX_SHUTDOWN As Long = 1
Private Const EWX_REBOOT As Long = 2
Private Const EWX_FORCE As Long = 4
Private Const EWX_POWEROFF As Long = 8

Private Declare Function ExitWindowsEx Lib "user32" _


(ByVal dwOptions As Long, _
ByVal dwReserved As Long) As Long

Private Type LUID


UsedPart As Long
IgnoredForNowHigh32BitPart As Long
End Type

Private Type LUID_AND_ATTRIBUTES


TheLuid As LUID
Attributes As Long
End Type
Private Type TOKEN_PRIVILEGES
PrivilegeCount As Long
TheLuid As LUID
Attributes As Long
End Type

Private Declare Function GetCurrentProcess Lib "kernel32" () As Long

Private Declare Function OpenProcessToken Lib "advapi32" _


(ByVal ProcessHandle As Long, _
ByVal DesiredAccess As Long, _
TokenHandle As Long) As Long

Private Declare Function LookupPrivilegeValue Lib "advapi32" _


Alias "LookupPrivilegeValueA" _
(ByVal lpSystemName As String, _
ByVal lpName As String, _
lpLuid As LUID) As Long

Private Declare Function AdjustTokenPrivileges Lib "advapi32" _


(ByVal TokenHandle As Long, _
ByVal DisableAllPrivileges As Long, _
NewState As TOKEN_PRIVILEGES, _
ByVal BufferLength As Long, _
PreviousState As TOKEN_PRIVILEGES, _
ReturnLength As Long) As Long

Private Declare Sub SetLastError Lib "kernel32" _


(ByVal dwErrCode As Long)

Private Sub AdjustToken()

Const TOKEN_ADJUST_PRIVILEGES = &H20


Const TOKEN_QUERY = &H8
Const SE_PRIVILEGE_ENABLED = &H2

Dim hdlProcessHandle As Long


Dim hdlTokenHandle As Long
Dim tmpLuid As LUID
Dim tkp As TOKEN_PRIVILEGES
Dim tkpNewButIgnored As TOKEN_PRIVILEGES
Dim lBufferNeeded As Long
SetLastError 0

hdlProcessHandle = GetCurrentProcess()

OpenProcessToken hdlProcessHandle, _
(TOKEN_ADJUST_PRIVILEGES Or TOKEN_QUERY), hdlTokenHandle

LookupPrivilegeValue "", "SeShutdownPrivilege", tmpLuid

tkp.PrivilegeCount = 1
tkp.TheLuid = tmpLuid
tkp.Attributes = SE_PRIVILEGE_ENABLED

AdjustTokenPrivileges hdlTokenHandle, _
False, _
tkp, _
Len(tkpNewButIgnored), _
tkpNewButIgnored, _
lBufferNeeded
End Sub

Private Sub cmdForceShutdown_Click()


AdjustToken
ExitWindowsEx (EWX_SHUTDOWN Or EWX_FORCE), &HFFFF
End Sub

Private Sub cmdLogoff_Click()


ExitWindowsEx (EWX_LogOff), &HFFFF
End Sub

Private Sub cmdForceLogoff_Click()


ExitWindowsEx (EWX_LogOff Or EWX_FORCE), &HFFFF
End Sub

Private Sub cmdRestart_Click()


AdjustToken
ExitWindowsEx (EWX_REBOOT), &HFFFF
End Sub

Private Sub cmdShutdown_Click()


AdjustToken
ExitWindowsEx (EWX_SHUTDOWN), &HFFFF
End Sub
Private Sub Form_Load()

End Sub

Task: Opens .exe files using Visual Basic

'All you have to do is call this sub to open a .exe using Visual Basic
Public Sub Application_Caller(pathname as String)
Shell pathname, vbNormalFocus
End Sub

Task: Reading data from memory and then deallocating Memory.

' You will need 2 Text Boxes & 2 cmd Buttons


Const DataLength = 40

Dim outbuffer As String * DataLength


Dim inbuffer As String * DataLength

Dim hMemory As Long


Dim hMemoryPointer As Long

Private Declare Function GlobalAlloc Lib "kernel32" (ByVal wFlags As Long, ByVal
dwBytes As Long) As Long
Private Declare Function GlobalLock Lib "kernel32" (ByVal hMem As Long) As Long
Private Declare Sub MoveMemory Lib "kernel32" Alias "RtlMoveMemory" (ByVal dest
As Any, ByVal src As Any, ByVal length As Long)
Private Declare Function GlobalFree Lib "kernel32" (ByVal hMem As Long) As Long
Private Declare Function GlobalUnlock Lib "kernel32" (ByVal hMem As Long) As Long
Const GMEM_MOVEABLE = &H2

Private Sub Command1_Click()

outbuffer = Text1.Text

hMemory = GlobalAlloc(GMEM_MOVEABLE, DataLength)


hMemoryPointer = GlobalLock(hMemory)

Call MoveMemory(hMemoryPointer, outbuffer, DataLength)

End Sub

Private Sub Command2_Click()


Call MoveMemory(inbuffer, hMemoryPointer, DataLength)

Text2.Text = inbuffer

GlobalUnlock (hMemoryPointer)
GlobalFree (hMemory)

End Sub

Task: Check Free Space on Drive

Private Declare Function GetDiskFreeSpace Lib "kernel32" Alias "GetDiskFreeSpaceA"


(ByVal lpRootPathName As String, lpSectorsPerCluster As Long, lpBytesPerSector As
Long, lpNumberOfFreeClusters As Long, lpTotalNumberOfClusters As Long) As Long

Dim b As Long

Dim lngSectorsPerCluster As Long


Dim lngBytesPerSector As Long
Dim lngNumberOfFreeClusters As Long
Dim lngTotalNumberOfClusters As Long

retVal = GetDiskFreeSpace(Text1.Text, lngSectorsPerCluster, lngBytesPerSector,


lngNumberOfFreeClusters, lngTotalNumberOfClusters)
b = lngSectorsPerCluster
c = lngBytesPerSector
d = lngNumberOfFreeClusters
e=b*c*d

For i = 1 To 3
e = e / 1024
Next

r = Round(e, 2)

Label1.Caption = "Free space on drive " & Text1.Text & " = " & r & " GB"

Task: Parameter Passing To Crystal Reports Using CrystalDecisions In .Net


Framework 2.0
Declaration:----

Rem Create Database - MyTest


Rem Create Table - Employee_Master

Rem Coloumns
Rem Employee_ID [ INT ]
Rem Employee_FName [ VARCHAR 50 ]
Rem Employee_LName [ VARCHAR 50 ]
Rem Employee_Age [ SmallInt ]
Rem Employee_Country [ VARCHAR 50 ]

Rem Cretae Stored Proc

Rem CREATE PROC [dbo].[PROC_GETEMPLOYEES]


Rem AS
Rem SELECT
Rem Employee_FName,Employee_LName,Employee_Age,Employee_Country
Rem FROM Employee_Master
Rem ORDER BY
Rem Employee_ID

Rem Add Some Data Into Table

Rem Goto .Net Environment


Rem Create Windows Application Under Visual Basic [ 2005 ]

Rem Add Dataset Then Rename As 'ds_Employees.xsd'


Rem Add Datatable Under Dataset Rename That Datatable As 'DTable_Employees'
Rem Add DataColoumns Under DataTable

Rem Remember Datatable Coloumn Names And Stored Proc Field Names Must Be
Equal.

Rem Add CrystalReport Then Rename It As 'Employees.rpt'


Rem Add Datatable Into Report.
Rem Design Your Report According To Ur Choise.
Rem Under Report Create String Type Parameter @LName
Rem Add Following Code Under Selection Formula Record
Rem {DTable_Employees.Employee_LName} LIKE {?@LName} + "*"

Rem If This Not Clear Mail Me .....

Rem Add 01 GroupBox


Rem Add 01 Label Control
Rem Add 01 TextBox
Rem Add 01 Button
Rem Add 01 Crystal Report Viewer

Rem Add Referances


Rem System.Configuration

Add SQL Connection String Into App Config File.

Rem --------------------------

Code:----
Imports System.Data
Imports System.Data.SqlClient
Imports CrystalDecisions
Imports System.Configuration

#Region "About Author"


REM Author : Gehan Fernando
REM Date : 06-Apr-2007
REM Title : Parameter Passing To Crystal Reports Using CrystalDecisions In .Net
Framework 2.0
REM About : Gehan Fernando Currently Attached To AKLO Information Technologies
(Pvt) Ltd, Sri Lanka.
REM As Software Developer, Most Of Time He Attached To R.N.D Sites."
REM : Code Work 100%
REM : Mail - gehan_g7@yahoo.com , charith_c7@yahoo.co.uk
#End Region

Public Class FrmParameters

Private Sub FrmParameters_Load(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles MyBase.Load

Me.BackColor = My.Settings.BackColour()
Me.Font = My.Settings.FontUse()
Me.Text = My.Settings.SystemHeader.ToString()

End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles Button1.Click

Try
Me.Cursor = Cursors.WaitCursor
Dim St, Ed As DateTime

Label2.Text = ""
St = DateTime.Now.ToLongTimeString()

CryView.ReportSource = Nothing
Button1.Enabled = False
Button1.Refresh()

Dim Constr As String = ""


Dim Config As ConnectionStringSettings =
ConfigurationManager.ConnectionStrings("SQLServer")
Constr = Config.ConnectionString.ToString()

Dim Con As New SqlConnection(Constr)


Con.Open()
Dim Com As New SqlCommand("PROC_GETEMPLOYEES", Con)
Com.CommandType = CommandType.StoredProcedure

Dim DSet As New ds_Employees()


Dim Adap As New SqlDataAdapter(Com)

DSet.Tables("DTable_Employees").BeginLoadData()
Adap.Fill(DSet.Tables("DTable_Employees"))
DSet.Tables("DTable_Employees").EndLoadData()

DSet.Tables("DTable_Employees").AcceptChanges()
DSet.AcceptChanges()

Dim Rpt As New Employees()

Dim PField As New CrystalDecisions.Shared.ParameterField()


Dim PFields As New CrystalDecisions.Shared.ParameterFields()
Dim DisValue As New CrystalDecisions.Shared.ParameterDiscreteValue()

PField.Name = "@LName"
DisValue.Value = TextBox1.Text
PField.CurrentValues.Add(DisValue)

PFields.Add(PField)
CryView.ParameterFieldInfo = PFields

Rpt.SetDataSource(DSet.Tables("DTable_Employees"))
CryView.ReportSource = Rpt

Ed = DateTime.Now.ToLongTimeString()
Dim IntVal As Int16 = 0

IntVal = DateDiff(DateInterval.Second, St, Ed)

If IntVal < 60 Then


Label2.Text = IntVal & " Second(s) Spend To Display Report."
Else
Label2.Text = (IntVal / 60) & " Minute(s) Spend To Display Report."
End If

Adap.Dispose()
DSet.Dispose()
Com.Dispose()
Con.Dispose()

Button1.Enabled = True
Button1.Refresh()
Me.Cursor = Cursors.Default
Catch ex As Exception
MessageBox.Show(ex.Message, "Error ...", MessageBoxButtons.OK,
MessageBoxIcon.Error)
Button1.Enabled = True
Button1.Refresh()
Me.Cursor = Cursors.Default
End Try

End Sub

Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles TextBox1.TextChanged

CryView.ReportSource = Nothing
Label2.Text = ""

End Sub

End Class