Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6730441
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T10:24:32+00:00 2026-05-26T10:24:32+00:00

I have a scenario where I am synchronizing data between multiple VERY dissimilar systems.

  • 0

I have a scenario where I am synchronizing data between multiple VERY dissimilar systems. (The data itself is similar but the tables on the different systems have quite different formats.) To assist with this synchronization, I have a database table which stores object hashes from each of the systems along with item keys and other relevant information. When the hash of an object from either system changes, I update the other.

My database table looks something like this.

CREATE TABLE [dbo].[SyncHashes](
    [SyncHashId] [int] IDENTITY(1,1) NOT NULL,
    [ObjectName] [nvarchar](50) NULL,
    [MappingTypeValue] [nvarchar](25) NULL,
    [MappingDirectionValue] [nvarchar](25) NULL,
    [SourceSystem] [nvarchar](50) NULL,
    [SourceKey] [nvarchar](200) NULL,
    [SourceHash] [nvarchar](50) NULL,
    [TargetSystem] [nvarchar](50) NULL,
    [TargetKey] [nvarchar](200) NULL,
    [TargetHash] [nvarchar](50) NULL,
    [UpdateNeededValue] [nvarchar](max) NULL,
    [CreatedOn] [datetime] NULL,
    [ModifiedOn] [datetime] NULL,
    [Version] [timestamp] NOT NULL, 
    [IsActive] [bit] NOT NULL,
PRIMARY KEY CLUSTERED 
(
    [SyncHashId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

So far so good. But…

In order to effectively compute a hash (such as an MD5 hash (which is what i am using)) for an object, you need to be able to convert it to a byte array.

And…

It seems that in order to convert an object to a byte array, it must be serializable. (At least that’s what I have read, and the errors I am getting from .NET seem to indicate that is true.)

For one of the systems, I have the ability to make all of my database objects serializable so that’s great. Hashes get generated, everything gets synchronized, and the world is beautiful!

For another system, things are not so great. I am passed a database context from entity framework 4 (code first) model and the entities are NOT serialized.

When I attempt to cast as byte using something like the following, .NET complains and throws a minor tantrum–all the while refusing to give me the nice little byte array I so politely asked for.

foreach(var dataItem in context.TableName)
{
    var byteArray = (byte[]) dataItem;
}

Ok. No problem.

I have myself a nice little extension method which I thought might do the trick.

public static byte[] ObjectToByteArray<T>(this T obj)
{
    if (obj == null)
        return null;
    BinaryFormatter bf = new BinaryFormatter();
    MemoryStream ms = new MemoryStream();

    bf.Serialize(ms, obj);
    return ms.ToArray();
}

But oh no! If the object (the Entity) is not serializable, this routine throws me another nice little (and totally expected) exception.

So… I modify the routine and add a where clause to the method definition like so.

public static byte[] ObjectToByteArray<T>(this T obj) where T : ISerializable
{
    if (obj == null)
        return null;
    BinaryFormatter bf = new BinaryFormatter();
    MemoryStream ms = new MemoryStream();

    bf.Serialize(ms, obj);
    return ms.ToArray();
}

The only problem is that now I am back to square one where all of my objects need to be serializable to get a byte array.

Hmmm. Not good.

So I put together a hack to iterate through all of the object’s properties and generate a string representation from which I could build a byte array. It was UGLY and INEFFICIENT but it kind of sort of did the trick.

public static string ComputeMD5Hash<T>(this T input)
{
    StringBuilder sb = new StringBuilder();

    Type t = input.GetType();
    PropertyInfo[] properties = t.GetProperties();

    foreach (var property in properties)
    {
        sb.Append(property.Name);
        sb.Append("|");
        object value = property.GetValue(input, null);
        if (value != null)
        {
            sb.Append(value);
        }
        sb.Append("|");
    }

    return MD5HashGenerator.GenerateKey(sb.ToString());
}

But…

After all that, what I still really would like to be able to is efficiently and properly to create a byte array from an object whose class is not marked as serializable. What is the best way to accomplish this?

Thank you in advance!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T10:24:33+00:00Added an answer on May 26, 2026 at 10:24 am

    create a byte array from an object whose class is not marked as serializable

    You can use protobuf-net v2 to accomplish this. Download the zip then reference the protobuf-net assembly.

    Consider this simple class definition we want to serialize:

    public class Person
    {
        public string Firstname { get; set; }
        public string Surname { get; set; }
        public int Age { get; set; }
    }
    

    You can then serialize this as a byte array:

    var person = new Person {Firstname = "John", Surname = "Smith", Age = 30};
    var model = ProtoBuf.Meta.TypeModel.Create();
    //add all properties you want to serialize. 
    //in this case we just loop over all the public properties of the class
    //Order by name so the properties are in a predictable order
    var properties = typeof (Person).GetProperties().Select(p => p.Name).OrderBy(name => name).ToArray();
    model.Add(typeof(Person), true).Add(properties);
    
    byte[] bytes;
    
    using (var memoryStream = new MemoryStream())
    {
        model.Serialize(memoryStream, person);
        bytes = memoryStream.GetBuffer();
    }
    

    The protobuf-net serializer will serialize much faster and produce a smaller byte[] array than BinaryFormatter

    caveat 1 This will only (in its current form) serialize the public properties of your class, which looks ok for your usage.
    caveat 2 This is considered brittle because adding a new property to Person may mean you are unable to deserialize a Person object that was serialized with the prior TypeModel.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a scenario where multiple users will be doing import processes, but all
I have this scenario where I need data integrity in the physical database. For
I have a scenario where I have one thread that loops between waiting and
I have a scenario with code like the following: extracted_data = data.map{|row| ((row.some_long_number.to_f) if
I have a scenario where I get a data table with 65 columns and
I have a scenario where I would like to update multiple fields in multiple
Have a scenario where i need to compile my project with jdk 1.5 but
I have a scenario where data needs to be imported from a CSV file
I have a scenario like this: There are two tables table1 and table2 .
I have scenario, I have two update panels on the page (both have update

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.