65.9K
CodeProject is changing. Read more.
Home

ADODB Serialization

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.33/5 (3 votes)

Sep 26, 2006

CPOL
viewsIcon

37811

How to serialize and deserialize an ADODB Recordset.

Introduction

I came across a need to create a .NET interface to allow a COM client to use .NET Remoting. The COM client heavily uses ADO Recordsets.

When using Remoting, it is not possible to send an ADO Recordset as a return value. The same will apply when using a Web Service.

I tried Googling on the subject, but the only article I found was to save the Recordset as a DataSet, then save it back to an ADODB Recordset. There had to be an easier solution. After trial and errors, I found the perfect solution (it could be adapted easily for a Web Service: simply uuEncode and decode the byte array).

Here it is, with just a few lines of code....

The Code

using System;
using ADODB;

namespace InteropSample
{
    public static class RsUtil
    {
        public static byte[] SerializeRs(Recordset rs)
        {
            ADODB.Stream s = new ADODB.Stream();
            rs.Save(s, ADODB.PersistFormatEnum.adPersistADTG);
            return (byte[])s.Read(s.Size);
        }
        public static Recordset DeserializeRs(byte[] data)
        {
            ADODB.Stream s = new ADODB.Stream();
            s.Open(Missing.Value, ConnectModeEnum.adModeUnknown, 
            ADODB.StreamOpenOptionsEnum.adOpenStreamUnspecified, "", "");
            s.Type = ADODB.StreamTypeEnum.adTypeBinary;
            s.Write(data);
            s.Position = 0;
            Recordset rs = new Recordset();
            rs.Open(s, Missing.Value, CursorTypeEnum.adOpenUnspecified, 
            LockTypeEnum.adLockUnspecified, -1);
            return rs;
        }
    }
}