Skip to content

DRNJ

Light at the end of the Technology Tunnel

  • Home
  • About
  • Contact
DRNJ

Month: July 2018

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);

 

DotNet, WebAPI

.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

Uncategorized

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….

Uncategorized

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 !

Windows

Outlook Stopped Automatically Sending and Receiving

July 14, 2018

My Outlook 2007 stopped automatically sending and receiving emails. Strange ! I checked the settings (Tools->Options->Mail-Settings(tab)->Send/Receive) – it was set to ‘Schedule and automatic send/receive’ every minute. Still no automatic send/receive.

I performed windows updates. No effect

I deleted and recreated my email profile (via control-panel->mail). No effect

Then I stumbled upon the dialog

Tools->Send/Receive->Send/Receive Settings

and at the bottom is an item called ‘Disable Scheduled Send/Receive’. It was selected !!! Unselect it and, voila, send/receive works !

Question is, how did it get set in the first place ?

Windows

IPSec and AES Update

July 14, 2018

h3. IPSec

In my previous note I described how to get IPSec working to encrypt wireless or other traffic. I managed to get it working with triple-DES encryption but I could not get it to tunnel when using AES (and SHA1 hash). I particulary wanted to get this working to be able to tunnel my mobile-broadband connection back to base and from there out to the internet – who knows who snoops your mobile broadband traffic !

After some time playing I saw error messages in my unix log concerning MTU. So I searched and found an article about reducing MTU sizes on windows.

I reduced my MTU size to 1420 bytes and…voila…AES encryption/tunnelling works !

Simples.

Security

“No such interface supported” error in windows 7

July 14, 2018

After installed IE 10 on Windows 7/85 I got this error from various applications. Also, right-click “Open folder in windows explorer” stopped working inside Visual Studio.

The solution ?

Many thanks to <a href=”http://pyrocam.com/re-register-all-dlls-to-fix-no-such-interface-supported-error-in-windows-7-after-installing-ie7-standalone/”>these guys</a>

Basically, do

Dir *.dll /s /b > c:\regdll.bat

then replace c:\ with Regsvr32.exe /s c:\

and run the bat file

Windows

Recent Posts

  • AutoMapper and “Could not load type ‘SqlGuidCaster'” Error
  • OpenVPN on Docker and the Strange Error Message Saga
  • Docker CLI and Compose Information Message
  • Docker Containers and Azure – An Introduction
  • Serilog in .Net Core 6

Recent Comments

    Archives

    • April 2025
    • December 2024
    • April 2024
    • September 2022
    • November 2021
    • June 2021
    • March 2021
    • July 2020
    • April 2020
    • November 2019
    • September 2019
    • July 2019
    • May 2019
    • February 2019
    • July 2018
    • June 2018

    Categories

    • .NET Core
    • Azure
    • Docker
    • DotNet
    • Security
    • Uncategorized
    • WebAPI
    • Windows

    Meta

    • Log in
    • Entries feed
    • Comments feed
    • WordPress.org

    Idealist by NewMediaThemes