NHibernate, Sybase, CHAR(10) Columns and Poor Performance

April 17, 2020

The Problem

I was working on a C# ODATA WebAPI development that utilised NHibernate (version 4.1.1.4), Sybase, a Sybase ASE driver, .Net 4.7 etc. The tables being queried were from a legacy system and contain many char(1), char(10) and char(20) colums rather than varchar columns.

The performance of the API was not stunning.

Using an ODATA $filter against the API endpoints also did not achieve stunning performance – the response was the order of 10-20 Seconds. But why?

Investigation

NHibernate query logging was enabled so it was possible to see the queries being fired at the database – all looked fine. The queries were extracted from the log files and run directly against the database using TOAD – the queries ran quickly (a few hundred mS). So why was the API so slow?

The API code itself was quite simple – they controller method returned an IQueryable object and the magic of the Microsoft WebAPI infrastructure applied the $filter “WHERE CLAUSE” to the IQueryable and the results were returned as JSON to the caller.

However, many of the columns used in the WHERE clause were char(10) and char(20) columns rather than VARCHAR. In the NHIbernate XML mappings these fields were mapped to strings

 <property column="ExampleCharDBCol" type="String" name="ExampleModelPropertu" not-null="true" length="10"/>

From investiation it was surmised (NB surmised, I have no hard facts) that tomewhere in the NHibernate database communication the WHERE parameters were being transferred as some unicode encoded value which when, on the DB server, the query was “unpacked” and run the various indexes were ignored. Hence the slow querying

The Solution

I must give thans to B Boy and StackOverflow and Todd for pointing me in the right direction.

The answer is to use type=”AnsiString” in the NHibernate XML mappings:

 <property column="ExampleCharDBCol" type="AnsiString" name="ExampleModelPropertu" not-null="true" length="10"/>

Doing this made the queries run a factor 100 faster !!

Epilogue

I don’t think this solution is pertinent to only Sybase, I think it is valid for any database that NHibernate talks to.

VMWare Workstation Doesn’t Work on Windows 10

November 22, 2019

The Problem

I recently updated my Windows 10 desktop to the latest “improved” version of Windows 10. I rarely install Windows updates due to my mantra of “if it ain’t broke don’t fix it”, however, I ignored my mantra and opened up a plethora of problems.

One of the big problems is that I run (ran) VMWare Workstation – and version 7 to be specific. This is an old version but my VMs work, I purchased the copy so why upgrade? After the Windows 10 updates VMWare workstation would not run:

VMware Workstation Pro can't run on Windows

It would appear that one (or more) of the Windows updates was prevening VMWare from running.

The Solution

I googled and found many articles recommending uninstalling verious Windows updates – this seems dangerous and can leave you machine unuseable (the voice of experience). I then found this article. Scroll down to

There is no need to replace the entire sysmain.sdb (this action could expose your machine to unpredicatble problems).

You can simply run the Compatibility Administrator Toolkit (https://docs.microsoft.com/it-it/windows-hardware/get-started/adk-install), and disable the entry under the “System Database/Applications/VMware Workstation Pro” path. That’s all.

Here it explains about installing the Compatability Administrator Toolkit (downloadable from Microsoft). Then run the “Compatability Administrator” (this will have been installed as part of the toolkit) by click taskbar search, type “Compatability Administrator”. Within the tool search for “VMWare Workstation” under System Databases-> Application

Right click vmware.exe and click “Disable Entry”. Repeat for VMWare Workstation Pro.

VMWare Workstation should then run

Thanks MicroSoft.

Docker Hello World on Windows 10 Fails

September 12, 2019

The Problem

I was attempting to follow the Docker “Getting Started” documentation and tried to run the “Hello World” Example and I got

C:\>docker run hello-world
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
docker: no matching manifest for windows/amd64 10.0.16299 in the manifest list entries.
See 'docker run --help'.

What does this mean ?

After much head-scratching and searching (mostly unhelpful posts about using Linux containers or “experimental mode”) I came across this article about docker manifests. It did not make much sense but after some more head-scratching I worked out what the error message meant.

I ran

C:\>docker manifest inspect hello-world:latest

And got (not all the file is listed):

{
"schemaVersion": 2,
"mediaType": "application/vnd.docker.distribution.manifest.list.v2+json",
"manifests": [
{
"mediaType": "application/vnd.docker.distribution.manifest.v2+json",
"size": 524,
"digest": "sha256:92c7f9c92844bbbb5d0a101b22f7c2a7949e40f8ea90c8b3bc396879d95e899a",
"platform": {
"architecture": "amd64",
"os": "linux"
}
},

..... text chopped out for this post....

{
"mediaType": "application/vnd.docker.distribution.manifest.v2+json",
"size": 1357,
"digest": "sha256:f9fea6a66184b4907c157323de7978942eab1815be146c93a578b01a3a43ad6d",
"platform": {
"architecture": "amd64",
"os": "windows",
"os.version": "10.0.17134.1006"
}
},
{
"mediaType": "application/vnd.docker.distribution.manifest.v2+json",
"size": 1046,
"digest": "sha256:2bff08b2d77710d0a0a1608b35ea4dfdc28f698f6da86991c3da755968fa56d6",
"platform": {
"architecture": "amd64",
"os": "windows",
"os.version": "10.0.17763.737"
}
}
]
}

The Answer

All the error means is that the docker image repository (the place on the internet where the docker hello world image is stored) does not have a version built for your version of windows. i.e. it has one for Windows 10.0.17134.1006 and Windows 10.0.17763.737 but not for my version of windows: Windows 10.0.16299

How hard would an error message to that effect be?

NHibernate – Generate All Columns in Update SQL

July 9, 2019

The problem

NHibernate maintains internal state of the entities that it has loaded from the database. When saving an entity back to the DB you may want some properties (columns) included in the UPDATE SQL generated although the property value hasn’t changed. Why ? Because the update on a particular column might force a database trigger to run.

Or, to put it another way:

Database triggers are not really compatible with Object Relationship Mappers

 

In my naievety I had assumed that NHibernate would contain a “simple” option to turn on “please generate all columns in UPDATE SQL”, but, alas, no.

The Solution

I consulted StackOverflow – many posts, all leading nowhere. Then I stumbled across one post which spoke of NHibernate IInterceptors. I then consulted the NHibernate documentation – to say the documentation on interceptors is brief and concise does not do it justice.

After much messing about I worked out how interceptors work and got a working implementation so that my UPDATE SQL now includes all the columns that I require.

To make an interceptor work you need

  • Interceptor code (which implements FindDirty method)
  • Plug interceptor into NHibernate Session Create

Interceptor

The “documentation” recommends deriving your interceptor from the NHibernate EmptyInterceptor. The FindDirty method must be overriden in your interceptor, it returns an array [] of ints, the value represent the index of the propertyNames parameter of the FindDirty method – which is a list of the properties of the entity being saved. In my case I returned all items – so that all UPDATE SQL columns were included

Plug Into NHibernate

In your code (in my case, UnitofWork/Repo pattern code) you need to pass the interceptor as a parameter to the SessionFactory.OpenSession() method – this registers the interceptor with NHibernate and it will be called for all Saves

Code Example

Interceptor

public class MyInterceptor : EmptyInterceptor
{
	/// <summary>
	/// Interceptor method
	/// Return array of indices into propertyNames of columns that will be maked
	/// as dirty i.e. SQL will be generated from them
	/// </summary>
	/// <param name="entity"></param>
	/// <param name="id"></param>
	/// <param name="currentState"></param>
	/// <param name="previousState"></param>
	/// <param name="propertyNames"></param>
	/// <param name="types"></param>
	/// <returns></returns>
	public override int[] FindDirty(object entity, object id, object[] currentState,
	object[] previousState, string[] propertyNames, IType[] types)
	{
		List<int> dirty = new List<int>();

		//---------------------------------------------
		// Mark as dirty for all except for ....      |
		//---------------------------------------------
		for (int i = 0; i < propertyNames.Length; i++)
		{
			if (propertyNames[i] != "ColumnIDontwantInSql" && propertyNames[i] != "AnotherColumnIDontwantInSql")
			{
				dirty.Add(i);
			}
		}
		return dirty.ToArray();
	}
}

Wiring Up

CODE SNIPPET FROM UNIT OF WORK



 public UnitOfWork(INHibernateContext context, ISaveInterceptor interceptor)
 {
     this.context = context;
     this.Interceptor = interceptor;

     // See here for why dummy session
     ISession dummy = context.SessionFactory.OpenSession(this.Interceptor);
     this.Session = context.SessionFactory.OpenSession(dummy.Connection, this.Interceptor);
 }

NHibernate – the given key was not present in the dictionary

May 29, 2019

The Problem

Using Hibernate on a (.Net/C#) project and came to delete a record from a “collection” and this threw an error

the given key was not present in the dictionary

After much head scratching it was determined that the problem was down to a subtle interaction between NHibernate and a DataBase C# entity class.The class overrode the GetHashCod() method

 

public override int GetHashCode()

{
   ...
}

Originally the underlying database table has a composite key utilising two integer columns, the GetHashCode() method used both of these columns to generate the (unique) hash code. A database modification moved from a composite key to a single key, however, the GetHashCode() method was not updated.

Everything worked fine for read but Delete threw an exception. So what was going on?

Upon investigation it was found that, as part of NHibernate initialisation or lazy-loading, when reading the data the primary key column was populated but the defunct key column was zero, but the GetHashCode() method was called. Later on in the lifecycle all the properties of the Db class were populated and this meant a different hash code was generated (as the defunct column’s value was populated and the GetHashCode() method used this value as well as the primary key value – see earlier). So it looks like that, initially, items were read by NHibernate and added to it’s internal “collection” with hash-codes from partially loaded data, whereas the delete was being made for an item with a hash-code generated from fully populated data – and NHibernate could not find that item in the collection. It looked like NHibernate was using the hash-code to identify individual items.

The solution

Generate a hash-code (GetHashCode() method) using only the primary key.

 

Unit Testing Protected and Private Methods

February 6, 2019

The problem

You write a class in true SOLID tradition, and then you want to write the unit tests (or you do true TDD and do the reverse).

All well and good until you want to test some “internal” protected or private methods.

Purists would say you only need to test the external public interface. My response is that this is rubbish, you should test bite-sized pieces of fuctionality, especially if you are writing base classes (and no I don’t want to get into a discussion of programming against interfaces only and not using inheritance)

The Solution

After some googling and manipulation I discovered the Microsoft PrivateObject class (in the Microsoft.VisualStudio.QualityTools.UnitTestFramework assembly). This allows the “wrapping” of the class to be tested and then it’s protected or private methods can be invoked.

I discovered a wrapper to this PrivateObject class which makes unit testing straightforward e.g. if class ClassToTest has a protected method with signature ProctedMethod(int,string) then it can be invoked for testing as:

var x = new ClasstoTest();
dynamic target = new DynamicAccessor(x, typeof(ClassToTest));
target.ProtectedMethod(1,"abcd");

 

This has worked fine and dandy until trying to test a class with generic methods. I found some information on StackOverflow (this article, and this one)  I modified the class to use reflection and it works for most generic methods (it’s still not perfect).

The Code

 

  /// <summary>
    /// DynamicAccessor
    ///
    /// Class to be utilised in Unit Tests to allow protected and private
    /// members and properties to be called from external tests
    ///
    /// Not perfect and based on someone else's hard word along with
    /// a bit of hot-rod magic
    /// 
    /// </summary>
    public class DynamicAccessor : DynamicObject
    {
        public PrivateObject privateObject;
        private object parentObject;

        public DynamicAccessor(object d)
        {
            this.privateObject = new PrivateObject(d);
        }

        public DynamicAccessor(object d, Type t)
        {
            this.parentObject = d;
            this.privateObject = new PrivateObject(d, new PrivateType(t));
        }


        /// <summary>
        /// The try invoke member.
        ///
        /// Doesn't work as is with Generic<T> methods
        ///
        /// so use a combination of
        /// https://stackoverflow.com/questions/5492373/get-generic-type-of-call-to-method-in-dynamic-object
        /// to get type params and
        ///  https://stackoverflow.com/questions/42006662/testing-private-static-generic-methods-in-c-sharp
        /// to invoke
        ///
        /// Hot Rod Programming (DJ)
        /// 
        /// </summary>
        /// <param name="binder">
        /// The binder.
        /// </param>
        /// <param name="args">
        /// The args.
        /// </param>
        /// <param name="result">
        /// The result.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
        {
            try
            {
                // https://stackoverflow.com/questions/5492373/get-generic-type-of-call-to-method-in-dynamic-object
                var csharpBinder = binder.GetType().GetInterface("Microsoft.CSharp.RuntimeBinder.ICSharpInvokeOrInvokeMemberBinder");
                var typeArgs = (csharpBinder.GetProperty("TypeArguments").GetValue(binder, null) as IList<Type>);

                //------------------------------------
                // if typeargs then a generic method |
                //------------------------------------
                if (typeArgs.Any())
                {
                    //----------------------------------------------------------------------------------------------------
                    // Use reflection to get to method                                                                   |
                    // https://stackoverflow.com/questions/42006662/testing-private-static-generic-methods-in-c-sharp    |
                    //----------------------------------------------------------------------------------------------------


                    MethodInfo fooMethod = this.parentObject.GetType().GetMethod(binder.Name, BindingFlags.NonPublic | BindingFlags.Instance);
                    if (fooMethod == null)
                    {
                        result = null;
                        return false;
                    }
                    //-------------------------------------------
                    // Turn Into Generic and invoke with params |
                    //-------------------------------------------
                    MethodInfo genericFooMethod = fooMethod.MakeGenericMethod(typeArgs.ToArray());
                    result = genericFooMethod.Invoke(this.parentObject, args);
                }
                else
                {
                    //-----------------------------
                    // Non Generic so just invoke |
                    //-----------------------------
                    result = privateObject.Invoke(binder.Name, args);
                }

                return true;
            }
            catch (MissingMethodException)
            {
                result = null;
                return false;
            }
        }

        public void SetProperty(string propName, object o)
        {
            this.privateObject.SetProperty(propName, o);
        }
    }

 

NHibernate Connection Cycling

July 26, 2018

The Problem

On a webAPI (C#/.Net 4) using NHibernate 4 an issue was observed under stress testing. The issue was associated with the user-impersonation being done on the database connection – the impersonation would work correctly, however, for subsequent database operations would fail. After much (and I do mean much) investigation it was found that the connections seem to be “cycled” amongst the NHibernate sessions – so we could observe the session using a connection with one particular HashCode (unique object identifier) and see the user-impersonation SQL execute, but when it came to some ORM write-backs to the DB another connection with another user’s impersonation (and differing HashCode) was observed in the session for the db operation.

Weird or what ?

The Solution

I must give a round of applause to the guys at StackOverflow for this one.

Basically, create a dummy session from the session factory , then pass the connection of this session to the OpenSession method of the session factory to create the session you’re going to use.

Simples

ISession dummy = sessionFactory.Factory.OpenSession();
this.Session = sessionFactory.Factory.OpenSession(dummy.Connection);

 

.NET DataSet to ADO RecordSet Conversion

July 14, 2018

The Problem

Converting an ADO recordset into a .NET DataSet is straightforward, the following code will achieve this

Dim da As New System.Data.OleDb.OleDbDataAdapter<br/>
da.Fill(ds, rs, "ADODB.RecordSet") 

where ds is a DataSet and rs is an ADO Recordset

So you would think that going from a DataSet to an ADO Recordset would be just as simple. Wrong ! This conversion is not built into .NET 1 or 2, the only information I could find on how to do this is article which utilises and XSL stylesheet to transform the data. So I modified the code from this article and have coded up an object which does the conversion.

In addition I can also access the ADO recordset XML as a string from this object. Why would I want to do this ? Well, if you want to pass back an ADO recordset as part of web service results you can’t, you get an error as the web service code can’t serialise the ADO recordset. The way round this is to pass the ADO recordset XML representation as a string over the web service and convert it back into and ADO recordset at the receiving end (this could be a legacy ASP app accessing the web-service via SOAP or XMLHTTP).

The Solution

'-------------------------------------------------------------------------- 
' File : DataConversion.vb 
' 
' Author : DJ 
' 
' Version : <VSS Version Stamp> 
' 
' Purpose : Routines to convert DataSet to ADO Recordset etc etc etc. 
' 
' This object uses and XSLT to transform dataset into ADO recordset. I have 
' modified code from MS KB article to avoid using a temporary file for output. 
' I build up a string of the XML representation of the ADO recordset which can 
' then be sent back to the caller 'as xml' which can be stuffed into an ADO recordset 
' 
' It is a shame that MS did not include Dataset<->Recordset conversion as part 
' of .NET n or .NET n+1 
' 
' Modification History:

' Taken from http://support.microsoft.com/kb/316337 
' 
'-------------------------------------------------------------------------- 
Imports Microsoft.VisualBasic 
Imports System.Data 
Imports System.Xml 
Imports System.Xml.XPath 
Imports System.Xml.Xsl 
Imports System.IO 
Public Class DataConversion

Private xmlstr As String 
Private quote = "'" 
Private error_message As String

Public Sub New() 
Me.error_message = "" 
Me.xmlstr = "" 
End Sub 
Public Property ErrorMessage() 
Get 
Return Me.error_message 
End Get 
Set(ByVal Value) 
'NOP 
End Set 
End Property

'************************************************************************* 
' Class Name : ConvertToRs 
' Description : This class converts a DataSet to a ADODB Recordset. 
'**************************************************************************

'************************************************************************** 
' Method Name : GetADORS 
' Description : Takes a DataSet and converts into a Recordset. The converted 
' ADODB recordset is saved as an XML file. The data is saved 
' to the file path passed as parameter. 
' Output : The output of this method is long. Returns 1 if successfull. 
' If not throws an exception. 
' Input parameters: 
' 1. DataSet object 
' 2. Database Name 
' 3. Output file - where the converted should be written. 
'**************************************************************************

Public Function GetXML() 
Return Me.xmlstr 
End Function 
'---------------------------------------------------------------- 
Public Function GetRS() As ADODB.Recordset 
'---------------------------------------------------------------- 
' Purpose 
' Turn XML string into ADO Recordset 
' 
' Input Params 
' Returns 
' 
'---------------------------------------------------------------- 
Dim strm As New ADODB.Stream 
Dim res_rs As New ADODB.Recordset

'------------------------------------------- 
' Open a stream and write XML String to it | 
'------------------------------------------- 
strm.Open() 
strm.WriteText(Me.xmlstr)

'---------------- 
' Reset positin | 
'---------------- 
strm.Position = 0

'------------------------- 
' Read it into recordset | 
'------------------------- 
res_rs.Open(strm)

GetRS = res_rs

End Function 
Public Function ConvertDSToXML(ByVal ds As DataSet, ByVal xslfile As String) As Boolean

Me.xmlstr = ""

'Create an xmlwriter object, to write the ADO Recordset Format XML 
Try 
' Dim xwriter As New XmlTextWriter(outputfile, System.Text.Encoding.Default)

'call this Sub to write the ADONamespaces to the XMLTextWriter 
WriteADONamespaces() 
'call this Sub to write the ADO Recordset Schema 
WriteSchemaElement(ds)

Dim TransformedDatastrm As New MemoryStream

TransformedDatastrm = TransformData(ds, xslfile) 
'Pass the Transformed ADO REcordset XML to this Sub 
'to write in correct format. 
HackADOXML(TransformedDatastrm)

Return True

Catch ex As Exception 
'Returns error message to the calling function. 
Me.error_message = ex.Message & " - " & ex.ToString 
Return False 
End Try

End Function

Private Sub WriteADONamespaces() 
'The following is to specify the encoding of the xml file 
'WriteProcessingInstruction("xml", "version='1.0' encoding='ISO-8859-1'")

'The following is the ado recordset format 
'<xml xmlns:s='uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882' 
' xmlns:dt='uuid:C2F41010-65B3-11d1-A29F-00AA00C14882' 
' xmlns:rs='urn:schemas-microsoft-com:rowset' 
' xmlns:z='#RowsetSchema'> 
' </xml>

'Write the root element 
WriteStartElement("xml", "")

'Append the ADO Recordset namespaces 
WriteAttributeString("xmlns", "s", "uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882") 
WriteAttributeString("xmlns", "dt", "uuid:C2F41010-65B3-11d1-A29F-00AA00C14882") 
WriteAttributeString("xmlns", "rs", "urn:schemas-microsoft-com:rowset") 
WriteAttributeString("xmlns", "z", "#RowsetSchema") 
WriteEndStartElement()

End Sub

Private Sub WriteSchemaElement(ByVal ds As DataSet) 
'ADO Recordset format for defining the schema 
' <s:Schema id='RowsetSchema'> 
' <s:ElementType name='row' content='eltOnly' rs:updatable='true'> 
' </s:ElementType> 
' </s:Schema>

'write element schema 
WriteStartElement("s", "Schema") 
WriteAttributeString("id", "RowsetSchema") 
WriteEndStartElement()

'write element ElementTyoe 
WriteStartElement("s", "ElementType")

'write the attributes for ElementType 
WriteAttributeString("name", "row") 
WriteAttributeString("content", "eltOnly") 
WriteAttributeString("rs:updatable", "true")

WriteEndStartElement()

WriteSchema(ds) 
'write the end element for ElementType

WriteFullEndElement("s", "ElementType") 
'write the end element for Schema

WriteFullEndElement("s", "Schema")


End Sub

Private Sub WriteSchema(ByVal ds As DataSet)

Dim i As Int32 = 1 
Dim dc As DataColumn

For Each dc In ds.Tables(0).Columns

dc.ColumnMapping = MappingType.Attribute

WriteStartElement("s", "AttributeType") 
'write all the attributes 
WriteAttributeString("name", dc.ToString) 
WriteAttributeString("rs", "number", i.ToString) 
WriteAttributeString("rs", "baseCatalog", "") 
WriteAttributeString("rs", "baseTable", dc.Table.TableName.ToString) 
WriteAttributeString("rs", "keycolumn", dc.Unique.ToString) 
WriteAttributeString("rs", "autoincrement", dc.AutoIncrement.ToString) 
WriteEndStartElement()

'write child element 
WriteStartElement("s", "datatype") 
'write attributes 
WriteAttributeString("dt", "type", GetDatatype(dc.DataType.ToString)) 
WriteAttributeString("dt", "maxlength", dc.MaxLength.ToString) 
WriteAttributeString("rs", "maybenull", dc.AllowDBNull.ToString) 
WriteEndStartElement() 
WriteFullEndElement("s", "datatype")

'write end element for datatype 
'end element for AttributeType 
WriteFullEndElement("s", "AttributeType")

i = i + 1 
Next 
dc = Nothing

End Sub

'Function to get the ADO compatible datatype 
Private Function GetDatatype(ByVal dtype As String) As String 
Select Case (dtype) 
Case "System.Int32" 
Return "int" 
Case "System.DateTime" 
Return "dateTime" 
End Select 
End Function

'Transform the data set format to ADO Recordset format 
'This only transforms the data 
Private Function TransformData(ByVal ds As DataSet, ByVal xslfile As String) As MemoryStream

Dim instream As New MemoryStream 
Dim outstream As New MemoryStream

'write the xml into a memorystream 
ds.WriteXml(instream, XmlWriteMode.IgnoreSchema) 
instream.Position = 0

'load the xsl document 
Dim xslt As New XslTransform 
xslt.Load(xslfile)

'create the xmltextreader using the memory stream 
Dim xmltr As New XmlTextReader(instream) 
'create the xpathdoc 
Dim xpathdoc As XPathDocument = New XPathDocument(xmltr)

'create XpathNavigator 
Dim nav As XPathNavigator 
nav = xpathdoc.CreateNavigator

'Create the XsltArgumentList. 
Dim xslArg As XsltArgumentList = New XsltArgumentList

'Create a parameter that represents the current date and time.

xslArg.AddParam("tablename", "", ds.Tables(0).TableName)

'transform the xml to a memory stream 
xslt.Transform(nav, xslArg, outstream)

instream = Nothing 
xslt = Nothing 
' xmltr = Nothing 
xpathdoc = Nothing


nav = Nothing

Return outstream

End Function

''************************************************************************** 
'' Method Name : ConvertToRs 
'' Description : The XSLT does not tranform with fullendelements. For example, 
'' <root attr=""/> intead of <root attr=""><root/>. ADO Recordset 
'' cannot read this. This method is used to convert the 
'' elements to have fullendelements. 
''************************************************************************** 
Private Sub HackADOXML(ByVal ADOXmlStream As System.IO.MemoryStream)

ADOXmlStream.Position = 0 
Dim rdr As New XmlTextReader(ADOXmlStream) 
Dim outStream As New MemoryStream 
Dim wrt As New XmlTextWriter(outStream, System.Text.Encoding.Default)

rdr.MoveToContent() 
'if the ReadState is not EndofFile, read the XmlTextReader for nodes. 
Do While rdr.ReadState <> ReadState.EndOfFile 
If rdr.Name = "s:Schema" Then 
wrt.WriteNode(rdr, False) 
wrt.Flush() 
ElseIf rdr.Name = "z:row" And rdr.NodeType = XmlNodeType.Element Then 
wrt.WriteStartElement("z", "row", "#RowsetSchema") 
rdr.MoveToFirstAttribute() 
wrt.WriteAttributes(rdr, False) 
wrt.Flush() 
ElseIf rdr.Name = "z:row" And rdr.NodeType = XmlNodeType.EndElement Then 
'The following is the key statement that closes the z:row 
'element without generating a full end element 
wrt.WriteEndElement() 
wrt.Flush() 
ElseIf rdr.Name = "rs:data" And rdr.NodeType = XmlNodeType.Element Then 
wrt.WriteStartElement("rs", "data", "urn:schemas-microsoft-com:rowset") 
ElseIf rdr.Name = "rs:data" And rdr.NodeType = XmlNodeType.EndElement Then 
wrt.WriteEndElement() 
wrt.Flush() 
End If 
rdr.Read() 
Loop

' wrt.WriteEndElement() 
wrt.Flush()


'--------- 
' Kludge | 
'--------- 
Dim byteArray = New Byte(CType(outStream.Length, Integer)) {} 
Dim xstr As String

outStream.Position = 0 
outStream.Read(byteArray, 0, outStream.Length)

xstr = System.Text.Encoding.ASCII.GetString(byteArray) 
' remove trailing null 
xstr = Left(xstr, Len(xstr) - 1) 
Me.xmlstr &= xstr

WriteFullEndElement("xml", "")

End Sub 
Private Sub WriteStartElement(ByVal tag, ByVal val)

Me.xmlstr &= "<" & tag 
If (val <> "") Then Me.xmlstr &= ":" & val 
End Sub

Private Sub WriteAttributeString(ByVal tag, ByVal val) 
Me.xmlstr &= " " & tag & "=" & quote & val & quote

End Sub 
Private Sub WriteAttributeString(ByVal tag1, ByVal tag2, ByVal val) 
Me.xmlstr &= " " & tag1 & ":" & tag2 & "=" & quote & val & quote

End Sub

Private Sub WriteFullEndElement(ByVal tag, ByVal val) 

Me.xmlstr &= "</" & tag 
If (val <> "") Then Me.xmlstr &= ":" & val 
Me.xmlstr &= ">"

End Sub


Private Sub WriteEndStartElement()

Me.xmlstr &= ">" & vbCrLf 
End Sub

Public Function RsToXML(ByVal rs As ADODB._Recordset, ByRef outputXml As String) As Boolean 
'---------------------------------------------------------------- 
' Purpose 
' Convert and ADO Recordset into an XML String 
' Input Params 
' ADO Recordset 
' Returns 
' XML String 
'----------------------------------------------------------------

Try 
Dim streamObj As New ADODB.Stream

rs.Save(streamObj, ADODB.PersistFormatEnum.adPersistXML)

outputXml = streamObj.ReadText()

Return True 
Catch ex As Exception 
Me.error_message = ex.Message & " - " & ex.ToString 
Return False 
End Try

End Function 
Public Function RStoDS(ByVal rs As ADODB._Recordset, ByRef ds As DataSet) As Boolean 
Try 
Dim da As New System.Data.OleDb.OleDbDataAdapter 
da.Fill(ds, rs, "ADODB.RecordSet") 
Return True 
Catch ex As Exception

Me.error_message = ex.Message & " - " & ex.ToString 
Return False 
End Try

End Function 


End Class
<?xml version="1.0"?> 
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"
xmlns:rs="urn:schemas-microsoft-com:rowset"
xmlns:z="#RowsetSchema">
<xsl:output method="xml" indent="yes"/>
<xsl:param name="tablename"/>
<xsl:template match="NewDataSet">
<rs:data>
<xsl:for-each select="./node()[local-name(.)=$tablename]">
<z:row>
<xsl:for-each select="@*">
<xsl:copy-of select="."/>
</xsl:for-each>
</z:row>
</xsl:for-each>
</rs:data>
</xsl:template>
</xsl:stylesheet>

 

sddsad

DNS, BIND, root files and forwarders

July 14, 2018

The Problem

Suppose you have a BIND-9 server on an intranet acting as master or slave for the root (‘.’) zone. Then, for an extranet connection you put a forward zone in named.conf….Voila, named will not forward any requests no matter what you do if it is slave (or master) for root.

The Solution

How do you solve it ? Well, you have to put a ‘dummy’ delegation in the root zone file for the zone then named will override this with your forwarders directive.

Simple when you know how….

Can’t Write CDs from Windows

July 14, 2018

The Problem

I used to be able to write CD’s directly from Windows XP by ‘sending’ files directly to the drive and then ‘writing’ the CD. One day this stopped working and all I got when trying to write the files was “there is no disc in the drive” message. However, other CD-writing programs still worked so the CD-RW drive was not out of order. What was going on ?

After judicious googling I found two items of interest.

Registry

Firstly, the properties of the CD-RW are held in the registry in

HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\CD Burning\Drives

The values for this key are

1 – CD-R Drive
2- CD-RW Drive
3- Just a CD

So make sure this value is 1 or 2.

Mine was set to 3 so I changed it to 2, however, the drive still would not write CDs.

Security Settings

Next I found an article about Local Security Settings. Goto to control-panel->Administrative Tools and open “Local Security Policy”. Click the “Security Options” item and look for item “Devices: Restrict CD-ROM access to locally logged-on users only”.

I disabled this and…voila I can now write CDs from Windows.

WARNING

I am not convinced that it is correct to disable this item but I needed my CD-RW working again !