BPSoftware.com
Home   Utilities   Purchase   FAQ   Support   Contact        
Shareware Utilities
 APrintDirect
 AIconExtract
 AFile Attribute Manager
Freeware Utilities
 AddrMon
 AFileSync
 ASysIcon
 B&P Table Utilities
 BPACLer
 BPSNMPMon
 BPSNMPUtil
 CharCount
 Delphi® Components
 MacAddr
Miscellaneous
 BPSoftware Blog
 Purchase Shareware
 Support

 Subscribe!

Sunday, January 28, 2007
PInvoke WIN32 and .NET

The WIN32 API has been around for quite sometime and has a large number of 'calls' and 'mechanisms' that have not yet been ported over to the .NET world. There are also still quite a few valuable WIN32 libraries/exports that have yet to be 'upgraded'. When integration is needed with existing WIN32 applications or APIs from a .NET application the unmanaged WIN32 DLL exports can be accessed using Platform Invoke (also referred to as PInvoke or P/Invoke). I am in the process of moving pieces of code to use the .NET framework. One of the first pieces on my list was the About Box class that I use in my personal applications. This base About Box class I created and use through out most (if not all) of my personal applications. The setting of a few properties has the About Box up and running for a new application in moments. In this About Box class I use the GlobalMemoryStatus function to display virtual and physical memory information. In order to still use this function in my new and 'improved' .NET About Box I needed to use PInvoke.

C#

using System.Runtime.InteropServices;

// define the structure
public struct _MEMORYSTATUS //http://msdn2.microsoft.com/en-us/library/aa366772.aspx
{
public uint dwLength;
public uint dwMemoryLoad;
public uint dwTotalPhys;
public uint dwAvailPhys;
public uint dwTotalPageFile;
public uint dwAvailPageFile;
public uint dwTotalVirtual;
public uint dwAvailVirtual;
}


[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern void GlobalMemoryStatus(out _MEMORYSTATUS memorystatus);


// for simplicity of demonstration
_MEMORYSTATUS memorystatus = new _MEMORYSTATUS();
GlobalMemoryStatus(out memorystatus);
ulong totalVirtualMemory = memorystatus.dwTotalVirtual;
ulong availablePhysicalMemory = memorystatus.dwAvailPhys;
ulong availableVirtualMemory = memorystatus.dwAvailVirtual;
ulong totalPhysicalMemory = memorystatus.dwTotalPhys;




VB.NET

Imports System.Runtime.InteropServices

Public Structure _MEMORYSTATUS
Dim dwLength As Integer
Dim dwMemoryLoad As Integer
Dim dwTotalPhys As Integer
Dim dwAvailPhys
As Integer
Dim dwTotalPageFile As Integer
Dim dwAvailPageFile As Integer
Dim dwTotalVirtual As Integer
Dim dwAvailVirtual As Integer
End Structure

'In VB.NET there are two ways to call this

'<DllImport("kernel32.dll")> Public Shared Sub _
' GlobalMemoryStatus1(ByVal memorystatus As _MEMORYSTATUS)
'End Sub

Declare Auto Sub GlobalMemoryStatus Lib "kernel32" (ByRef lpBuffer As _MEMORYSTATUS)



Dim memorystatus As New _MEMORYSTATUS
GlobalMemoryStatus(memorystatus)

Dim totalVirtualMemory As Integer = memorystatus.dwTotalVirtual
Dim availablePhysicalMemory As Integer = memorystatus.dwAvailPhys
Dim availableVirtualMemory As Integer = memorystatus.dwAvailVirtual
Dim totalPhysicalMemory As Integer = memorystatus.dwTotalPhys



Side Note: After having problems with Windows Live Writer after I 'upgraded' to the 'new' Blogger I published this blog entry using Google Docs & Spreadsheets. Curiosity got the best of me and I wanted to see how it worked.

Labels: , , ,

posted by Brad Prendergast at 12:16:00 AM (0 comments)
Links to this post
Permalink
Saturday, January 27, 2007
ASP.NET upload a file HtmlInputFile Control

When developing a web application it often may be necessary to allow a user to ‘send’ (upload) a file. With HtmlInputFile control the this seemingly complicated task is much easier than one would expect. The HtmlInputFile control is not listed in the toolbox by default but can be easily added using HTML in your page. In order to use the HtmlInputFile control the following form code must be added to your .aspx page:



<!-- Add enctype="multipart/form-data" to the form declaration -->
<form id="Form1" method="post" runat="server" enctype="multipart/form-data">

<!-- the following line was manually entered to display the file control -->
<input id="btnSelectFile" type="file" runat="server" style="Z-INDEX: 101; LEFT: 24px; WIDTH: 470px; POSITION: absolute; TOP: 48px; HEIGHT: 22px" size="59">
<!-- -->

<asp:Label id="lblStatus" style="Z-INDEX: 103; LEFT: 176px; POSITION: absolute; TOP: 88px" runat="server" Width="224px">Status:</asp:Label>
<asp:Button id="btnUpload" style="Z-INDEX: 102; LEFT: 96px; POSITION: absolute; TOP: 88px" runat="server" Text="Upload"></asp:Button>
</form>


The size and position of the controls can be what ever you desire. Once the HtmlInputFile code is added you can visually design its size and position. In the above code I have also included a label for the displaying of status information and a button that will actually execute the code for the uploading of the file selected with the HtmlInputFile.
The code to upload the file is simple:

' Root Data path
‘ ensure the proper permissions are set on this folder default is the ASP.NET account
Const ROOTPATH = "C:\Data\"

Private Sub btnUpload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpload.Click

Dim filename As String

' Extract the selected filename
filename = System.IO.Path.GetFileName(btnSelectFile.PostedFile.FileName)

' Set the label to display where the file will be saved – this could also be used to display the file size uploaded
lblStatus.Text = "Status: " & ROOTPATH & filename

' Save the file
btnSelectFile.PostedFile.SaveAs(ROOTPATH & filename)

' This calls a procedure that I had created that will display the contents of a directory in a table
ListDirectory()

End Sub


Private Sub ListDirectory()

Dim currentdir As New DirectoryInfo(ROOTPATH)
Dim files As FileInfo
Dim tr As TableRow
Dim tcFile As TableCell
Dim tcSize As TableCell

For Each files In currentdir.GetFiles()
tr = New TableRow
tcFile = New TableCell
tcSize = New TableCell
tcFile.Text = files.Name
tcSize.HorizontalAlign = HorizontalAlign.Right
tcSize.Text = FormatNumber(files.Length, 0, TriState.False, TriState.True, TriState.True)
tr.Cells.Add(tcFile)
tr.Cells.Add(tcSize)
tblFiles.Rows.Add(tr)
Next

End Sub



In reviewing the previous code sample one can see how easy it is to upload a file through a web application.

Labels: , , ,

posted by Brad Prendergast at 3:54:00 PM (0 comments)
Links to this post
Permalink
Monday, December 18, 2006
More Hash - Part I

Yesterday I discussed using the System.Security.Cryptography Namespace to compute the hash value of files. Hash values of files can be used to quickly compare two files to see if they are identical. Due to the irreversible nature of Hash values, they are useful in password situations. For example, if you have an application that requires authentication you can compute the hash of a user's password and store that information. When it comes time to authenticate the user you can compare the hash value of the entered password with the stored hash value. This eliminates the storage of the actual password value, which could lead to well, problems. I had put together an application that compares the hash values of two files or strings to determine if the data is identical. This application can also be used to generate hash values. This application used the MD5, SHA1, SHA256, SHA384 and SHA512 classes. The hash values are displayed in Hexadecimal notation. If you're interested in just the application it can be downloaded here. Here is the VB.NET source. I will post the Delphi source later.

Imports System.IO
Imports System.Security.Cryptography
Imports System.Text

Public Class frmMain
Enum HashType
MD5
SHA1
SHA256
SHA384
SHA512
End Enum

Private Sub GroupCompare_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles radFiles.CheckedChanged, radStrings.CheckedChanged
ClearForm()
Select Case CType(sender, Control).Tag
Case "Files"
lblValue1.Text = "File 1:"
lblValue2.Text = "File 2:"
txtValue1.ReadOnly = True
txtValue2.ReadOnly = True
btnValue1.Visible = True
btnValue2.Visible = True
Case "Strings"
lblValue1.Text = "String 1:"
lblValue2.Text = "String 2:"
txtValue1.ReadOnly = False
txtValue2.ReadOnly = False
btnValue1.Visible = False
btnValue2.Visible = False
End Select
End Sub

Private Sub txt_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles txtValue1.TextChanged, txtValue2.TextChanged, _
txtResults1.TextChanged, txtResults2.TextChanged

ToolTip1.SetToolTip(CType(sender, Control), CType(sender, Control).Text)

End Sub

Private Sub btnFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnValue1.Click, btnValue2.Click
If ofdFiles.ShowDialog Then
Select Case CType(sender, Button).Tag
Case 0
txtValue1.Text = ofdFiles.FileName
Case 1
txtValue2.Text = ofdFiles.FileName
End Select
End If
End Sub

Private Sub ClearForm()
txtValue1.Text = ""
txtValue2.Text = ""
txtResults1.Text = ""
txtResults2.Text = ""
End Sub

Private Sub btnCompare_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCompare.Click
Dim myCursor As Cursor
Dim hasht As hashtype

myCursor = Cursor
Cursor = Cursors.WaitCursor
Try
If
radMD5.Checked Then
hasht = hashtype.MD5
End If
If
radSHA1.Checked Then
hasht = hashtype.SHA1
End If
If
radSHA256.Checked Then
hasht = hashtype.SHA256
End If
If
radSHA384.Checked Then
hasht = hashtype.SHA384
End If
If
radSHA512.Checked Then
hasht = hashtype.SHA512
End If

If radFiles.Checked Then
txtResults1.Text = GetFileHash(txtValue1.Text, hasht)
txtResults2.Text = GetFileHash(txtValue2.Text, hasht)
ElseIf radStrings.Checked Then
txtResults1.Text = GetStringHash(txtValue1.Text, hasht)
txtResults2.Text = GetStringHash(txtValue2.Text, hasht)
End If

If (String.Compare(txtResults1.Text, txtResults2.Text) = 0) Then
picResult.Image = ImageList1.Images(1)
Else
picResult.Image = ImageList1.Images(0)
End If
Catch ex As Exception
MessageBox.Show(ex.Message, ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
Cursor = myCursor
End Try
End Sub

Private Function GetFileHash(ByVal filename As String, ByVal hasht As hashtype) As String
Dim oFileStream As System.IO.FileStream
Dim lBytes As Long

Try
If
filename <> "" Then
Dim instance As New FileInfo(filename)
oFileStream = instance.OpenRead()
lBytes = oFileStream.Length
Dim filecontents(lBytes) As Byte
oFileStream.Read(filecontents, 0, lBytes)
oFileStream.Close()

Return GetHash(filecontents, hasht)
Else
Return
""
End If
Catch ex As Exception
MessageBox.Show(ex.Message, ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Error)
Return ""
End Try

End Function

Private Function GetStringHash(ByVal input As String, ByVal hasht As hashtype) As String

Return GetHash(Encoding.Default.GetBytes(input), hasht)

End Function

Public Function GetHash(ByRef contents As Byte(), ByVal hasht As hashtype) As String
Dim result() As Byte

Select Case hasht
Case hashtype.MD5
Dim MD5 As MD5 = MD5.Create
result = MD5.ComputeHash(contents)
Case hashtype.SHA1
Dim sha1M As New SHA1Managed
result = sha1M.ComputeHash(contents)
Case hashtype.SHA256
Dim sha256M As New SHA256Managed
result = sha256M.ComputeHash(contents)
Case hashtype.SHA384
Dim sha384M As New SHA384Managed
result = sha384M.ComputeHash(contents)
Case hashtype.SHA512
Dim sha512M As New SHA512Managed
result = sha512M.ComputeHash(contents)
End Select

Return GetByteString(result)
End Function

Public Function GetByteString(ByVal data As Byte())
Dim sBuilder As New StringBuilder()
Dim i As Integer

For i = 0 To data.Length - 1
sBuilder.Append(data(i).ToString("x2"))
Next i
Return sBuilder.ToString()
End Function
End Class

Labels: , ,

posted by Brad Prendergast at 3:19:00 PM (1 comments)
Links to this post
Permalink
Sunday, December 17, 2006
Is it a Hash Brown?

It has been one crazy semester (I think the lack of activity can vouch for that). I've come up to the surface and see that a lot of the landscape has changed, take the emergence of CodeGear for example. I am hoping this is a breathe of new life that can revitalize the Delphi community and not just a last ditch effort (personally I think the BDS IDE is far better for development than VS). I am optimistic about the whole thing and hope they endure the 'rebirth process'.

As I was submerged in my own little world for a period of time, I had the need to calculate the Hash value for files. This actually turned out to server two purposes. The first being the verification of a file as original (intact) by comparing the hash value of the current and original file. Second, it turned out to be a fast way of identifying identical files. Often times a CRC is used to calculate a checksum, however I opted to make use of the System.Security.Cryptography Namespace. This Namespace has a number of useful hash functions including SHA1, SHA256 and SHA512. Surprisingly (or not) these are relatively easy to use and eliminate the need to formulate the algorithm on your own. Here it is in a couple of worlds:

Delphi:

uses
System.Security.Cryptography, System.IO;

procedure frmMain.ClearForm;
begin
txtSHA1.Text:= '';
txtSHA256.Text:= '';
txtSHA512.Text:= '';
end;

procedure frmMain.txtFileName_TextChanged(sender: System.Object; e: System.EventArgs);
begin
ToolTip1.SetToolTip(txtFileName,txtFileName.Text);
end;

procedure frmMain.btnCalculate_Click(sender: System.Object; e: System.EventArgs);
var
myCursor: System.Windows.Forms.Cursor;
oFileStream: FileStream;
lBytes: int64;
instance: FileInfo;
filecontents: Array of Byte;
result: Array of Byte;
SHA1M: SHA1Managed;
SHA256M: SHA256Managed;
SHA512M: SHA512Managed;

begin
myCursor:= Cursor;
Cursor:= Cursors.WaitCursor;
try
try
if not
(txtFileName.Text='') then
begin
ErrorProvider1.SetError(btnFile,'');

instance:= FileInfo.Create(txtFileName.Text);
oFileStream:= instance.OpenRead;
lBytes:= oFileStream.Length;
SetLength(filecontents,lBytes);
oFileStream.Read(filecontents,0,lBytes);
oFileStream.Close;

SHA1M:= SHA1Managed.Create;
result:= SHA1M.ComputeHash(filecontents);
txtSHA1.Text:= Convert.ToBase64String(result);

SHA256M:= SHA256Managed.Create;
result:= SHA256M.ComputeHash(filecontents);
txtSHA256.Text:= Convert.ToBase64String(result);

SHA512M:= SHA512Managed.Create;
result:= SHA512M.ComputeHash(filecontents);
txtSHA512.Text:= Convert.ToBase64String(result);
end
else
begin

ErrorProvider1.SetError(btnFile,'Select a filename');
end;
except

on e: exception do
MessageBox.Show(e.Message, e.Source, MessageBoxButtons.OK,
MessageBoxIcon.Error);
end;
finally

Cursor:= myCursor;
end;
end;

procedure frmMain.btnFile_Click(sender: System.Object; e: System.EventArgs);
begin
if (ofdFileName.ShowDialog = System.Windows.Forms.DialogResult.OK) then
begin
ClearForm;
txtFileName.Text:= ofdFileName.FileName;
end;
end;

VB:

Imports System.Security.Cryptography
Imports System.IO

Public Class frmMain

Private Sub btnFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFile.Click
If ofdFileName.ShowDialog Then
ClearForm()
txtFileName.Text = ofdFileName.FileName
End If
End Sub

Private Sub txtFileName_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtFileName.TextChanged
ToolTip1.SetToolTip(txtFileName, txtFileName.Text)
End Sub

Private Sub ClearForm()
txtSHA1.Text = ""
txtSHA256.Text = ""
txtSHA512.Text = ""
End Sub

Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click
Dim myCursor As Cursor
Dim oFileStream As System.IO.FileStream
Dim lBytes As Long
Dim result() As Byte

myCursor = Cursor
Cursor = Cursors.WaitCursor
Try

If Not (txtFileName.Text = "") Then
ErrorProvider1.Clear() 'Introduced .NET 2.0

Dim instance As New FileInfo(txtFileName.Text)
oFileStream = instance.OpenRead()
lBytes = oFileStream.Length
Dim filecontents(lBytes) As Byte
oFileStream.Read(filecontents, 0, lBytes)
oFileStream.Close()

Dim sha1M As New SHA1Managed
result = sha1M.ComputeHash(filecontents)
txtSHA1.Text = Convert.ToBase64String(result)

Dim sha256M As New SHA256Managed
result = sha256M.ComputeHash(filecontents)
txtSHA256.Text = Convert.ToBase64String(result)

Dim sha512M As New SHA512Managed
result = sha512M.ComputeHash(filecontents)
txtSHA512.Text = Convert.ToBase64String(result)
Else
ErrorProvider1.SetError(btnFile, "Select a filename")
End If

Catch ex As Exception
MessageBox.Show(ex.Message, ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Error)

Finally
Cursor = myCursor
End Try
End Sub

End Class

This is another post done with Live Writer, I think it is pretty 'groovy'.

Labels: , , ,

posted by Brad Prendergast at 8:04:00 AM (0 comments)
Links to this post
Permalink
Thursday, May 25, 2006
Adapter Information Round 2

In an earlier post getting local adapter information via the Internet Protocol Helper (IP Helper) was discussed. The .NET Framework version 2.0 has the System.Net.NetworkInformation namespace that provides access to this information. For this sample I used VB.NET, however I will try some 'blogged' tricks to see if I can get this working in BDS® 2006 and see how it all works out.




Imports System.Net.NetworkInformation
Imports System.Net

Public Sub RetrieveLocalAdapterInformation(ByVal text As TextBox)
Dim interfaces As NetworkInterface() 'NIC
Dim netInterface As NetworkInterface ' adapter
Dim properties As IPInterfaceProperties
Dim address As PhysicalAddress
Dim ip As IPAddress
Dim ipinfo As IPAddressInformation

text.Clear()

If NetworkInterface.GetIsNetworkAvailable Then
interfaces = NetworkInterface.GetAllNetworkInterfaces

If interfaces.GetLength(0) > 0 Then
For Each netInterface In interfaces
properties = netInterface.GetIPProperties


text.AppendText(netInterface.Name & vbCrLf)
text.AppendText("Id: " & netInterface.Id.ToString & vbCrLf)
address = netInterface.GetPhysicalAddress
text.AppendText("MAC Address: " & (Microsoft.VisualBasic.IIf(address.ToString = String.Empty, "None", address.ToString)) & vbCrLf)
For Each ipinfo In properties.UnicastAddresses
text.AppendText("IP: " & ipinfo.Address.ToString & vbCrLf)
Next
For Each ip In properties.DhcpServerAddresses
text.AppendText("DHCP Server: " & ip.ToString & vbCrLf)
Next
For Each ip In properties.DnsAddresses
text.AppendText("DNS Server: " & ip.ToString & vbCrLf)
Next
text.AppendText("Type: " & netInterface.NetworkInterfaceType.ToString & vbCrLf)
text.AppendText("Operational Status: " & netInterface.OperationalStatus.ToString & vbCrLf)
text.AppendText("Speed: " & netInterface.Speed.ToString("N") & " bytes" & vbCrLf)

' XP Only
'text.AppendText("Receive Only: " & netInterface.IsReceiveOnly.ToString & vbCrLf)

' XP Only
'text.AppendText("Support Multicast: " & netInterface.SupportsMulticast.ToString & vbCrLf)


text.AppendText("Support IPv4: " & netInterface.Supports(NetworkInterfaceComponent.IPv4).ToString & vbCrLf)
text.AppendText("Support IPv6: " & netInterface.Supports(NetworkInterfaceComponent.IPv6).ToString & vbCrLf)
text.AppendText("DnsSuffix: " & properties.DnsSuffix.ToString & vbCrLf)
text.AppendText("" & vbCrLf)
Next
End If
End If
End Sub

Labels: , ,

posted by Brad Prendergast at 8:51:00 PM (0 comments)
Links to this post
Permalink
Monday, April 10, 2006
Ho Hum

I did receive a couple inquiries about yesterday's post with VB.NET. Well, here goes:

Imports Microsoft.Win32

Public Class frmMain
Const basetzikey = _
"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones\"


Private Sub frmMain_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load

FillComboBox(cbxTimeZone)

End Sub

Private Sub FillComboBox(ByVal cbxCombo As ComboBox)

Dim rootkey As RegistryKey
Dim subkeynames As String()
Dim subkeyname As String

cbxCombo.Items.Clear()
rootkey = Registry.LocalMachine
subkeynames = rootkey.OpenSubKey(basetzikey, False).GetSubKeyNames
For Each subkeyname In subkeynames
cbxCombo.Items.Add(subkeyname.ToString)
Next
End Sub


Private Sub cbxTimeZone_SelectedValueChanged(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles cbxTimeZone.SelectedValueChanged

FillTextEdit(cbxTimeZone.Text, txtOutput)

End Sub

Private Sub FillTextEdit(ByVal timezone As String, _
ByRef txtEdit As TextBox)

Dim sb As New System.Text.StringBuilder
Dim rootkey As RegistryKey
Dim subkeyvalues As String()
Dim subkeyvalue As String
Dim keyname As String
Dim b As Byte()
Dim i As Integer

txtEdit.Clear()

sb.Append(basetzikey)
sb.Append(timezone)
keyname = sb.ToString

' clear stringbuilder
sb.Remove(0, sb.Length)

rootkey = Registry.LocalMachine
subkeyvalues = rootkey.OpenSubKey(keyname, False).GetValueNames
For Each subkeyvalue In subkeyvalues
sb.Remove(0, sb.Length)
sb.Append(subkeyvalue)
sb.Append(": ")
sb.Append(rootkey.OpenSubKey(keyname, False).GetValue(subkeyvalue).ToString)
sb.Append(vbCrLf)
If (subkeyvalue = "TZI") Then
b = rootkey.OpenSubKey(keyname, False).GetValue(subkeyvalue)
i = BitConverter.ToInt32(b, 0)
sb.Append("Bias: ")
sb.Append(i.ToString)
sb.Append(" minutes.")
sb.Append(vbCrLf)
End If

txtEdit.AppendText(sb.ToString)
Next
End Sub
End Class

Labels: , ,

posted by Brad Prendergast at 6:30:00 AM (2 comments)
Links to this post
Permalink
Monday, March 13, 2006
Syndicate Me

RSS has quickly picked up as an effective way of monitoring updated content on web sites (I even have one for this site). There are many applications available to aggregate these feeds. RSS is common enough that RSS aggregation is available (or soon to be) in popular web browsers. What if you wanted your own application or web site to include RSS feed information?

Aggregating and parsing RSS feed information via System.XML namespace of .NET is a lot easier than it sounds. Fortunately RSS is a standard structure XML file. The sub-elements of each item element contain the update information. I have created three (extremely basic) separate examples (BDS 2006, VB.NET 2005 and ASP.NET) of including feed information in your application. (I also put some together using the MSXML ActiveX library that I’ll probably put in another post)

Setting the sample (WinForm) application up in BDS 2006 (Delphi®) and VB.NET 2005 is pretty much the same. On a form I place a Button, TextBox and RichTextBox (screenshot is the two side-by-side).

The TextBox is where one enters the URL of a RSS feed. When the button is clicked the RichTextBox is filled with the feed sub-element information. They both need to use the System.XML namespace.

VB.NET Code
Private Sub btnProcess_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

Dim XMLDoc As New System.Xml.XmlDocument
Dim rssItems As System.Xml.XmlNodeList
Dim child, cn As System.Xml.XmlNode

RichTextBox1.Clear()
XMLDoc.Load(TextBox1.Text)
' each of the sub-elements of the item element contain the feed information
rssItems = XMLDoc.GetElementsByTagName("item")
For Each child In rssItems
For Each cn In child.ChildNodes
' you could filter and/or process each element by name - depending
' on what you'd like to do with node data (i.e. hyperlink to the
' actual post)

RichTextBox1.AppendText(cn.Name)
RichTextBox1.AppendText(vbCr)
RichTextBox1.AppendText(cn.InnerText.Trim)
RichTextBox1.AppendText(vbCrLf)
Next
Next
End Sub


Delphi® Code
procedure TWinForm.Button1_Click(sender: System.Object; e: System.EventArgs);
var
XMLDoc: System.Xml.XmlDocument;
rssItems: System.Xml.XmlNodeList;
child, cn: System.Xml.XmlNode;

begin
RichTextBox1.Clear;

XMLDoc:= XmlDocument.Create;
XMLDoc.Load(TextBox1.Text);
rssItems:= XMLDoc.GetElementsByTagName('item');
For child in rssItems do
begin
For
cn in child.ChildNodes do
begin
RichTextBox1.AppendText(cn.Name);
RichTextBox1.AppendText(#13);
RichTextBox1.AppendText(cn.InnerText.Trim);
RichTextBox1.AppendText(#13#10);
end;
end;
end;


To display the same information on an ASP.NET web page create a document with the following code:
<%@ Page Language="VB" Debug = true%>
<%@ Import namespace="System.Xml" %>

<html>
<head>
<title>BPSoftware.com - RSS Reader</title>
</head>

<body bgcolor="#f8f8ff">
<%

Dim XMLDoc As New System.Xml.XmlDocument
Dim rssItems As System.Xml.XmlNodeList
Dim child, cn As System.Xml.XmlNode

XMLDoc.Load("http://www.techweb.com/rss/all.xml ")
rssItems = XMLDoc.GetElementsByTagName("item")
For Each child In rssItems
For Each cn In child.ChildNodes %>
<%=cn.Name%>

<br />
<%=cn.InnerText.Trim%>
<br />
<%
Next
Next
%>


</body>
</html>

After you get the basic connectivity and processing working, it is easy to filter our and process only the sub-elements that you’d like to include in your application or on your web page. There is a lot that can be done with this inside of an application; I figured I’d go with the basics to help spark some interest. For some unknown reason I've abandoned C some time ago, but if anyone wants to follow up with the same in C please do....

Labels: , , ,

posted by Brad Prendergast at 6:08:00 AM (0 comments)
Links to this post
Permalink
Recent Posts
 SQL: DBCC CHECKTABLE on multiple tables
 SQL: Index Fragmentation Maintenance
 Off-topic: Uhm, Rickroll?
 SQL: Where are the database files?
 Show Desktop in my QuickLaunch Toolbar?
 Command Line: Visual Source Safe
 SQL: Remove / Delete Orphan Users
 SQL Delete/Drop a User from each Database
 Is there an 'I' in phone?
 SQL Optimization: Am I missing any indexes? - Part...

 Subscribe!


Labels



Archives
 October 2005
 November 2005
 December 2005
 January 2006
 February 2006
 March 2006
 April 2006
 May 2006
 June 2006
 July 2006
 August 2006
 September 2006
 December 2006
 January 2007
 February 2007
 March 2007
 September 2007
 October 2007
 November 2007
 July 2008
 November 2008
Powered by Blogger