지금은 매우 좌절 문제가 발생하고 있습니다. 좀 더 쉽게하기 위해 문제를 추상화하려고 노력할 것입니다. 내 사용자 지정 개체를 한 프로세스에서 데이터베이스로 serialize하고 다른 프로세스에서 deserialize해야합니다.MemoryStream deserializing - 예기치 않은 동작
나는 두 개의 단편을 가지고 있습니다. AppToDB.dll
및 AppFromDB.dll
. 제 3의 어셈블리 - MyCustomObject.dll
-이 두 어셈블리 모두에 대한 참조가 들어 있습니다. MyCustomObject.dll
은 MarshalByRefObject
까지 확장됩니다. 당신이 MemoryStream
객체를 볼 수있는 코드의 두 조각, 그래서
public OCR.Batch deserializeFromDB()
{
MemoryStream memStream = new MemoryStream();
try
{
string queryString = "SELECT object FROM FCBatch";
OdbcCommand command = new OdbcCommand(queryString, connection);
OdbcDataReader reader = command.ExecuteReader(CommandBehavior.SequentialAccess);
// Size of the BLOB buffer.
int bufferSize = 100;
// The BLOB byte[] buffer to be filled by GetBytes.
byte[] outByte = new byte[bufferSize];
// The bytes returned from GetBytes.
long retval;
// The starting position in the BLOB output.
long startIndex = 0;
MemoryStream dbStream = new MemoryStream();
while (reader.Read())
{
// Reset the starting byte for the new BLOB.
startIndex = 0;
// Read bytes into outByte[] and retain the number of bytes returned.
retval = reader.GetBytes(0, startIndex, outByte, 0, bufferSize);
// Continue while there are bytes beyond the size of the buffer.
while (retval == bufferSize)
{
dbStream.Write(outByte, 0, bufferSize);
dbStream.Flush();
// Reposition start index to end of last buffer and fill buffer.
startIndex += bufferSize;
retval = reader.GetBytes(0, startIndex, outByte, 0, bufferSize);
}
// Write the remaining buffer.
dbStream.Write(outByte, 0, (int)retval);
dbStream.Flush();
}
// Close the reader and the connection.
reader.Close();
dbStream.Position = 0;
object temp = oBFormatter.Deserialize(dbStream);
MyCustomObject obj = (MyCustomObject)temp;
return null;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return null;
}
}
OK : AppFromDB.dll
에서
public bool serializeToDB(MyCustomObject obj)
{
OdbcDataAdapter da = new OdbcDataAdapter();
MemoryStream memStream = new MemoryStream();
try
{
ObjRef marshalledObj = RemotingServices.Marshal((System.MarshalByRefObject)obj);
// Serialize the object; construct the desired formatter
IFormatter oBFormatter = new BinaryFormatter();
// Try to serialize the object
oBFormatter.Serialize(memStream, marshalledObj);
// Create byte array
byte[] serialized = memStream.ToArray();
// Build the query to write to the database
string queryString =
"INSERT INTO MyCustomObject(id, object) VALUES(?, ?)";
OdbcCommand command = new OdbcCommand(queryString, connection);
command.Parameters.AddWithValue("id", 1);
command.Parameters.AddWithValue("object", serialized);
// Write the object byte array to the database
int num = command.ExecuteNonQuery();
}
catch { }
}
이 코드를 실행 : 내 AppToDB.dll
에서
는 다음 코드를 실행합니다. 처음에는 AppToDB
이 만들어졌으며 내용을 보면 707 바이트가 들어 있습니다. 벌금. 나는 그것을 데이터베이스에 쓰고 BLOB로 저장한다. 이제 AppFromDB
에서 BLOB를 검색하여 byte[]
배열에 저장합니다. 배열을 MemoryStream
에 다시 쓰고 내 MemoryStream
개체에 707 바이트가 들어 있는지 확인하십시오.이 모든 것은 원본과 동일합니다. 내가 성공한 물건을 옮겼던 것 같습니다!
이제 문제는 object temp = oBFormatter.Deserialize(dbStream);
입니다. 역 직렬화하려고하면 object
은 투명한 프록시이므로 MyCustomObject
으로 전송할 수 없습니다 !! 원본 개체를 다시 얻으려면 어떻게해야합니까? # @ &의 이름은 MemoryStream 객체를 가질 수 있습니다 ... 메모리에서 ... 직렬화 할 준비가되었습니다 ... 그리고 갑자기 Transparent Proxy가 다시 나타납니다.
실종되었습니다. 도움을 주시면 감사하겠습니다. 내가 답을 가지고있는 하나 & @ #기도합니다;
편집) 1 확인을, 나는 일들이 문제가 계속하지만) (이제 이해하기 시작 말해야한다. 내 문제 : 한쪽에 객체 (상태 포함)가 있고 데이터베이스에 저장해야하므로 다른 일에 나중에 다른 프로세스에서 사용할 수 있습니다.
제 객체는 직렬화 가능으로 표시되지 않은 타사 객체를 래핑하기 때문에 직렬화 할 수 없습니다. 그래서 내 유일한 옵션은 직렬화가 가능한 ObjRef를 반환하는 마샬링 (marshal) 인 것 같습니다. 그러나 당연히 - 일 후에 - 비 직렬화하는 객체는 참조 일 뿐이며 원래 객체는 사라졌습니다.
문제를 어떻게 해결할 수 있습니까? 더 많은 사람들이 발생해야합니다 난 그냥
편집 2 OK ... 답을 찾을 수가 없어, 나는 제 3 자 객체에 동형 내 자신의 직렬화 클래스를 작성하기 위하여려고하고있다 같아요. 그런 다음 전체 타사 객체를 실행하고 상태 정보 등을 저장/포장 한 다음 데이터베이스에 객체를 직렬화합니다. 내 유일한 옵션 인 것 같습니다.
편집 3 잠시 후이 문제로 다시 시작하십시오. 편집 2에 게시 된 솔루션이 작동하지 않더라도 실현되었습니다. 제 3 자 어셈블리가 알고있는 객체로 비 순차적으로 처리해야합니다.
중복 가능성 (http://stackoverflow.com/questions/3068702/how-to-marshal-an-object-and-its- [개체와 콘텐츠 (또는 객체) 마샬링 방법] content-also-objects) – Lucero