How can I pretty-print XML source using VB6 and MSXML? - vb6

I've been looking after this for months now and I mostly found sites asking the same question.
The answers I did found were always for .NET or C++ or involved XSLT.

After months of research I've come up with this.
Public Function PrettyPrintXML(XML As String) As String
Dim Reader As New SAXXMLReader60
Dim Writer As New MXXMLWriter60
Writer.indent = True
Writer.standalone = False
Writer.omitXMLDeclaration = False
Writer.encoding = "utf-8"
Set Reader.contentHandler = Writer
Set Reader.dtdHandler = Writer
Set Reader.errorHandler = Writer
Call Reader.putProperty("http://xml.org/sax/properties/declaration-handler", _
Writer)
Call Reader.putProperty("http://xml.org/sax/properties/lexical-handler", _
Writer)
Call Reader.parse(XML)
PrettyPrintXML = Writer.output
End Function
Using a document:
Public Function PrettyPrintDocument(Doc As DOMDocument60) As String
PrettyPrintDocument = PrettyPrintXML(Doc.XML)
End Function

Related

VB.net anonymous type has incorrect property casing from AJAX call

We have noticed that sometimes from the results of an AJAX call to a controller action that the case of the JSON result is incorrect. The returned case will actually change if we rebuild our solution and try the exact same call. In the following case, the key's case has been correct for over a year until now when it has decided to start randomly changing depending on some seemingly random circumstances.
As you can see in the picture above, the key for the JSON result is lowercase "success". However when I view the results in Chrome's console, it is an uppercase "Success". This is causing our JavaScript to fail since it is checking for the lowercase version.
What is causing this? And more importantly, how do we stop this?
vb.net is case-insensitive as opposed to C# which is case-sensitive. This means that the compiler will generate only one class (from the first instance) for each of the following anonymous types:
Dim a = New With {.success = True} 'Compiler generate a class based on this type
Dim b = New With {.Success = True} 'Same type as `a`
Dim c = New With {.sUcCeSs = True} 'Same type as `a`
Debug.WriteLine(a.GetType().Name)
Debug.WriteLine(b.GetType().Name)
Debug.WriteLine(c.GetType().Name)
VB$AnonymousType_0'1
VB$AnonymousType_0'1
VB$AnonymousType_0'1
Here's how the complied code looks like when compiled back to vb.net:
<DebuggerDisplay("success={success}"), CompilerGenerated> _
Friend NotInheritable Class VB$AnonymousType_0(Of T0)
' Methods
<DebuggerNonUserCode> _
Public Sub New(ByVal success As T0)
Me.$success = success
End Sub
<DebuggerNonUserCode> _
Public Overrides Function ToString() As String
Dim builder As New StringBuilder
builder.Append("{ ")
builder.AppendFormat("{0} = {1} ", "success", Me.$success)
builder.Append("}")
Return builder.ToString
End Function
Public Property success As T0
<DebuggerNonUserCode> _
Get
Return Me.$success
End Get
<DebuggerNonUserCode> _
Set(ByVal Value As T0)
Me.$success = Value
End Set
End Property
Private $success As T0
End Class

What is this VB6 method doing?

We are converting a VB6 application to C# (4.0). and have come across a method in VB6 that we're battling to understand.
Public Sub SaveToField(fldAttach As ADODB.Field)
Dim bData() As Byte
Dim nSize As Long
nSize = Len(m_sEmail)
bData = LngToByteArray(nSize)
fldAttach.AppendChunk bData
If nSize > 0 Then
bData = StringToByteArray(m_sEmail)
fldAttach.AppendChunk bData
End If
nSize = Len(m_sName)
bData = LngToByteArray(nSize)
fldAttach.AppendChunk bData
If nSize > 0 Then
bData = StringToByteArray(m_sName)
fldAttach.AppendChunk bData
End If
bData = LngToByteArray(m_nContactID)
fldAttach.AppendChunk bData
End Sub
It seems like it's doing some binary file copy type thing, but I'm not quite understanding. Could someone explain so that we can rewrite it?
It serializes the members of the current class (m_sEmail, m_sName, etc.) into the fldAttach database field as a byte array. Each data element is prefixed with its size, that's why th code LngToByteArray(nSize) is there for each piece of data written out.
In C# you'd use a MemoryStream and BinaryWriter to accomplish the serialization aspect of it and then you'd write the byte array from the memory stream to the database. Something like:
byte[] byData;
using (MemoryStream oStream = new MemoryStream)
{
using (BinaryWriter oWriter = new BinaryWriter (oStream))
{
if (m_sName == null)
{
oWriter.Write ((byte) 0); // null string
}
else
{
oWriter.Write ((byte) 1); // not a null string
oWriter.Write (m_sName);
}
// other fields
}
byData = oStream.ToArray (); // get serialized byte array
}
// use byData here
Edit: MarkJ pointed out in the comments that this code doesn't write the same binary format as the original VB6 code, only something similar. If there's an existing database with records written by the VB6 code, the C# code will have to handle those.
There are two major differences: one is how strings are output - the original VB6 code doesn't deal with null strings (there's no such concept in VB6). The other is that BinaryWriter.Write(string) automatically writes a length-prefixed string - this may or may not be in the same exact format used by the VB6 code which outputs a length and then the string bytes. C# can replicate the VB6 code here using the following logic:
...
// assuming sStr is not null
byte[] byString = Encoding.Unicode.GetBytes ( sStr );
oWriter.Write ( sStr.Length );
oWriter.Write ( byString );
The C# port will have to assume no null strings or it'll have to deal with those in some way.
It may be better to write a small utility that goes through the database and updates all records to the new format in which strings have a null marker, a length-prefix and then the string bytes. I'd personally go with this solution since then new code doesn't have to deal with the quirks of and old language.
PS:
Do note that Long in VB6 maps to int in C#. This is important for handling the length prefix for the VB6 binary format.
Also, here's a link to a question about VB6 strings - this may be useful when porting happens:
VB6 equivalent of string.IsNullOrEmpty

VB6: Is there a standard library (parser) to strip HTML tags from content? [duplicate]

How to strip ALL HTML tags using MSHTML Parser in VB6?
This is adapted from Code over at CodeGuru. Many Many thanks to the original author:
http://www.codeguru.com/vb/vb_internet/html/article.php/c4815
Check the original source if you need to download your HTML from the web. E.g.:
Set objDocument = objMSHTML.createDocumentFromUrl("http://google.com", vbNullString)
I don't need to download the HTML stub from the web - I already had my stub in memory. So the original source didn't quite apply to me. My main goal is just to have a qualified DOM Parser strip the HTML from the User generated content for me. Some would say, "Why not just use some RegEx to strip the HTML?" Good luck with that!
Add a reference to: Microsoft HTML Object Library
This is the same HTML Parser that runs Internet Explorer (IE) - Let the heckling begin. Well, Heckle away...
Here's the code I used:
Dim objDocument As MSHTML.HTMLDocument
Set objDocument = New MSHTML.HTMLDocument
'NOTE: txtSource is an instance of a simple TextBox object
objDocument.body.innerHTML = "<p>Hello World!</p> <p>Hello Jason!</p> <br/>Hello Bob!"
txtSource.Text = objDocument.body.innerText
The resulting text in txtSource.Text is my User's Content stripped of all HTML. Clean and maintainable - No Cthulhu Way for me.
One way:
Function strip(html As String) As String
With CreateObject("htmlfile")
.Open
.write html
.Close
strip = .body.outerText
End With
End Function
For
?strip("<strong>hello <i>wor<u>ld</u>!</strong><foo> 1234")
hello world! 1234
Public Function ParseHtml(ByVal str As String) As String
Dim Ret As String, TagOpenend As Boolean, TagClosed As Boolean
Dim n As Long, sChar As String
For n = 1 To Len(str)
sChar = Mid(str, n, 1)
Select Case sChar
Case "<"
TagOpenend = True
Case ">"
TagClosed = True
TagOpenend = False
Case Else
If TagOpenend = False Then
Ret = Ret & sChar
End If
End Select
Next
ParseHtml = Ret
End Function
This is a simple function i mafe for my own use.
use Debug window
?ParseHtml( "< div >test< /div >" )
test
I hope this will help without using external libraries

How to strip ALL HTML tags using MSHTML Parser in VB6?

How to strip ALL HTML tags using MSHTML Parser in VB6?
This is adapted from Code over at CodeGuru. Many Many thanks to the original author:
http://www.codeguru.com/vb/vb_internet/html/article.php/c4815
Check the original source if you need to download your HTML from the web. E.g.:
Set objDocument = objMSHTML.createDocumentFromUrl("http://google.com", vbNullString)
I don't need to download the HTML stub from the web - I already had my stub in memory. So the original source didn't quite apply to me. My main goal is just to have a qualified DOM Parser strip the HTML from the User generated content for me. Some would say, "Why not just use some RegEx to strip the HTML?" Good luck with that!
Add a reference to: Microsoft HTML Object Library
This is the same HTML Parser that runs Internet Explorer (IE) - Let the heckling begin. Well, Heckle away...
Here's the code I used:
Dim objDocument As MSHTML.HTMLDocument
Set objDocument = New MSHTML.HTMLDocument
'NOTE: txtSource is an instance of a simple TextBox object
objDocument.body.innerHTML = "<p>Hello World!</p> <p>Hello Jason!</p> <br/>Hello Bob!"
txtSource.Text = objDocument.body.innerText
The resulting text in txtSource.Text is my User's Content stripped of all HTML. Clean and maintainable - No Cthulhu Way for me.
One way:
Function strip(html As String) As String
With CreateObject("htmlfile")
.Open
.write html
.Close
strip = .body.outerText
End With
End Function
For
?strip("<strong>hello <i>wor<u>ld</u>!</strong><foo> 1234")
hello world! 1234
Public Function ParseHtml(ByVal str As String) As String
Dim Ret As String, TagOpenend As Boolean, TagClosed As Boolean
Dim n As Long, sChar As String
For n = 1 To Len(str)
sChar = Mid(str, n, 1)
Select Case sChar
Case "<"
TagOpenend = True
Case ">"
TagClosed = True
TagOpenend = False
Case Else
If TagOpenend = False Then
Ret = Ret & sChar
End If
End Select
Next
ParseHtml = Ret
End Function
This is a simple function i mafe for my own use.
use Debug window
?ParseHtml( "< div >test< /div >" )
test
I hope this will help without using external libraries

Windows Service HTTPListener Memory Issue

Im a complete novice to the "best practices" etc of writing in any code.
I tend to just write it an if it works, why fix it.
Well, this way of working is landing me in some hot water. I am writing a simple windows service to server a single webpage. (This service will be incorperated in to another project which monitors the services and some folders on a group of servers.)
My problem is that whenever a request is recieved, the memory usage jumps up by a few K per request and keeps qoing up on every request.
Now ive found that by putting GC.Collect in the mix it stops at a certain number but im sure its not meant to be used this way. I was wondering if i am missing something or not doing something i should to free up memory.
Here is the code:
Public Class SimpleWebService : Inherits ServiceBase
'Set the values for the different event log types.
Public Const EVENT_ERROR As Integer = 1
Public Const EVENT_WARNING As Integer = 2
Public Const EVENT_INFORMATION As Integer = 4
Public listenerThread As Thread
Dim HTTPListner As HttpListener
Dim blnKeepAlive As Boolean = True
Shared Sub Main()
Dim ServicesToRun As ServiceBase()
ServicesToRun = New ServiceBase() {New SimpleWebService()}
ServiceBase.Run(ServicesToRun)
End Sub
Protected Overrides Sub OnStart(ByVal args As String())
If Not HttpListener.IsSupported Then
CreateEventLogEntry("Windows XP SP2, Server 2003, or higher is required to " & "use the HttpListener class.")
Me.Stop()
End If
Try
listenerThread = New Thread(AddressOf ListenForConnections)
listenerThread.Start()
Catch ex As Exception
CreateEventLogEntry(ex.Message)
End Try
End Sub
Protected Overrides Sub OnStop()
blnKeepAlive = False
End Sub
Private Sub CreateEventLogEntry(ByRef strEventContent As String)
Dim sSource As String
Dim sLog As String
sSource = "Service1"
sLog = "Application"
If Not EventLog.SourceExists(sSource) Then
EventLog.CreateEventSource(sSource, sLog)
End If
Dim ELog As New EventLog(sLog, ".", sSource)
ELog.WriteEntry(strEventContent)
End Sub
Public Sub ListenForConnections()
HTTPListner = New HttpListener
HTTPListner.Prefixes.Add("http://*:1986/")
HTTPListner.Start()
Do While blnKeepAlive
Dim ctx As HttpListenerContext = HTTPListner.GetContext()
Dim HandlerThread As Thread = New Thread(AddressOf ProcessRequest)
HandlerThread.Start(ctx)
HandlerThread = Nothing
Loop
HTTPListner.Stop()
End Sub
Private Sub ProcessRequest(ByVal ctx As HttpListenerContext)
Dim sb As StringBuilder = New StringBuilder
sb.Append("<html><body><h1>Test My Service</h1>")
sb.Append("</body></html>")
Dim buffer() As Byte = Encoding.UTF8.GetBytes(sb.ToString)
ctx.Response.ContentLength64 = buffer.Length
ctx.Response.OutputStream.Write(buffer, 0, buffer.Length)
ctx.Response.OutputStream.Close()
ctx.Response.Close()
sb = Nothing
buffer = Nothing
ctx = Nothing
'This line seems to keep the mem leak down
'System.GC.Collect()
End Sub
End Class
Please feel free to critisise and tear the code apart but please BE KIND. I have admitted I dont tend to follow the best practice when it comes to coding.
You are right, you should not be doing this. Remove the Collect() call and let it run for a week. Any decent .NET book will talk about how the garbage collector works and how it does not immediately release memory when you set an object to Nothing. It doesn't kick in until you've consumed somewhere between 2 and 8 megabytes. This is not a leak, merely effective use of a plentiful resource.
You use a new thread for each individual connection, that's pretty expensive and scales very poorly when you get a lot of connections. Consider using ThreadPool.QueueUserWorkItem instead. Threadpool threads are very cheap and their allocation and execution is well controlled by the threadpool manager.

Resources