Wednesday, December 15, 2010

VB.NET Capture Client Computer NAME

 Imports System.Net

Dim computer_name() As String
        computer_name = Split(System.Net.Dns.GetHostEntry(Request.ServerVariables("remote_addr")).HostName, ".")
        Response.Write(computer_name(0).ToUpper)

OR

Dim strComputerName As String
        Dim host As System.Net.IPHostEntry
        host = System.Net.Dns.GetHostEntry(Request.ServerVariables.Item("REMOTE_HOST"))
        strComputerName = host.HostName
        Response.Write(strComputerName)

VB.NET Read from TEXT File

 Dim FILENAME As String = "c:\IP.txt"

        Dim objStreamReader As StreamReader
        objStreamReader = File.OpenText(FILENAME)
        Dim contents As String = objStreamReader.ReadToEnd()
        Button1.Text = contents
        objStreamReader.Close()

VB.NET Insert into TEXT File

Imports System.IO

Dim FILENAME As String = Server.MapPath("IP.txt")
                          OR
Dim FILENAME As String = "c:\IP.txt"

            Dim objStreamWriter As StreamWriter
            objStreamWriter = File.AppendText(FILENAME)
            objStreamWriter.WriteLine("External ip :" & externalip)
            objStreamWriter.WriteLine("Local ip    :" & localipaddresses)
            objStreamWriter.WriteLine("Remote ip   :" & strip)
            objStreamWriter.WriteLine("DateTime    :" & DateTime.Now)
            objStreamWriter.WriteLine("----------------------------------")
            objStreamWriter.Close()
            Dim objStreamReader As StreamReader
            objStreamReader = File.OpenText(FILENAME)
            Dim contents As String = objStreamReader.ReadToEnd()
            objStreamReader.Close()

Monday, December 13, 2010

VB.NET Getting Local ip of Client

Dim hostname As String

        hostname = System.Net.Dns.GetHostName()
        Dim localipaddresses As New IPHostEntry
        localipaddresses = Dns.GetHostEntry(hostname)


        Response.Write("Your Local IP Address is:  " & localipaddresses.AddressList(0).ToString() & "</em><br />")
       

Thursday, December 9, 2010

WPF Run Exe and Open URL in a Browser Window

System.Diagnostics.Process.Start("D:\2010-2011\smcen2010\optics2010.exe")


System.Diagnostics.Process.Start("http://122.160.43.248/labpendency")

Wednesday, December 8, 2010

VB.NET Capture Client Machine Remote IP

  1. Dim strClientIP As String
  2. strClientIP = Request.UserHostAddress()
  3. Response.Write(strClientIP)

VB.NET Run exe

Dim startInfo As System.Diagnostics.ProcessStartInfo
Dim pStart As New System.Diagnostics.Process

startInfo = New System.Diagnostics.ProcessStartInfo("C:\file.exe")

pStart.StartInfo = startInfo
pStart.Start()
pStart.WaitForExit()
'Your code will halt until the exe file has executed.

Wednesday, October 27, 2010

VB.NET (Wndows) Fill Datagrid with Access table

Imports System.Data.OleDb

Dim oConn As OleDbConnection
        Dim oComm As OleDbDataAdapter
        Dim sConn As String
        Dim sComm As String
        Dim oDataSet As New DataSet
        sConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\avs.mdb;Persist Security Info=False"
     
        oConn = New OleDbConnection(sConn)
        sComm = "select distinct party from avst"
        oComm = New OleDbDataAdapter(sComm, oConn)
        oComm.Fill(oDataSet, "avst")

        DataGridparty.DataSource = oDataSet.Tables("avst").DefaultView
        DataGridparty.Refresh()

Tuesday, October 12, 2010

VB.NET Creating Zip File

 //Imports System.IO

Dim emptyZip As Byte() = {80, 75, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
        Dim oApp As Object

        'Destination Zip File Name Here
        File.WriteAllBytes("c:\avs.zip", emptyZip)
        oApp = CreateObject("Shell.Application")

        'Source File Name
        oApp.Namespace("c:\avs.zip").CopyHere("c:\avs.mdb")
        MsgBox("Zipped..")

Wednesday, September 22, 2010

VB 6.0 Create Backup of a Table

mdbpassword = "9990513523"
file2 = "account.mdb"
cn3.Open "Provider=MSDataShape.1;Data Provider = Microsoft.Jet.OLEDB.3.51;Jet OLEDB:Database Password=" & mdbpassword & ";data source=" & file2
c = InputBox("Enter Table Name to Save::::Use only Numbers and Alphabets..", "Save Table")
If c = "" Then
cn3.Close
Exit Sub
Else
cn3.Execute "select * into [" & c & "] from attendance"
cn3.Execute "delete values from attendance"
cn3.Close
MsgBox "Table " & c & " Saved", vbInformation, "Saving Information..."
Att.Refresh
End If

VB 6.0 Show All Table Names in ComboBox

Dim con As New ADODB.Connection
Dim rs As New ADODB.Recordset
mdbpassword = "9990513523"
file2 = "account.mdb"

con.Open "Provider=MSDataShape.1;Data Provider = Microsoft.Jet.OLEDB.3.51;Jet OLEDB:Database Password=" & mdbpassword & ";data source=" & file2

Set rs = con.OpenSchema(adSchemaTables)

While Not rs.EOF
If rs("TABLE_TYPE") = ("TABLE") Then
Combo1.AddItem rs!TABLE_NAME

End If
rs.MoveNext
Wend

Tuesday, September 21, 2010

VB.NET Rename a File

//imports System.IO

Dim ddl As String
ddl = DropDownList1.Text
My.Computer.FileSystem.RenameFile("d:\kapil\uploaded\updatemaster.mdb", ddl & ".mdb")

Monday, September 20, 2010

VB.NET Download/Upload From FTP

//download

Private Sub ftpp()
Dim localFile As String = "C:\Inetpub\wwwroot\order\images\updatemaster.mdb"
Dim remoteFile As String = "/kapil/updatemaster.mdb"
Dim host As String = "ftp://ftp.sdmftp.com"
Dim URI As String = host & remoteFile
Dim username As String
Dim password As String
username = "rpc"
password = "rpc123"
Dim ftp As System.Net.FtpWebRequest = CType(FtpWebRequest.Create(URI), FtpWebRequest)
ftp.Credentials = New System.Net.NetworkCredential(username, password)
ftp.KeepAlive = False
ftp.UseBinary = True
ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile
Using response As System.Net.FtpWebResponse = _
CType(ftp.GetResponse, System.Net.FtpWebResponse)
Using responseStream As IO.Stream = response.GetResponseStream
'loop to read & write to file
Using fs As New IO.FileStream(localFile, IO.FileMode.Create)
Dim buffer(2047) As Byte
Dim read As Integer = 0
Do
read = responseStream.Read(buffer, 0, buffer.Length)
fs.Write(buffer, 0, read)
Loop Until read = 0 'see Note(1)
responseStream.Close()
fs.Flush()
fs.Close()
End Using
responseStream.Close()
End Using
response.Close()
End Using
MsgBox("downloaded")
End Sub

//Upload
Private Sub ftppu()
Dim localFile As String = "C:\Inetpub\wwwroot\order\images\updatemaster.mdb"
Dim remoteFile As String = "/kapil/updatemaster.mdb"
Dim host As String = "ftp://ftp.sdmftp.com"
Dim URI As String = host & remoteFile
Dim username As String
Dim password As String
username = "rpc"
password = "rpc123"

Dim reqObj As FtpWebRequest = WebRequest.Create(URI)
reqObj.Method = WebRequestMethods.Ftp.UploadFile
reqObj.Credentials = New NetworkCredential(username, password)
Dim streamObj As FileStream = File.OpenRead(localFile)
Dim buffer(streamObj.Length) As Byte
streamObj.Read(buffer, 0, buffer.Length)
streamObj.Close()
streamObj = Nothing
reqObj.GetRequestStream().Write(buffer, 0, buffer.Length)
reqObj = Nothing
End Sub

Saturday, September 18, 2010

Password Protected Internet Explorer

Start Internet Explorer, then go to the 'Tools' heading on the toolbar. Click on 'Internet Options.'

Select the 'Content' tab.

Click on the 'Enable' button.

Make your access selections, then click on 'OK.'

Choose a password when Internet Explorer asks you to do so. Type the password into the provided field.


Wednesday, September 15, 2010

VB.NET Add Title to Your aspx Page


//Go To Source view from Design View and at the Top of the Page Just add this red underlined line

VB.NET Place ICON of your website into Browser AddressBar


//Go to Source Page from Design View and write this line after "head tag"
// Where folder path is C:/inetpub/wwwroot/Yourwebsitefolder/images/n.ico


VB.NET Marquee

Thursday, September 9, 2010

VB.NET Web.Config File with ConnectionString


//For Access
//Imports System.Data.Oledb

Dim cmd As New OleDbCommand
Dim cnmdb As OleDbConnection = New OleDbConnection(ConfigurationSettings.AppSettings("ConnectionStringmdb"))
cnmdb.Open()
cmd = New OleDbCommand("insert into mainmaster values('" & txtname.Text & " ','" & txtcontact.Text & "','" & txtbilladd.Text & "',)", cnmdb)

cmd.ExecuteNonQuery()

//For Sqlserver
//Imports System.Data.Sqlclient

Dim cmd As New SqlCommand
Dim cn As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
cn.Open()
cmd = New SqlCommand("insert into mainmaster values('" & txtname.Text & " ','" & txtcontact.Text & "','" & txtbilladd.Text & "',)", cn)

cmd.ExecuteNonQuery()


VB.NET GridView Extract Selected Row Value


//on Download Button Click (Download Selected checkbox row index file)

Dim CheckBox As CheckBox

For Each row As GridViewRow In GridView1.Rows
CheckBox = CType(row.FindControl("checkbox1"), CheckBox)
If CheckBox.Checked Then
Response.AppendHeader("Content-Disposition", "attachment; filename=" + row.Cells(1).Text)

Response.TransmitFile("f:/soft/KapiL/uploaded/" + row.Cells(1).Text)
//Response.TransmitFile(Server.MapPath("~/uploaded/" + row.Cells(1).Text))

Response.End()
End If
Next

Monday, September 6, 2010

VB.NET Send Mail



imports System.Net.Mail
Dim mail As New MailMessage()
mail.From = New MailAddress("" & txtfrm.Text & "")
mail.To.Add("" & txtto.Text & "")

mail.Subject = "" & txtsub.Text & ""
mail.Body = "" & txtmsg.Text & ""
mail.IsBodyHtml = True

Dim file As String = "" & txtatch.Text & ""
If Not file = "" Then
Dim MsgAttach As New Attachment(file)
mail.Attachments.Add(MsgAttach)
End If

Dim smtp As New SmtpClient("mail.suprol.com")
smtp.Send(mail)
lblmail.Text="mail sent successfully..!!"
//With a copy send to mailsender with date time
Dim mail As New MailMessage()
Dim mailrep As New MailMessage()

mail.From = New MailAddress("" & txtfrm.Text & "")
mail.To.Add("" & txtto.Text & "")

mailrep.From = New MailAddress("" & txtfrm.Text & "")
mailrep.To.Add("" & txtfrm.Text & "")
mailrep.Subject = "Mail sent To" & "" & " " & txtto.Text & ""
mailrep.Body = "Your Mail successfully Sent To" & " " & "" & txtto.Text & "" & " " & "Date and Time was : " & " " & "" & DateTime.Now() & "" & " " & "With Attachment File Name :" & " " & "" & txtatch.Text & ""
mailrep.IsBodyHtml = True


mail.Subject = "" & txtsub.Text & ""
mail.Body = "" & txtmsg.Text & ""
mail.IsBodyHtml = True
Dim filerep As String = "" & txtatch.Text & ""
Dim file As String = "" & txtatch.Text & ""
If Not file = "" Then
Dim MsgAttach As New Attachment(file)
mail.Attachments.Add(MsgAttach)
mailrep.Attachments.Add(MsgAttach)
End If

Dim smtp As New SmtpClient("mail.suprol.com")
smtp.UseDefaultCredentials = False
smtp.Port = 2525
smtp.Send(mail)
smtp.Send(mailrep)

VB.NET Upload & Download a file

// UPLOAD
//drag fileupload control for path and a button for upload

Dim file As String
file = Path.GetFileName(FileUpload1.FileName)
FileUpload1.SaveAs("C:\Inetpub\wwwroot\order\images\" + file)
//it is better to save file in another folde rather than the inetpub JUST LIKE BELOW
FileUpload1.SaveAs("d:\kapil\images\" + file)
lblupload.Text = "File Upload Complete...."
labelsize.text=FileUpload1.PostedFile.ContentLength

//DOWNLOAD

Response.AppendHeader("Content-Disposition", "attachment; filename=ecc1.jpg")
Response.TransmitFile(Server.MapPath("~/images/ecc1.jpg"))
//Response.TransmitFile("d:/kapil/images/ecc1.jpg")
Response.End()

//By Default, maximum allowed size for file is 4MB. To allow files larger than the default of 4MB, one need to change the web.config file(in system.web TAB).There is a parameter called maxRequestLength which takes value in the KB.
 


//1048576 is around 1GB

Monday, August 30, 2010

VB.NET Export GridView to EXCEL

//FIRST WAY

If GridView1.Rows.Count.ToString + 1 < 65536 Then
GridView1.AllowPaging = "False"
bindgrid1()
Dim tw As New StringWriter()
Dim hw As New System.Web.UI.HtmlTextWriter(tw)
Dim frm As HtmlForm = New HtmlForm()
Response.ContentType = "application/vnd.ms-excel"
Response.AddHeader("content-disposition", "attachment;filename=" & txtfile.Text & ".xls") Response.Charset = "" EnableViewState = False Controls.Add(frm) frm.Controls.Add(GridView1) frm.RenderControl(hw) Response.Write(tw.ToString()) Response.End()
GridView1.AllowPaging = "True"
bindgrid1()
Else
lblerror.Text = "Too many rows - Export to Excel not possible"
End If

//SECOND WAY


Response.Clear()
Response.Buffer = True
Response.ContentType = "application/vnd.ms-excel"
Response.Charset = ""
Me.EnableViewState = False
Dim oStringWriter As New System.IO.StringWriter
Dim oHtmlTextWriter As New System.Web.UI.HtmlTextWriter(oStringWriter)

DataGrid1.RenderControl(oHtmlTextWriter)

Response.Write(oStringWriter.ToString())
Response.[End]()

End Sub

Friday, August 27, 2010

VB6.0 Table EXPORT to EXCEL

Private Sub Command3_Click()

Dim db As Database
Set db = OpenDatabase(App.Path & "\db1.mdb")
db.Execute "SELECT * INTO [Excel 8.0;DATABASE=d:\test.XLS].[atmmsttable] FROM [atmmstdatabase]"
Set db = Nothing
MsgBox "Saved XLS to D:\test.xls", vbInformation, "Complete"


End Sub

VB6.0 Changing Random Color

Private Sub Timer2_Timer()

Static A
A = A + 10: If A > 510 Then A = 0
//To change the effect, put other numbers insted of the 0 below.
//You can also replace places between the 'Abs(A - 256)' and one of thezeros below.
//To decrease the pace of the animation, increase the Timer intervalproperty.
cmdadditem.BackColor = RGB(Abs(A - 256), 100, 100)
cmdaddch.BackColor = RGB(Abs(A - 256), 50, 200)
cmdaddtocurrent.BackColor = RGB(Abs(A - 256), 150, 50)

End Sub

VB6.0 Remove Duplicates From ListBox

Private Sub Command6_Click()

Dim i As Long
Dim j As Long
With List1
For i = 0 To .ListCount - 1
For j = .ListCount To (i + 1) Step -1
If .List(j) = .List(i) Then
.RemoveItem j
End If
Next
Next
End With

Dim k As Long
Dim l As Long
With List2
For k = 0 To .ListCount - 1
For l = .ListCount To (k + 1) Step -1
If .List(l) = .List(k) Then
.RemoveItem l
End If
Next
Next
End With

End Sub

VB6.0 Fill ListBox with Column Values

Call cnOPEN //ConnectionString Function
rs.Open "select * from mainmaster", cn, adOpenDynamic, adLockOptimistic
rs.MoveFirst
Do While Not rs.EOF
List1.AddItem rs!mainpager
rs.MoveNext
Loop

VB6.0 MSAccess ConnectionString with Database Password

Public Sub cnOPEN()
mdbpassword = "k12i07s2002s"
mdbname = "bojpr2010.mdb"
If cn.State = 1 Then
cn.Close
End If
cn.Mode = adModeReadWrite
cn.Open "Provider=MSDataShape.1;Data Provider = Microsoft.Jet.OLEDB.3.51;Jet OLEDB:Database Password=" & mdbpassword & ";data source=" & App.Path & "\" & mdbname
End Sub

VB6.0 Work with FTP

//go to Project->Components->Select 'Microsoft Internet Transfer Controls 6.0(sp4)' and - 'Microsoft Internet Control'
//Drag Inet and webbrowser control

//Open FTP

WebBrowser1.Navigate "ftp://rpc:rpc123@sdmftp.com"
//where rpc and rpc123 are username and password


//UPLOAD to FTP

Inet1.Execute "ftp://rpc:rpc123@sdmftp.com", "put c:\npoh2010.zip npoh2010.zip "
Do While Inet1.StillExecuting: DoEvents: Loop
MsgBox "uploading Complete", vbInformation

//DOWNLOAD from FTP

Inet1.Execute "ftp://rpc:rpc123@sdmftp.com", "get dev.zip c:\dev.zip"
Do While Inet1.StillExecuting: DoEvents: Loop
MsgBox "Downloading Complete", vbInformation

//Open FTP with Shell Command

//declare this function

Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" (ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long

//open by default browser
ShellExecute 0, "open", "ftp://rpc:rpc123@sdmftp.com", vbNullString, vbNullString, 1
//open by selected browser
ShellExecute 0, "open", "C:\Program Files\opera\opera.exe", "ftp://rpc:rpc123@sdmftp.com", vbNullString, 1

VB6.0 Open Browser

//go to project->Components->select 'Microsoft internet controls'
// Drag webBrowser control



WebBrowser1.Navigate "http://www.google.com"

VB6.0 Only Digit in Textbox

Private Sub Text1_KeyPress(KeyAscii As Integer)

Dim str As String

str = "0123456789"
If KeyAscii > 26 Then
If InStr(str, Chr(KeyAscii)) = 0 Then
KeyAscii = 0
End If
End If
End Sub

VB6.0 Open EXE File

//With Shell Command

Private Sub Command1_Click()
Dim Ret As Variant
Ret = Shell("D:\kapil\projects\newdatastore\Dstore.exe", vbNormalFocus)
End Sub

//Without Shell Command

Private Sub Command2_Click()
Dim oWord
On Error Resume Next

Set oWord = GetObject("Word.Application")
If oWord Is Nothing Then
Set oWord = CreateObject("Word.Application")
End If

If oWord Is Nothing Then
MsgBox "Could not start Word"
Else
oWord.Visible = True
End If
End Sub

VB6.0 Marquee



Private Sub Form_Paint()

Label1.Left = Frame1.Width
Timer1.Interval = 1

End Sub

Private Sub Timer1_Timer()

Label1.Left = Label1.Left - 25
If Label1.Left < Frame1.Left - Label1.Width Then Label1.Left = Frame1.Width

End Sub

//Timer Interval set to 1

VB.NET : Fill DropDownList With a Column Values From The Table



//When Connection string present in web.config file

If Not IsPostBack Then

Dim cn As New SqlConnection
Dim cmd As New SqlCommand
Dim dr As SqlDataReader

cn = New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
cn.Open()
cmd.Connection = cn
cmd.CommandText = "SELECT DISTINCT name as 'named' FROM master"
dr = cmd.ExecuteReader()
While dr.Read
DropDownList1.Items.Add(dr.Item("named"))
End While
cn.Close()

end if

VB6 : ComboBox Duplicate Item Removed

Private Sub Combo1_Click()

Dim s As String
Dim i As Integer

s = Combo1.Text

For i = Combo1.ListCount - 1 To 0 Step -1
If Combo1.List(i) = s And Combo1.ListIndex <> i Then Combo1.RemoveItem i
Next i

End Sub

Stop Browsing

Log into the user account you want to restrict.
Go to "Internet Options" and click on the "Connections" tab. Click on the "LAN Settings" button and put a tick in the box next to "use a proxy server for your LAN". Type into the "Address" box:

127.0.0.1

Click "OK" then "OK" again.

This will make the users account you need to restrict unable to access the internet.


You can use a Group Policy setting to remove the "connections" tab in "internet options" to prevent the settings being changed back.

Click "Start" > "Run" then type:

gpedit.msc

Click Computer Configuration > Administrative Templates > Windows Components > Internet Explorer > Internet Control Panel > Disable the Connections page, and click Enabled, click Apply then OK.

This is easily reversable.