Tuesday 11 December 2007

Quick Update

Just a quick update to let you folks know that I haven't forgotten about you all and we're actually busy coding the new and improved version of FastIMF (which is being renamed) from scratch.

I'm hoping we will be able to get something out early next year but believe me when I say this is going to be worth the wait! If development at the minute is anything to go by, it should be the only service/application you need for email.

Check back in a few weeks for another update, sorry it seems like a long wait!

As a side note, Exchange 2007 will work with this new version (as will nearly any email server such as Lotus Notes etc)...there's a hint for you!

Tuesday 4 December 2007

FastIMF - Onto better things!

After much thought and planning, I have decided to push the development of FastIMF into a whole new direction today.

Watch this space!

Friday 23 November 2007

FastIMF - version 0.4

Well here is the latest version of FastIMF with a few added features, these include:

Press Delete key to delete emails
Senders addresses are now shown in main list view
Select multiple emails for allowing

Still got a few more things planned/ideas. If you want to see anything in future versions, just let me know by adding a comment!

I'm hoping to make it look a bit more professional as well in future, to make it a more polished product (it doesn't look too pretty at the minute as I'm sure you are aware).

You can download it here: DOWNLOAD
If that doesn't work then try this: DOWNLOAD (alternative)

I have used a nicer host this time as well and will be using this every time providing nobody has problems :)

Enjoy!

Thursday 25 October 2007

FastIMF - version 0.3

Well, version 0.3 has arrived and this version is greatly improved. Here are some of the features:

View email in web browser (HTML)
Multiple selection for deleting (faster to process the spam!)
Automatic folder detection (saves you trying to browse)
Search for text (looking for something? you can find it now!)

DOWNLOAD HERE

Enjoy!

Tuesday 23 October 2007

FastIMF - version 0.2

After testing my first post of FastIMF (v 0.1) I had found a bunch of problems plus I wanted to add some core features for a better release, I mainly wanted to gain interest with my initial post. This version is still by no means a polished version and I will again say that it *should* work and that I have been running the software for the past 24 hours without problems.

In this version, I have added the ability to browse the emails that have been blocked by IMF, read the content and then are able to unblock, delete or add the sender to whitelist with a simple click.

If you have any suggestions or feature requests, please leave a comment. I am currently planning for the program to be able to download a "blacklist" of approved offensive words from an updated internet source that you specify and I want to redesign the GUI to make it look pretty (I originally made the program for myself so I didn't care how it looked). Hopefully someone out there may have a good idea for a feature...

Here is version 0.2: DOWNLOAD HERE

Wednesday 17 October 2007

Exchange 2003 - Whitelist Email Addresses

FastIMF
=======

Ok, I got so frustrated by the lack of options on IMF (regardless of the XML custom weighting feature etc) that I decided to make a program that I'm sure more than enough people will appreciate.

I have only just started to program it today but it should work. What this program allows you to do is whitelist external (senders!) email addresses and also absolute delete emails that contain specific words.

There has been a patch by MS that allows you to whitelist recipients addresses but only pay-for IMF addons have previously allowed you to white list external (senders) addresses.

I will be testing it more over the next few days and making it nicer to use however it *should* work fine. The only prerequisites that I know it should require is .NET framework 2.0.

PLEASE REMEMBER TO SET DIRECTORIES IN Options->Configure Directories THE FIRST TIME YOU LOAD THE PROGRAM ELSE THE PROGRAM WILL FAIL TO WORK CORRECTLY.

Enjoy

Download here (14KB!)

Thursday 30 August 2007

ASP.NET - Random Key Generator

OK, you may need to generate a secure random key to maybe place in a database, or any other reason that you have. Here's a way I generate a secure case-sensitive string:

Add the following under Inherits System.Web.UI.Page:


Const minlength = 13
Const maxlength = 15
Dim m_rand As New Random



Now add a new function, like so:


Function GenerateKey()
Dim charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
Dim length As Integer
length = m_rand.Next(minlength, maxlength + 1)
Dim key As New StringBuilder(length)
Dim i
For i = 0 To length
key.Append(Mid(charset, m_rand.Next(0, Len(charset)), 1))
Next
Return key.ToString
End Function



Now all you need to do in your code is call GenerateKey() and it will return a unique key. Bear in mind that you can change the minimum and maximum length of the key by editing the const values that we added at the start.

Enjoy!

Monday 6 August 2007

ASP.NET - Save password value

If you create a textbox with a TextMode of Password, you will see that when the form is submitted, the value is lost out of the textbox. This is due to security reasons, but you can force it to keep the value by simply adding the following to the Page_LoadComplete event:



If Page.IsPostBack Then
Me.password.Attributes.Add("value", Me.password.Text)
End If



Just make sure you replace "password" with the name of your textbox.

ASP.NET - Dynamic Controls

Let's say you wanted to create a CheckBox for every row in a table. How do we create it? How do we reference it on a PostBack? There are many guides on how to do this but they are unclear and don't explain what happens.

If we create components via code, you may be unsure on how to reference it later, say in a buttons click. When they are created dynamically the problem is that the controls are lost on a PostBack thus code fails to execute and you can't get the Checked state or Text of say a TextBox control because they are no longer there.

How do we solve this? You MUST create all dynamic controls in the Page_Init event. This means that the controls will not be lost during a PostBack, thus you can reference them correctly.

Let's create 10 CheckBox controls on the page and then return their checked state when you push a button. The first thing to do is place a PlaceHolder control onto the page, in this example it will be left to its default name of PlaceHolder1. This will be a container for all of our dynamic controls.


dim i
for i = 0 to 9
Dim cb As New CheckBox
cb.ID = "cb" & i
cb.Text = "Dynamic Checkbox " & i
cb.EnableViewState = True
cb.Width = 300
PlaceHolder1.Controls.Add(cb)
PlaceHolder1.Controls.Add(New LiteralControl("< BR>"))
Next


In the example above we step through a loop and create 10 checkbox controls, each with a html break to seperate them and make it look tidy. Now all we need to do is get the state of every checkbox and here's how (place the following code within a button):



Dim results
Dim cb As Control
For Each cb In PlaceHolder1.Controls
If TypeOf cb Is CheckBox Then
If CType(cb, CheckBox).Checked Then
results = results & CType(cb, CheckBox).Text & " is Checked < BR>"
End If
End If
Next
response.write(results)


The above will simply check through all of the dynamic controls and list all the boxes that are checked via a simple response.write. You could code a Select All button simply by doing the following:



Dim cb As Control
For Each cb In PlaceHolder1.Controls
If TypeOf cb Is CheckBox Then
CType(cb, CheckBox).Checked = True
End If
Next


Easy! Hopefully you all understand the basics of working with dynamic controls now. The examples above have no limit on the amount of controls that are created and can easily be adapted to the amount of rows on a database, for example.

Thursday 2 August 2007

ASP.NET - LDAP Domain Information

Ever wanted to retrieve properties of a user from the domain? An easy way is through LDAP (providing the service is running).

Declare the following:


Imports System.DirectoryServices



Now place the following in your code, where appropriate:


Dim oroot As DirectoryEntry = New DirectoryEntry("LDAP://SERVER", "USERNAME", "PASSWORD")
Dim osearcher As New DirectorySearcher(oroot)
Dim oresult As SearchResultCollection
Dim result As SearchResult

Dim FINDUSERNAME = "jbloggs"

osearcher.Filter = "(&(objectCategory=person)(sAMAccountName=" & FINDUSERNAME & "))"
osearcher.PropertiesToLoad.Add("cn") ' username
osearcher.PropertiesToLoad.Add("name") ' full name
osearcher.PropertiesToLoad.Add("department") ' department
osearcher.PropertiesToLoad.Add("givenname") ' firstname
osearcher.PropertiesToLoad.Add("sn") ' lastname
osearcher.PropertiesToLoad.Add("mail") ' mail
osearcher.PropertiesToLoad.Add("initials") ' initials
osearcher.PropertiesToLoad.Add("ou") ' organizational unit
osearcher.PropertiesToLoad.Add("userPrincipalName") ' login name
osearcher.PropertiesToLoad.Add("distinguishedName") ' distinguised name
osearcher.PropertiesToLoad.Add("sAMAccountName") 'userlogin

Try
oresult = osearcher.FindAll()

dim username
dim fullname

For Each result In oresult
username = result.GetDirectoryEntry.Properties("cn").Value
fullname = result.GetDirectoryEntry.Properties("name").Value
Next
Catch
Response.Write("Error processing details")
End Try



The above example will look up the user jbloggs using the credentials USERNAME and PASSWORD to connect to the server and return the username and fullname, although you can retrieve any one of the properties that are mentioned, such as result.GetDirectoryEntry.Properties("department").Value for that persons department.

ASP.NET - Double click a ListBox

Ever been frustrated by a ListBox not having an OnDoubleClick event? Do not worry, all you have to do is add this simple line to the Page_Load event:



ListBox1.Attributes.Add("ondblClick", "{document.getElementById('" + Button1.UniqueID + "').click();return false;} ")



Now when you double click an item in the listbox, it will do the actions in the Button1_OnClick event. If you wanted to process something with the selected value in the ListBox, simply use the ListBox1.SelectedValue property within the Button1_OnClick event. A similar technique can also be used for other controls.

Simple but useful!

ASP.NET - Export to PDF

First of all, sorry for the lack of updates (is anyone out there reading this?) :) I'll have to update it a bit to try and bring in visitors.

Ok, we know how to export to Excel but how can we export to PDF? Below I shall explain using the iTextSharp library http://sourceforge.net/projects/itextsharp/ to export a table to PDF. There hasn't been much documentation on this on the web, especially when it's regarding VB as a language.

The example below is for exporting a table to PDF, however the functions are there to export absolutely anything, even plain text such as a word document. Make your own application and decide what you need it to do.

First of all, declare the following:


Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports System.IO

Dim ds As New System.Data.DataSet
Dim dg As New DataGrid
Dim stringWrite As New System.IO.StringWriter
Dim htmlWrite As New System.Web.UI.HtmlTextWriter(stringWrite)



Now fill your DataSet (ds) with data somehow (I used MySQL to run a query against a database) then do the following:


dg.DataSource = ds.Tables(0)
dg.DataBind()

Dim mytable As New PdfPTable(ds.Tables(0).Columns.Count)

mytable.SpacingBefore = 8
mytable.DefaultCell.Padding = 1
mytable.WidthPercentage = 100
mytable.DefaultCell.HorizontalAlignment = Element.ALIGN_JUSTIFIED
mytable.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE

Dim t
For t = 0 To ds.Tables(0).Columns.Count - 1

Dim cell As New PdfPCell
cell.BorderWidth = 0.001F
cell.BackgroundColor = New Color(101, 197, 250)
cell.BorderColor = New Color(0, 0, 0)
cell.Phrase = New Phrase(ds.Tables(0).Columns(t).ToString, FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 8, Font.BOLD))
mytable.AddCell(cell)

Next



Dim r
Dim c

For r = 0 To ds.Tables(0).Rows.Count - 1
For c = 0 To ds.Tables(0).Columns.Count - 1

Dim cell As New PdfPCell

cell.BorderWidth = 0.001F
cell.BackgroundColor = New Color(255, 255, 255)
cell.BorderColor = New Color(0, 0, 0)
cell.Phrase = New Phrase(ds.Tables(0).Rows(r).Item(c).ToString, FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 8, Font.BOLD))
mytable.AddCell(cell)

Next
Next



First we create the columns with different formatting and then we step through every cell and build the PDF. Finally, we write the file and certain attributes:




Try

Dim mystream As New MemoryStream()
Dim document As New Document(PageSize.A4.Rotate(), 15, 15, 15, 15)
Dim writer As PdfWriter
writer = PdfWriter.GetInstance(document, mystream)
writer.SetEncryption(PdfWriter.STRENGTH40BITS, "", "", PdfWriter.AllowPrinting)
document.AddAuthor("Joe Bloggs")
document.AddSubject("Published from my ASP.NET page")
document.AddTitle("Exported Document")
document.Open()
document.Add(mytable)
document.Close()
mystream.Flush()
mystream.Close()

Dim bytearray As Byte() = mystream.ToArray
Response.Clear()
Response.AddHeader("Content-Disposition", "attachment; filename=export.pdf")
Response.ContentType = "application/pdf"
Response.BinaryWrite(bytearray)

Catch ex As DocumentException
Response.Write(ex.Message.ToString)
End Try



And there you have it! It is much easier to explain how to export normal text and not a table but if you understand how this works, the rest is easy!

A point to note is that you can allow unrestricted access to this PDF by commenting out this line: writer.SetEncryption(PdfWriter.STRENGTH40BITS, "", "", PdfWriter.AllowPrinting). This blocks editing of the document etc.

If you have any questions or problems, post a comment.

Friday 25 May 2007

ASP.NET - Gridview HTMLEncode

Ever been frustrated that when you Auto generate columns, you cannot set the HTMLEncode property to false so that it renders HTML inside the Gridview?

Simple place the code inside the Gridviews RowDataBound event:



If (e.Row.RowType = DataControlRowType.DataRow) Then

Dim cells As TableCellCollection
cells = e.Row.Cells
Dim cell = New TableCell

For Each cell In cells
cell.Text = Server.HtmlDecode(cell.Text)
Next

End If



Now every cell that has HTML inside will get rendered, such as HREF's etc ;)

Wednesday 23 May 2007

ASP.NET/Java/ASP - Run External File

This is code I use in an Intranet to execute a file on a server. Just place it in the Head of the page:




SCRIPT Language="JScript"

function openOutlook() {
myfile="R:\\Shortcuts\\Outlook.lnk";
WSH=new ActiveXObject("WScript.Shell");
WSH.Run(myfile)
}

/SCRIPT



Remember to add the < and />'s!

Now simply call a href with javascript:openOutlook and voila! Also note that the path MUST have \\ and NOT a single \

ASP.NET - web.config and posting attachments

Ever wondered why you can only post requests around 4mb in your ASP.NET pages?

Simply edit the web.config file and add the following under the system.web section:



httpRuntime maxRequestLength="100000"


Remember to add < at the start and /> at the end of the line (this blog posting will not render the line properly if I type it!)

You can now post files (for example, into a database) larger than you ever would want to.

ASP.NET - File Information

Want to know the subject/author/created date/etc... of a file in ASP.NET? Well you can use a slightly adapted version of my Classic ASP example. Note that the version below is for a server running on Windows 2000.



Function FileInfo(ByVal filename, ByVal Attribute)

Dim shortname
shortname = Right(filename, Len(filename) - InStrRev(filename, "\"))
Dim objShell = CreateObject("Shell.Application")
Dim objFolder = objShell.Namespace(Left(filename, InStrRev(filename, "\")))
Dim folderitem = objFolder.parsename(shortname)
Dim detail = ""

'// Windows 2000 attributes
'// =======================
'// Name, Size, Type, Modified, Attributes, Comments
'// Created, Accessed, Owner, Author, Title, Subject
'// Category, Pages, Copyright, CompanyName, ModuleDescription
'// ModuleVersion, ProductName, ProductVersion, SenderName
'// RecipientName, RecipientNumber, CSID, TSID, TransmissionTime
'// CallerID, Routing, AudioFormat, SampleRate, AudioSampleSize
'// AudioChannels, PlayLength, FrameCount, FrameRate
'// VideoSampleSize, VideoCompression

Select Case Attribute
Case "Size"
detail = objFolder.GetDetailsOf(folderitem, 1)
Case "Type"
detail = objFolder.GetDetailsOf(folderitem, 2)
Case "Modified"
detail = objFolder.GetDetailsOf(folderitem, 3)
Case "Attributes"
detail = objFolder.GetDetailsOf(folderitem, 4)
Case "Comments"
detail = objFolder.GetDetailsOf(folderitem, 5)
Case "Created"
detail = objFolder.GetDetailsOf(folderitem, 6)
Case "Accessed"
detail = objFolder.GetDetailsOf(folderitem, 7)
Case "Owner"
detail = objFolder.GetDetailsOf(folderitem, 8)
Case "Author"
detail = objFolder.GetDetailsOf(folderitem, 10)
Case "Title"
detail = objFolder.GetDetailsOf(folderitem, 11)
Case "Subject"
detail = objFolder.GetDetailsOf(folderitem, 12)
Case "Category"
detail = objFolder.GetDetailsOf(folderitem, 13)
Case "Pages"
detail = objFolder.GetDetailsOf(folderitem, 14)
Case "Copyright"
detail = objFolder.GetDetailsOf(folderitem, 15)
Case "CompanyName"
detail = objFolder.GetDetailsOf(folderitem, 16)
Case "ModuleDescription"
detail = objFolder.GetDetailsOf(folderitem, 17)
Case "ModuleVersion"
detail = objFolder.GetDetailsOf(folderitem, 18)
Case "ProductName"
detail = objFolder.GetDetailsOf(folderitem, 19)
Case "Version"
detail = objFolder.GetDetailsOf(folderitem, 20)
Case "SenderName"
detail = objFolder.GetDetailsOf(folderitem, 21)
Case "RecipientName"
detail = objFolder.GetDetailsOf(folderitem, 22)
Case "RecipientNumber"
detail = objFolder.GetDetailsOf(folderitem, 23)
Case "CSID"
detail = objFolder.GetDetailsOf(folderitem, 24)
Case "TSID"
detail = objFolder.GetDetailsOf(folderitem, 25)
Case "TransmissionTime"
detail = objFolder.GetDetailsOf(folderitem, 26)
Case "CallerID"
detail = objFolder.GetDetailsOf(folderitem, 27)
Case "Routing"
detail = objFolder.GetDetailsOf(folderitem, 28)
Case "AudioFormat"
detail = objFolder.GetDetailsOf(folderitem, 29)
Case "SampleRate"
detail = objFolder.GetDetailsOf(folderitem, 30)
Case "AudioSampleSize"
detail = objFolder.GetDetailsOf(folderitem, 31)
Case "AudioChannels"
detail = objFolder.GetDetailsOf(folderitem, 32)
Case "PlayLength"
detail = objFolder.GetDetailsOf(folderitem, 33)
Case "FrameCount"
detail = objFolder.GetDetailsOf(folderitem, 34)
Case "FrameRate"
detail = objFolder.GetDetailsOf(folderitem, 35)
Case "VideoSampleSize"
detail = objFolder.GetDetailsOf(folderitem, 36)
Case "VideoCompression"
detail = objFolder.GetDetailsOf(folderitem, 37)
End Select
Return (detail)

End Function


Use by calling:



FileInfo("C:\file.txt","Subject")

Thursday 10 May 2007

VB.NET - Give me dates!

Wish to know the date range of last week or next week? What about the current or last months start and end date? Here's how...


Dim startweek
Dim endweek
Dim lastweekstart
Dim lastweekend
Dim currentmonthstart
Dim currentmonthend
Dim lastmonthstart
Dim lastmonthend

Dim today
today = Date.Today

endweek = DateAdd(DateInterval.Day, 1, DateAdd(DateInterval.Day, 7 - DatePart(DateInterval.Weekday, today), today))

startweek = DateAdd(DateInterval.Day, -6, endweek)

lastweekend = DateAdd(DateInterval.Day, -1, startweek)

lastweekstart = DateAdd(DateInterval.Day, -6, lastweekend)

currentmonthstart = DateAdd(DateInterval.Day, -(DatePart(DateInterval.Day, today) - 1), today)

currentmonthend = DateAdd(DateInterval.Day, -1, DateAdd(DateInterval.Month, 1, currentmonthstart))

lastmonthstart = DateAdd(DateInterval.Month, -1, currentmonthstart)

lastmonthend = DateAdd(DateInterval.Day, -1, DateAdd(DateInterval.Month, 1, lastmonthstart))

Thursday 29 March 2007

Classic ASP - Draw SQL Tables

Place the following code into an include file and it will draw a table. It can display either horizontal (HTable) or vertical (VTable) and has many options as parameters. Make sure you set strconn to a valid connection i.e strConn = "Provider=MSDASQL;DSN=database;"


Const adOpenStatic = 3
Const adUseClient = 3

'///////////////////////////////////////////////////////////////
'//Function list
'///////////////////////////////////////////////////////////////
'//Draw a Vertical table
'//Function VTable(objNum,strSQL,TWidth,DisplayNames,Alignment,CellShading,Border,CellPadding,CellSpacing)
'//
'//Draw a Horizontal table
'//Function HTable(objNum,strSQL,TWidth,DisplayNames,Alignment,CellShading,Border,CellPadding,CellSpacing)
'//
'//

Function OpenDB(objNum,strConn,strSQL)

'// Create the ADO objects:
Set objConn(objNum) = Server.CreateObject("ADODB.Connection")
Set objRS(objNum) = Server.CreateObject("ADODB.Recordset")
'// Connect to the database using OLE DB:
objConn(objNum).Open strConn
'// Use a client-side cursor so we can sort later and so we can create a disconnected recordset:
objRS(objNum).CursorLocation = adUseClient
objRS(objNum).Source = strSQL
'// Use a static cursor so we can navigate freely:
objRS(objNum).CursorType = adOpenStatic
Set objRS(objNum).ActiveConnection = objConn(objNum)
'// Open the report's recordset:
objRS(objNum).Open
'// Disconnect the recordset from the connection:
Set objRS(objNum).ActiveConnection = Nothing
'// Close the connection to the database:
objConn(objNum).Close
End Function

Function HTable(objNum,strSQL,TWidth,DisplayNames,Alignment,CellShading,Border,CellPadding,CellSpacing)
if TWidth = "" then TWidth="100%"
if DisplayNames = "" then DisplayNames = "Yes"
if Alignment = "L" then Alignment = "Left"
if Alignment = "C" then Alignment = "Center"
if Alignment = "R" then Alignment = "Right"
if CellShading = "" then CellShading = "No"
if Border = "" then Border=0
if CellPadding = "" then CellPadding=0
if CellSpacing = "" then CellSpacing=0

Call OpenDB(objNum,strConn,strSQL)

If Not (objRS(objNum).BOF And objRS(objNum).EOF) Then

objRS(objNum).AbsolutePage = 1
objRS(objNum).PageSize= objRS(objNum).RecordCount
intDisplayRows = objRS(objNum).PageSize - 1
intColMax = objRS(objNum).Fields.count - 1
response.write("")
N=0

For intCol = 0 To intColMax
if Len(ObjRs(objNum).Fields(intCol).Value) > 0 then
MyName = ObjRs(objNum).Fields(intCol).Name
MyValue = ObjRs(objNum).Fields(intCol).Value

if MyValue <> "000000" then

if CellShading = "Yes" then
If (N/2)=Int(N/2) Then
response.write("")
Else
response.write("")
end if
N=N+1
else
response.write("")
end if

if DisplayNames = "Yes" then
response.write("")
response.write(ObjRs(objNum).Fields(intCol).Name)
response.write("
")
end if


Select Case MyName
Case "Scheduled Date"
response.write("< align=" + Alignment + ">")
response.write(MyValue)
response.write(" (") & (WeekdayName(Weekday(MyValue))) & ")"
response.write("
")
Case "AM PM"
If MyValue <> "" then
response.write("")
If MyValue="083000" Then
response.write("AM")
Else If MyValue="123000" Then
response.write("PM")
end if
end if
response.write("
")
end if
Case Else
response.write("")
response.write(ObjRs(objNum).Fields(intCol).Value)
response.write("
")
End Select
end if
end if
Next
response.write("
")
response.write("
")
else
response.write("&nb sp")
End If
ObjRS(objNum).Close
End Function

Function VTable(objNum,strSQL,TWidth,DisplayNames,Alignment,CellShading,Border,CellPadding,CellSpacing)
if TWidth = "" then TWidth="100%"
if DisplayNames = "" then DisplayNames = "Yes"
if Alignment = "L" then Alignment = "Left"
if Alignment = "C" then Alignment = "Center"
if Alignment = "R" then Alignment = "Right"
if CellShading = "" then CellShading = "No"
if Border = "" then Border=0
if CellPadding = "" then CellPadding=0
if CellSpacing = "" then CellSpacing=0

Call OpenDB(objNum,strConn,strSQL)

If Not (objRS(objNum).BOF And objRS(objNum).EOF) Then

objRS(objNum).AbsolutePage = 1
objRS(objNum).PageSize= objRS(objNum).RecordCount
intDisplayRows = objRS(objNum).PageSize - 1
intColMax = objRS(objNum).Fields.count - 1
response.write("")
N=0
if CellShading = "Yes" then
If (N/2)=Int(N/2) Then
response.write("")
Else
response.write("")
end if
N=N+1
else
response.write("")
end if


if DisplayNames = "Yes" then
For intCol = 0 To intColMax
response.write("")
response.write(ObjRs(objNum).Fields(intCol).Name)
response.write("
")
next
response.write("
")
else
response.write("")
end if

For intRow = 0 To intDisplayRows

if CellShading = "Yes" then
If (N/2)=Int(N/2) Then
response.write("")
Else
response.write("")
end if
N=N+1
else
response.write("")
end if

For intCol = 0 To intColMax
response.write("")
response.write(ObjRs(objNum).Fields(intCol).Value)
response.write("
")
Next
response.write("
")
ObjRs(ObjNum).MoveNext
Next

response.write("
")
else
response.write("&nbs p")

End If
ObjRS(objNum).Close
end function


Now all you have to do is call the function and pass it some SQL and parameters and it will draw a table with the results!

Sorry for it being a bit messy but this blog isn't wide enough to display the code properly so it's a bit hard to understand. I have also had to add spaces so that the blog doesn't parse the code.

Wednesday 28 March 2007

MySQL - Downloading data

So you've uploaded your binary file into the database but how do you get it? Place the following code in a function or whatever you choose:


Dim datareader As MySql.Data.MySqlClient.MySqlDataReader
Dim myConnection As New MySql.Data.MySqlClient.MySqlConnection
Dim mycommand As New MySql.Data.MySqlClient.MySqlCommand
myConnection.ConnectionString = "Server=
MYSERVER;User Id=MYUSER;Password=MYPASS;Persist Security Info=True;Database=MYDATABASE"
mycommand.Connection = myConnection


mycommand.CommandText = "SELECT Document, MIMEType, FileName FROM mydb.mytable WHERE ID = 1;"
datareader = mycommand.ExecuteReader()

While datareader.Read
If datareader.Item(0).Equals(System.DBNull.Value) Then
Response.Write("")
Else
Dim FileName
Dim MIMEType
FileName = datareader.Item(2).ToString
MIMEType = datareader.Item(1).ToString
Response.Clear()
Response.AddHeader("Content-Disposition", "attachment; filename=""" & FileName & """")
Response.ContentType = MIMEType
Response.BinaryWrite(datareader.Item(0))
End If
End While

MySQL - Uploading binary data

Believe it or not, alot of people have trouble with this and it can be quite confusing but here I am again to make it easy for you all. This post will explain how to upload binary data successfully to a MySQL database and the binary data can be anything from a picture to an MP3 file.

In this example, I have a page with a FileUpload component and a button. Paste the following code into the button_click event or write a seperate function to call:


Dim myConnection As New MySql.Data.MySqlClient.MySqlConnection
myConnection.ConnectionString = "Server=
MYSERVER;User Id=MYUSER;Password=MYPASS;Persist Security Info=True;Database=MYDATABASE"
myConnection.Open()
Dim mycommand As New MySql.Data.MySqlClient.MySqlCommand
mycommand.Connection = myConnection
Dim strsql
strsql = "INSERT INTO `mydb`.`mytable` (`Document` ) VALUES (?file);"
mycommand.Parameters.Add("?file", FileUpload1.FileBytes)
mycommand.CommandText = strsql
mycommand.ExecuteNonQuery()

As usual, fill out the bold text correctly. Easy huh?

ASP.NET - SQL to Excel: easy as 1, 2, 3!

Want to make some SQL generate an Excel file with formatting? easy!

What you have to understand with this example is that you must set a Session variable before calling the page. This variable (ExcelSQL) holds the SQL which will be executed when the page is called. This example is for MySQL but could easily be adapted for other database types.


Place the following code on the Page_Load event:

Dim ExcelSQL As String
ExcelSQL = Session("ExcelSQL")


If ExcelSQL <> "" Then
Dim conn As New MySql.Data.MySqlClient.MySqlConnection
Dim mycommand As New MySql.Data.MySqlClient.MySqlCommand
Dim da As New MySql.Data.MySqlClient.MySqlDataAdapter
Dim ds As New System.Data.DataSet
Dim dg As New DataGrid
Response.Clear()
Response.Charset = ""
Response.ContentType = "application/vnd.ms-excel"
Dim stringWrite As New System.IO.StringWriter
Dim htmlWrite As New System.Web.UI.HtmlTextWriter(stringWrite)

conn.ConnectionString = "Server=
MYSERVER;User Id=MYUSER;Password=MYPASS;Persist Security Info=True;Database=MYDATABASE"

conn.Open()
mycommand.Connection = conn
mycommand.CommandText = ExcelSQL
da.SelectCommand = mycommand
da.Fill(ds)
dg.DataSource = ds.Tables(0)
dg.DataBind()
'//set how it should look
dg.HeaderStyle.Font.Bold = True
dg.HeaderStyle.HorizontalAlign = HorizontalAlign.Center
dg.HeaderStyle.BackColor = Drawing.Color.LightSkyBlue
'//write file
dg.RenderControl(htmlWrite)
Dim FileName
FileName = "Results.xls"
Response.AddHeader("Content-Disposition", "attachment; filename=""" & FileName & """")
Response.Write(stringWrite.ToString)
Response.End()

conn.Close()
Else
'//no data in table, do nothing
Response.Write("")
End If


Be sure to set the connection string correctly (highlighted in bold) and to set the session variable correctly by doing the following BEFORE you call the page, for example:

Session("ExcelSQL") = "SELECT * FROM MyTable WHERE ID > 0;"

ASP.NET - Totals on a GridView

So you have lots of numeric data on a GridView and you would like to show totals in the footer? Here's how:

First of all, place the following at the top of the .vb file, under the Imports ...:

Dim MyTotal(100) as Decimal


Secondly, place the following within the GridView1.RowDataBound event:

On Error Resume Next
Dim i

If e.Row.RowType = DataControlRowType.DataRow Then
For i = 0 To e.Row.Cells.Count - 1
mytotal(i) += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, gv1.HeaderRow.Cells(i).Text))
Next
ElseIf e.Row.RowType = DataControlRowType.Footer Then
e.Row.Cells(0).Text = "Totals:"

For i = 1 To e.Row.Cells.Count - 1
If mytotal(i) <> 0 Then
' for the Footer, display the running totals
e.Row.Cells(i).Text = mytotal(i).ToString("f")
e.Row.Cells(i).HorizontalAlign = HorizontalAlign.Right
End If
Next
e.Row.Font.Bold = True
End If


But my GridView is sortable and it won't work! In this case, use the following:

On Error Resume Next
Dim i
If e.Row.RowType = DataControlRowType.DataRow Then
For i = 0 To e.Row.Cells.Count - 1
Dim lnkBtnText As String = CType(GridView1.HeaderRow.Cells(i).Controls(0), LinkButton).Text
MyTotal(i) += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, lnkBtnText))
If MyTotal(i) = "" Then
MyTotal(i) += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, GridView1.HeaderRow.Cells(i).Text))
End If

Next
End If

If e.Row.RowType = DataControlRowType.Footer Then
e.Row.Cells(0).Text = "Totals"
For i = 1 To e.Row.Cells.Count - 1
If MyTotal(i) <> 0 Then
' for the Footer, display the running totals
e.Row.Cells(i).Text = MyTotal(i).ToString("f")
e.Row.Cells(i).HorizontalAlign = HorizontalAlign.Right
End If
Next
e.Row.Font.Bold = True
End If
End Sub

MySQL - Double values return too many decimal places!

Ok, you may have a double value stored in a MySQL table of say "94.2348723". The problem is, this can look silly when displaying the data in a table and causes columns to be far too wide. Imagine the "94.2348723" as a price, so we would like to return "94.23" by editing the SQL statement, here's how:

Let's say the value is stored in a column "Price" like so:

ItemNo | Price
-------------------
1                94.2348723
2                83.3821974

To round the figures correctly in MySQL, use the following:

SELECT `ItemNo`, Truncate(SUM(`Price`) + 0.0051,2) AS Price


It should now be correctly rounded to 2 decimal places!

Classic ASP - File Information

Paste the following code into an include file and use the GetFileAttribute function to return the attribute of that file, simple eh?

<%
'//Attribute List
'//==============
'// Windows 2000
'// ------------
'// Name, Size, Type, Modified, Attributes,
'// Comments, Created, Accessed, Owner, Author,
'// Title, Subject, Category, Pages, Copyright,
'// CompanyName, ModuleDescription, ModuleVersion,
'// ProductName, ProductVersion, SenderName, RecipientName,
'// RecipientNumber, CSID, TSID, TransmissionTime,
'// CallerID, Routing, AudioFormat, SampleRate,
'// AudioSampleSize, AudioChannels, PlayLength,
'// FrameCount, FrameRate, VideoSampleSize,
'// VideoCompression
'//
'// Win XP/2003
'// -----------
'// Name, Size, Type, Modified, Created, Accessed
'// Attributes, Status, Owner, Author, Title, Subject
'// Category, Pages, Comments, Copyright, Artist,
'// AlbumTitle, Year, TrackNumber, Genre, Duration,
'// BitRate, Protected, CameraModel, PictureDate,
'// Dimensions, Company, Description, Version,
'// ProductName, ProductVersion


function GetFileAttribute(filename, attribute)
dim srv, attrib
attrib = "error"
srv = Request.ServerVariables("SERVER_SOFTWARE")
if instr(srv,"/5.0")>0 then
'//Windows 2000 Machine
select case attribute
case "Name"
attrib = 0
case "Size"
attrib = 1
case "Type"
attrib = 2
case "Modified"
attrib = 3
case "Attributes"
attrib = 4
case "Comments"
attrib = 5
case "Created"
attrib = 6
case "Accessed"
attrib = 7
case "Owner"
attrib = 8
case "Author"
attrib = 10
case "Title"
attrib = 11
case "Subject"
attrib = 12
case "Category"
attrib = 13
case "Pages"
attrib = 14
case "Copyright"
attrib = 15
case "CompanyName"
attrib = 16
case "ModuleDescription"
attrib = 17
case "ModuleVersion"
attrib = 18
case "ProductName"
attrib = 19
case "ProductVersion"
attrib = 20
case "SenderName"
attrib = 21
case "RecipientName"
attrib = 22
case "RecipientNumber"
attrib = 23
case "CSID"
attrib = 24
case "TSID"
attrib = 25
case "TransmissionTime"
attrib = 26
case "CallerID"
attrib = 27
case "Routing"
attrib = 28
case "AudioFormat"
attrib = 29
case "SampleRate"
attrib = 30
case "AudioSampleSize"
attrib = 31
case "AudioChannels"
attrib = 32
case "PlayLength"
attrib = 33
case "FrameCount"
attrib = 34
case "FrameRate"
attrib = 35
case "VideoSampleSize"
attrib = 36
case "VideoCompression"
attrib = 37
end select

elseif instr(srv,"/5")>0 or instr(srv,"/6")>0 then
'//Windows XP/2003
select case attribute
case "Name"
attrib = 0
case "Size"
attrib = 1
case "Type"
attrib = 2
case "Modified"
attrib = 3
case "Created"
attrib = 4
case "Accessed"
attrib = 5
case "Attributes"
attrib = 6
case "Status"
attrib = 7
case "Owner"
attrib = 8
case "Author"
attrib = 9
case "Title"
attrib = 10
case "Subject"
attrib = 11
case "Category"
attrib = 12
case "Pages"
attrib = 13
case "Comments"
attrib = 14
case "Copyright"
attrib = 15
case "Artist"
attrib = 16
case "AlbumTitle"
attrib = 17
case "Year"
attrib = 18
case "TrackNumber"
attrib = 19
case "Genre"
attrib = 20
case "Duration"
attrib = 21
case "BitRate"
attrib = 22
case "Protected"
attrib = 23
case "CameraModel"
attrib = 24
case "PictureDate"
attrib = 25
case "Dimensions"
attrib = 26
case "Company"
attrib = 30
case "Description"
attrib = 31
case "Version"
attrib = 32
case "ProductName"
attrib = 33
case "ProductVersion"
attrib = 34
end select
end if

if IsNumeric(attrib) then
sFolder = left(filename,instrRev(filename,"\"))
sFile = right(filename, len(filename)-instrRev(filename,"\"))
Set oShell = CreateObject("Shell.Application")
Set oFolder = oShell.NameSpace(sFolder)
Set oFolderItem = oFolder.ParseName(sFile)
sInfo = oFolder.GetDetailsOf(oFolderItem, attrib)
If sInfo="" Then
GetFileAttribute=" "
Else
GetFileAttribute=sInfo
End If
else
GetFileAttribute=" "
end if

end function
%>


As an example, do the following:

GetFileAttribute(C:\myfile.txt, Created)

Welcome

I have been meaning to create a blog for a long time and I have finally got around to it. I will mainly be talking about Web development, programming, cars and my personal life. Hopefully you will all find something useful here and if you have any questions regarding any code posted here, please leave a comment and I shall try my best to answer.

In the programming posts I will mainly be covering VB (Visual Basic)/ASP/ASP.NET/MySQL, I may also have a few posts about Swyx (VOIP) and its SDK but this is undecided yet. I will also be covering aspects of all modern MS Windows versions relating to domains and registry etc...

I know there are probably hundreds of these about and what should make mine so special? Well in all honesty I don't know, other than the code I post here may help you or I try and help you resolve any issues. If nobody posts any comments here then I guess I will just use it as a personal reference but I hope you all start to contribute here.

Enjoy!