Can anybody help? I'm keeping an old Delphi7 project and have next trouble. How can I store BLOB field value if it contains Unicode string?
I tried:
var
str: WideString;
begin
...
str := WideString(Fields[1].AsString); - but I get empty string
...
...
str := VarToWideStr(Fields[1].AsVariant); - but I get "(BLOB)" result in str varible.
...
end;
My solution:
Code usage:
...
stream := TMemoryStream.Create;
try
Fields[1].SaveToStream(stream);
ss := MemStreamToWStr(stream);
finally
stream.Destroy;
end;
...
And function:
function TSnsFrame.MemStreamToWStr(Mstream: TMemoryStream): WideString;
begin
Mstream.Seek(0, soFromBeginning);
SetLength(Result, Mstream.size div 2);
MStream.ReadBuffer(Result[1], Mstream.size);
end;
Have a look at TDataSet.CreateBlobStream(). It returns a TStream that can be used to read/write the raw data of a blob field.
Related
I currently have a TMemoryStream that gets filled via reading a varbinary field, which is originally encoded by UTF8 standard from a MS SQL Server DB table.
The varbinary field contains a header part which needs to be removed before saving the remainder of the stream as a file.
I have successfully pulled out the header information required, which includes the file name, but haven’t
found a solution for then saving the remainder of the stream as a valid file.
The data is initially read into a TdxMemData dataset.
procedure TBaseDataPump.SaveAttachments(mtblAttachmentInfo: TdxMemData);
var
AFile: TMemoryStream;
ANewFile: TStringStream;
sFullPath: String;
wsImageBlob, wsHeader, wsBody: WideString;
iposition: Integer;
begin
if mtblAttachmentInfo.Active then // TdxMemData filled with data
begin
with mtblAttachmentInfo do
begin
First;
while NOT EOF do
begin
// Below code works fine to save the file without removing the data
AFile := TMemoryStream.Create; // Create the memory stream
TBlobField(FieldByName('ImageBlob')).SaveToStream(AFile);
// load the file image from the data to the memory strem
// Get the header content
ANewFile := TStringStream.Create('');
TBlobField(FieldByName('ImageBlob')).SaveToStream(ANewFile);
// read the filed again to a TStringStream
wsImageBlob := UTF8ToString(ANewFile.DataString);
// I can see the data as wide string and can find the header bit and its ending position on the
// its ending position on the string
iposition := AnsiPos(#13#13#10, wsImageBlob); // find the header ending position
// getting the header to another widestring
wsHeader := AnsiLeftStr(wsImageBlob,position);
wsHeader := AnsiLeftStr(wsImageBlob,POS(#9,wsHeader)-1);
wsHeader := StringReplace(wsHeader,'''','',[rfReplaceall]);
// need to save the stream from the position of the end of header as file
end;
end;
end;
end;
Found the solution with the copyfrom method. and its is as follows :
// Create the TStringStream
ANewFile := TStringStream.Create('');
try
TBlobField(FieldByName('ImageBlob')).SaveToStream(ANewFile);
// get the blob as a string so we can extract the header information
wsImageBlob := UTF8ToString(ANewFile.DataString);
position := AnsiPos(#13#13#10, wsImageBlob);
if position <> 0 then begin
// have header information to extract
position := position + 2;
wsHeader := AnsiLeftStr(wsImageBlob, position);
wsHeader := AnsiLeftStr(wsImageBlob, POS(#9, wsHeader) - 1);
wsHeader := StringReplace(wsHeader, '''', '', [rfReplaceall]);
sFilePath := sDirectorypath + wsHeader;
ANewFile.Position := position;
AFile := TMemoryStream.Create;
try
AFile.CopyFrom(ANewFile, ANewFile.Size - position);
AFile.SaveToFile(sFilePath);
finally
FreeAndNil(AFile);
end;
end
finally
FreeAndNil(ANewFile);
end;
I'm looking for informations on how to put TRichEdit into an Array and save it to Local file (ex: File.dat).
The goal is to store a number of text, with a description, and the 'name' of it.
I think I have to start with:
type
TMessage = record
Name : string;
Desc : string;
Text : TMemoryStream;
end;
var ARListMessages: array[1..50] of TMessage
And add data with something like:
richedit.Lines.SaveToStream( ARListMessages[i].Text );
How to create the Array, and make manipulations on it (Add, remove
...) with the 'name'?
How can I save it (Array), and load it easily from local storage ? (Ex:
File.dat)
I've found some informations here, without beeing able to make something working.
Thanks for your time.
[EDIT 18/09/2017]
I'm Still looking to find a solution, and try to find a way to save my informations to a local file.
My actual code to test is :
var
MessageArray : array of TMessage;
// // // //
SetLength(MessageArray, 1);
MessageArray[0].Name := 'Hey You';
MessageArray[0].Desc := 'Im here and will stay here, just in case';
MessageArray[0].Text := TMemoryStream.Create;
MessageArray[0].Text.Position := 0;
RichEdit1.plaintext := false;
RichEdit1.Lines.SaveToStream( MessageArray[0].Text );
So, looking to save MessageArray, but haven't find how to do that yet.
I've take a look on SuperObjet, but can't find how to deal with it.
Omxl was looking Great and easy, but free trial ... :(
I've been able to have an answer.
I share it here if someone need the solution.
program Project1;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils, System.Generics.Collections, Classes, System.Zip;
type
TPersonne = class
strict private
FNom : string;
FPrenom: string;
public
property Nom: string read FNom write FNom;
property Prenom: string read FPrenom write FPrenom;
end;
TFamille = class(TDictionary<string, TPersonne>)
private
procedure LoadFromStream(stream: TStream);
procedure SaveToStream(stream: TStream);
public
procedure LoadFromFile(const AFileName: string);
procedure SaveToFile(const AFileName: string);
end;
procedure TFamille.SaveToStream(stream: TStream);
var
i: Integer;
Personne: TPersonne;
Pair: System.Generics.Collections.TPair<string, TPersonne>;
Writer: TWriter;
begin
Writer := TWriter.Create(stream, 4096);
try
Writer.WriteListBegin;
for Pair in Self do
begin
Writer.WriteString(Pair.Key);
Writer.WriteListBegin;
Personne := Pair.Value;
Writer.WriteString(Personne.Nom);
Writer.WriteString(Personne.Prenom);
Writer.WriteListEnd;
end;
Writer.WriteListEnd;
finally
Writer.Free;
end;
end;
procedure TFamille.LoadFromStream(stream: TStream);
var
Personne: TPersonne;
Reader: TReader;
sKey: string;
begin
Clear;
Reader := TReader.Create(stream, 1024);
try
Reader.ReadListBegin;
while not Reader.EndOfList do
begin
sKey := Reader.ReadString;
Personne := TPersonne.Create;
Reader.ReadListBegin;
while not Reader.EndOfList do
begin
Personne.Nom := Reader.ReadString;
Personne.Prenom := Reader.ReadString;
end;
Reader.ReadListEnd;
Add(sKey, Personne);
end;
Reader.ReadListEnd;
finally
Reader.Free;
end;
end;
procedure TFamille.LoadFromFile(const AFileName: string);
var
Stream: TStream;
begin
Stream := TFileStream.Create(AFileName, fmOpenRead);
try
LoadFromStream(Stream);
finally
Stream.Free;
end;
end;
procedure TFamille.SaveToFile(const AFileName: string);
var
stream: TStream;
begin
stream := TFileStream.Create(AFileName, fmCreate);
try
SaveToStream(stream);
finally
stream.Free;
end;
end;
var
Famille: TFamille;
Personne: TPersonne;
begin
try
Famille := TFamille.Create;
try
Personne := TPersonne.Create;
Personne.Nom := 'Julie';
Personne.Prenom := 'Albertine';
Famille.Add('1', Personne);
Famille.SaveToFile('D:\famille.txt');
finally
FreeAndNil(Famille);
end;
Famille := TFamille.Create;
try
Famille.LoadFromFile('D:\famille.txt');
if Famille.Count > 0 then
Writeln(Famille['1'].Nom + ' ' + Famille['1'].Prenom);
finally
FreeAndNil(Famille);
end;
Readln;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.
Thanks all for your Help !
How to create the Array, and make manipulations on it (Add, remove
...) with the 'name'?
From your first code the array is already created. No further work is needed. And even if you use dynamic arrays you still don't have to do any thing just declaring it will suffice.
If you are asking "How to create the array ?" as in "How to create such a list, so I could add, remove with the 'name' field" then I would suggest TDictionary (instead of the city names use your field 'name' as a key) to do the manipulations and then when saving use this
How can I save it (Array), and load it easily from local storage ?
(Ex: File.dat)
You can't directly just like array.savetofile;.You need to use one of file handling methods like TFileStream to store the array.
Note: in your edit the memory stream will cause you only trouble because each time you create it you will need to free it after its use instead use these functions to extract formatted text and change the field Text : TMemoryStream; to Text : string;
RichTextToStr: Convert the rich format text to a string.
function RichTextToStr(RichEdit:TRichEdit):string;
var
SS : TStringStream;
begin
SS := TStringStream.Create('');
try
RichEdit.Lines.SaveToStream(SS);
Result := SS.DataString;
finally
SS.Free;
end;
end;
loadToRichedit: Load the formatted text to the RichEdit again.
procedure loadToRichedit(Const St:string;RichEdit:TRichEdit);
var
SS : TStringStream;
begin
SS := TStringStream.Create(St);
try
RichEdit.Lines.LoadFromStream(SS);
finally
SS.Free;
end;
end;
i have tried this every way that I possible can, but cannot seem to resolve this. I am working with DBExress in Delphi XE3 writing a REST DataSnap Server.
I have data stored in MSQL in a Binary(384) field and Binary is as far as I know that same as a BLOB/Image field as it is all Binary data.
When trying to stream this data to a TStream I receive an exception error and have tried the following
var
STemplate : TStream;
begin
......
Template := TBlobField.Create(cdsBSUserTemplates.FieldByName('bTemplate'));
TBlobField(cdsBSUserTemplates.FieldByName('bTemplate')).SaveToStream(STemplate); //exception
......
end;
and I have tried
var
STemplate : TStream;
begin
......
Template := TBlobField.Create(cdsBSUserTemplates.FieldByName('bTemplate'));
STemplate := cdsBSUserTemplates.CreateBlobStream(Template, bmRead); //exception
......
end;
I can return the value .AsString, but it is Bytes and then I need to try and fix what I have read from that field.
Any idea what else I can try?
You're working much too hard. :-)
You need to properly create the stream, and then just let the field write to it.
var
Output: TMemoryStream;
Fld: TBlobField;
begin
// Use of variable makes it more readable
Fld := cdsBSUserTemplates.FieldByName('bTemplate') as TBlobField;
Output := TMemoryStream.Create;
try
Fld.SaveToStream(Output);
Output.Position := 0;
// Do whatever with the output stream
finally
Output.Free;
end;
end;
After your comment that you might not be using a TBlobField (which would have been nice to know before I posted my answer), you can try this instead (untested, because I clearly don't have your data):
var
Output: TMemoryStream;
Fld: TField;
Bytes: TArray<Byte>;
begin
Fld := ADOQuery1.FieldByName('bTemplate');
Output := TMemoryStream.Create;
try
if Fld.IsBlob then
TBlobField(Fld).SaveToStream(Output)
else
begin
Fld.GetData(Bytes);
Output.WriteData(Bytes, Length(Bytes));
end;
// Do whatever with output
finally
Output.Free;
end;
end;
I need to implement in Delphi 2006 an algoritm that work in .net
Basicaly I need to do the next steps:
Create an XML and validate aganist the XSD
Serialize the XML string into an array of bytes UTF-8 encoded and compress it with zip
The compressed info must be stored again into a array of bytes using base256 format
Create an image using Datamatrix 2D BarCode from this array of bytes and put this image on a report
For step 1, I create the XML using NativeXML library that work ok. In this library exist a metod SaveToBinaryFile but don't work ok. In my tests I used this function to create a binary file.
I was forced to use a binary file becouse my Zip component work only with files not with strings or aray of bytes from memory.
I compressed this binary file with the Zip component and loaded this compresed file into a blob file.
At the moment when I need to create the DataMatrix image I load this blob file into an ansistring and I create the image.
After many tests I found that my fault is when I save my XML into the binary file.
Now I need to found another way to save my xml (utf-8) string to a binarry file.
Please sorry for my english.
Can anyone help me?
procedure CreateXMLBarcodeș
var
BinarySize: Integer;
InputString: utf8string;
StringAsBytes: array of Byte;
F : FIle of Byte;
pTemp : Pointer;
begin
InputString := '';
ADoc := TNativeXml.CreateName(rootName);
try
... //create the XML
InputString := ADoc.WriteToLocalString; //utf8string
if InputString > '' then begin
//serialize the XML string to array of bytes
BinarySize := (Length(InputString) + 1) * SizeOf(Char);
SetLength(StringAsBytes, BinarySize);
Move(InputString[1], StringAsBytes[0], BinarySize);
//save the array of bytes to file
AssignFile( F, xmlFilename );
Rewrite(F);
try
BinarySize := Length( StringAsBytes );
pTemp := #StringAsBytes[0];
BlockWrite(F, pTemp^, BinarySize );
finally
CloseFile( F );
end;
end;
finally
ADoc.Free;
end;
end
...
//in other procedure:
DataSet1XMLBarCode.LoadFromFile(CreateXMLBarcode);
...
//when I want to create the report
//create the DataMatrix image
procedure xyz(Sender: TfrxReportComponent);
var AWidth, AHeight: Integer;
function GetStringFromBlob: AnsiString;
var BlobStream: TStream;
begin
Result := '';
DataSet.Open;
BlobStream := DataSet1.
CreateBlobStream(DataSet1XMLBarCode, bmRead);
try
SetLength(Result, BlobStream.Size);
BlobStream.Position := 0;
BlobStream.Read(Result[1], BlobStream.Size);
finally
BlobStream.Free;
end;
DataSet.Close;
end;
begin
Barcode2D_DataMatrixEcc2001.Locked := True;
Barcode2D_DataMatrixEcc2001.Barcode := GetStringFromBlob;
Barcode2D_DataMatrixEcc2001.Module := 1;
Barcode2D_DataMatrixEcc2001.DrawToSize(AWidth, AHeight);
with TfrxPictureView(frxReport1.FindObject('Picture1')).Picture.Bitmap do
begin
Width := AWidth;
Height := AHeight;
Barcode2D_DataMatrixEcc2001.DrawTo(Canvas, 0, 0);
end;
Barcode2D_DataMatrixEcc2001.Locked := False;
end;
//the code was 'çopied'and adapted from the internet
I need to go through a ton of data that is stored in a paradox table within a Memo field. I need to process this data line by line and process each line.
How can I tell Delphi to fetch each line in the memo field one by one?
Could I use #13#10 as a delimiter?
Assuming that what is in the memo field uses #13#10 as the line separator then I would use a TStringList, and the very useful Text property to split the memo field text into separate lines:
var
StringList: TStringList;
Line: string;
.....
StringList.Text := MemoFieldText;
for Line in StringList do
Process(Line);
Even if your memo field uses Unix linefeeds then this code will interpret the memo field correctly.
It depends on how the field is actually declared in Paradox. If it's a TMemoField, it's pretty easy:
var
SL: TStringList;
Line: string;
begin
SL := TStringList.Create;
try
SL.Text := YourMemoField.GetAsString;
for Line in SL do
// Process each line of text using `Line`
finally
SL.Free;
end;
end;
If it's a TBlobField, it's a little more complicated. You need to read the memo field using a TBlobStream, and load the content of that stream into a TStringList:
// For Delphi versions that support it:
procedure LoadBlobToStringList(const DS: TDataSet; const FieldName: string;
const SL: TStringList);
var
Stream: TStream;
begin
Assert(Assigned(SL), 'Create the stringlist for LoadBlobToStringList!');
SL.Clear;
Stream := DS.CreateBlobStream(DS.FieldByName(FieldName), bmRead);
try
SL.LoadFromStream(Stream);
finally
Stream.Free;
end;
end;
// For older Delphi versions that do not have TDataSet.CreateBlobStream
procedure LoadBlobToStringList(const DS: TDataSet; const TheField: TField;
const SL: TStringList);
var
BlobStr: TBlobStream;
begin
Assert(Assigned(SL), 'Create the stringlist for LoadBlobToStringList!');
SL.Clear;
BlobStr := TBlobStream.Create(DS.FieldByName(TheField), bmRead);
try
SL.LoadFromStream(BlobStr);
finally
BlobStr.Free;
end;
end;
// Use it
var
SL: TStringList;
Line: string;
begin
SL := TStringList.Create;
LoadBlobToStringList(YourTable, YourMemoFieldName, SL);
for Line in SL do
// Process each Line, which will be the individual line in the blob field
// Alternatively, for earlier Delphi versions that don't support for..in
// declare an integer variable `i`
for i := 0 to SL.Count - 1 do
begin
Line := SL[i];
// process line of text using Line
end;
end;