Archive for May, 2006

Posting data to a web-page with VB.net

I’ve been doing some tryouts on posting data to a xml-rpc.php page – and, I found it quite difficult to find info on the Internet on how to post to a webpage using vb.net. So, I gathered some from around, and made this simple thing:

Public Function PostXML(ByVal url As String, ByVal strXML As String) As String

Dim bytes() As Byte = System.Text.Encoding.UTF8.GetBytes(strXML)

Dim request As HttpWebRequest = CType(WebRequest.Create(url), HttpWebRequest)

Dim returnstring As String = Nothing

request.Method = WebRequestMethods.Http.Post

request.ContentLength = bytes.Length

request.ContentType = “text/xml”

Using requeststream As Stream = request.GetRequestStream

requeststream.Write(bytes, 0, bytes.Length)

End Using

Dim response As HttpWebResponse = CType(request.GetResponse, HttpWebResponse)

If Not response.StatusCode = HttpStatusCode.OK Then

Return “Failed connection to xml-rpc.”

Else

Dim receivestream As Stream = response.GetResponseStream

Dim encode As System.Text.Encoding = System.Text.Encoding.GetEncoding(“utf-8″)

‘ Pipe the stream to a higher level stream reader with the required encoding format.

Dim readStream As New StreamReader(receivestream, encode)

Dim read(256) As [Char]

‘ Read 256 charcters at a time .

Dim count As Integer = readStream.Read(read, 0, 256)

While count > 0

‘ Dump the 256 characters on a string and display the string onto the console.

Dim str As New [String](read, 0, count)

returnstring += str

count = readStream.Read(read, 0, 256)

End While

Return returnstring

‘ Release the resources of stream object.

readStream.Close()

 

End If

response.Close()

request = Nothing

End Function

Comments

Format Datetime in vb.net

I can never find out just how to format datetime using vb.net. But, found this page, which I think is helpful.

Comments (1)

Sending mails using .NET 2.0

Sending mails using .NET 2.0 is extremely easy. Thought I’d give a quick example, this one with a file-attachement.

Imports

System.Net.Mail

Private Sub SendEmail(ByRef FileToSend As String)

‘Creating the SMTP-connection (this one stored in web.config)
Dim smtp As New SmtpClient(ConfigurationManager.AppSettings(“smtpHost”).ToString)

‘Creating the actual mail-object
Dim mail As New MailMessage

‘The attachment (reference to a file)
Dim att As New Attachment(FileToSend)

‘If errors should happen
Try

‘Send mail from this address
mail.From = New MailAddress(“sender@domain.tld”)

‘Send mail to this address
mail.To.Add(“mailto@domain.tld”)

‘Send BCC-copy to this address (use CC like this)
mail.Bcc.Add(“someone@someotherdomain.tld”)

‘Adding the subject (taken from a text-box)
mail.Subject = txtSubject.Text

‘Adding the body-text (taken from a text-box
mail.Body = txtContent.Text

‘Add the attachment
mail.Attachments.Add(att)

‘Send the e-mail using the SMTP-connection
smtp.Send(mail)

Catch ex As Exception

‘If errors
Throw New System.Exception(ex.Message, ex.InnerException)

End Try

‘Cleaning up
smtp = Nothing
mail.Dispose()
mail =
Nothing

End Sub

Thats it. Read more about system.net.mail here.

Comments

Creating temporary and random filenames

Just found a blog on how easy it was to generate temporary and/or random file-names using C# – thought I’d translate it into vb.net:

Imports System.IO

Private Function GetRandomJPGFileName() As String
   Return String.Format(“{0}.{1}”, Path.GetFileNameWithoutExtension(Path.GetRandomFileName).ToString, “jpg”)
End Function

Private Function GetTempJPGFileName() As String
   Return String.Format(“{0}.{1}”, Path.GetFileNameWithoutExtension(Path.GetTempFileName).ToString, “jpg”)
End Function

Comments

FTP-client

Not long ago a new colleague joined our office, and i noticed the great FTP-client FileZilla.

So, if you’re in need of a solid and free ftp-client you should consider FileZilla. Filezilla also features a FTP-server (which I have’nt had time to test).

Comments

Tech Ed Europe – for IT-professionals and developes | Site now open

Microsoft’s premier EMEA conference designed to provide developers with deep dive technical training, information and community resources focusing on building software solutions with Microsoft development tools.

Microsoft’s premier EMEA conference designed to provide IT professionals with technical training, information and community resources to build, plan, deploy and manage the secure connected enterprise.

Comments

Create scheduled task using Visual Basic .NET and System.Diagnostics.Process

Private Function CreateScheduledTask(ByVal strName As String, ByVal StartTime As DateTime) As Boolean
Try
If EncoderTaskRunning() = False And EncoderTaskExists(“StartEncoder”) = False Then

Dim sCreateTask As New System.Diagnostics.Process
sCreateTask.StartInfo.FileName = “c:\windows\system32\schtasks.exe”
sCreateTask.StartInfo.Arguments = “/CREATE /sc ONCE /ru runasusername /rp runasuserpassword /TN ” & strName & ” /TR c:\windows\system32\cmd.exe /ST ” & StartTime & “”
sCreateTask.StartInfo.RedirectStandardOutput = True
sCreateTask.StartInfo.RedirectStandardError = True
sCreateTask.StartInfo.UseShellExecute = False
sCreateTask.Start()
sCreateTask.WaitForExit()

If sCreateTask.ExitCode <> 0 Then
EventLog.WriteEntry(sCreateTask.StandardError.ReadToEnd)
Else
EventLog.WriteEntry(sCreateTask.StandardOutput.ReadToEnd)
End If

sCreateTask.Dispose()
sCreateTask = Nothing

Else

EventLog.WriteEntry(“Encoder is running – could not create scheduled task”)

End If

Catch ex As Exception
EventLog.WriteEntry(ex.Message.ToString)
End Try
End Function

Comments

Find out if scheduled task exists using Visual Basic .NET and System.Diagnostics.Process

rivate Function EncoderTaskExists(ByVal strTaskName As String) As Boolean
Try
Dim sCreateTask As New System.Diagnostics.Process
With sCreateTask
.StartInfo.FileName = “c:\windows\system32\schtasks.exe”
.StartInfo.Arguments = “/query /fo table”
.StartInfo.RedirectStandardOutput = True
.StartInfo.RedirectStandardError = True
.StartInfo.UseShellExecute = False
.Start()
.WaitForExit()
End With

If sCreateTask.ExitCode <> 0 Then
EventLog.WriteEntry(sCreateTask.StandardError.ReadToEnd)
Else
Dim sLine As String = sCreateTask.StandardOutput.ReadLine()
Do Until sLine Is Nothing
EncoderTaskExists = False

If InStr(sLine, strTaskName) > 0 Then
Return True
Exit Do
End If

sLine = sCreateTask.StandardOutput.ReadLine()

Loop

sLine = Nothing

End If
sCreateTask.Dispose()

sCreateTask = Nothing

Catch ex As Exception
EventLog.WriteEntry(ex.Message.ToString)
End Try
End Function

Comments

Basic arraylist search

Dim arl As New ArrayList

arl.Add(“jpg”)
arl.Add(“gif”)
arl.Add(“png”)
arl.Add(“psd”)
arl.Add(“tif”)
arl.Add(“tga”)
arl.Add(“pct”)
arl.Add(“dko”)

‘Sorting the array
arl.Sort()

‘Do a case Insensitive search
Dim idx As Integer = arl.BinarySearch(“psd”, New CaseInsensitiveComparer)

If idx >= 0 Then
    Trace.WriteLine(“Found searchstring at ” & idx & “. The lenght of the arraylist is: ” & arl.Count)
Else
    Trace.WriteLine(“Searchstring not found. The length of the arraylist is: ” & arl.Count)
End If

Comments

Create database with if not exists check

‘Creating basic connection-string to server
Dim sConnectionString As String = “server=” & server_ip & “;uid=” & user_id & “;pwd=” & password & “;database=”

‘Creating SQL-command object
Dim cmdNew As New SqlCommand

‘Creating connection to server
Dim cnConnection As New SqlConnection

‘Adding the connection-string to the connection
cnConnection.ConnectionString = sConnectionString

‘Creating sql-string to execute
Dim strSQL As String

‘Assigning connection to sql-command
cmdNew.Connection = cnConnection

‘Preparing SQL-string to check if database exists
strSQL = “SELECT count(*) as numbers FROM master..sysdatabases WHERE name=’” & database & “‘”

‘Adding the sql-command to sql-command object
cmdNew.CommandText = strSQL

Try

    ‘Opening SQL-connection
    cnConnection.Open()

    If cmdNew.ExecuteScalar > 0 Then

‘The database already exists
MessageBox.Show(“Database already exists.”, “Information”, MessageBoxButtons.OK, MessageBoxIcon.Information)

    Else
‘Preparing SQL-string to create database
strSQL = “IF NOT EXISTS (Select * From master..sysdatabases Where Name = ‘” & database & “‘) CREATE DATABASE ” & database

‘Adding the SQL-string to the SQL-command
cmdNew.CommandText = strSQL

‘Executing SQL-query
cmdNew.ExecuteNonQuery()

‘Everything went well..
MessageBox.Show(“Database created succesfully!”, “SQL Information”, MessageBoxButtons.OK, MessageBoxIcon.Information)
    End If
    ‘Closing SQL-connection
    cnConnection.Close()

    ‘Catching SQL-exceptions
Catch sqlEx As SqlException
    MessageBox.Show(sqlEx.Message, “SQL ERROR”, MessageBoxButtons.OK, MessageBoxIcon.Error)

    ‘Catching remaining exceptions
Catch ex As Exception
    MessageBox.Show(ex.Message, “Common Error”, MessageBoxButtons.OK, MessageBoxIcon.Error)

End Try

Comments

« Previous entries Next Page » Next Page »