I am trying to post data to bing with this code
function PostExample: string;
var
lHTTP: TIdHTTP;
lParamList: TStringList;
begin
lParamList := TStringList.Create;
lParamList.Add('q=test');
lHTTP := TIdHTTP.Create(nil);
try
Result := lHTTP.Post('http://www.bing.com/', lParamList);
finally
FreeAndNil(lHTTP);
FreeAndNil(lParamList);
end;
end;
And then, how can I get the result to the TWebBrowser and display it?
Try LoadDocFromString:
procedure LoadBlankDoc(ABrowser: TWebBrowser);
begin
ABrowser.Navigate('about:blank');
while ABrowser.ReadyState <> READYSTATE_COMPLETE do
begin
Application.ProcessMessages;
Sleep(0);
end;
end;
procedure CheckDocReady(ABrowser: TWebBrowser);
begin
if not Assigned(ABrowser.Document) then
LoadBlankDoc(ABrowser);
end;
procedure LoadDocFromString(ABrowser: TWebBrowser; const HTMLString: wideString);
var
v: OleVariant;
HTMLDocument: IHTMLDocument2;
begin
CheckDocReady(ABrowser);
HTMLDocument := ABrowser.Document as IHTMLDocument2;
v := VarArrayCreate([0, 0], varVariant);
v[0] := HTMLString;
HTMLDocument.Write(PSafeArray(TVarData(v).VArray));
HTMLDocument.Close;
end;
Or you can use the memory streams for loading
uses
OleCtrls, SHDocVw, IdHTTP, ActiveX;
function PostRequest(const AURL: string; const AParams: TStringList;
const AWebBrowser: TWebBrowser): Boolean;
var
IdHTTP: TIdHTTP;
Response: TMemoryStream;
begin
Result := True;
try
AWebBrowser.Navigate('about:blank');
while AWebBrowser.ReadyState < READYSTATE_COMPLETE do
Application.ProcessMessages;
Response := TMemoryStream.Create;
try
IdHTTP := TIdHTTP.Create(nil);
try
IdHTTP.Post(AURL, AParams, Response);
if Response.Size > 0 then
begin
Response.Position := 0;
(AWebBrowser.Document as IPersistStreamInit).Load(
TStreamAdapter.Create(Response, soReference));
end;
finally
IdHTTP.Free;
end;
finally
Response.Free;
end;
except
Result := False;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
Params: TStringList;
begin
Params := TStringList.Create;
try
Params.Add('q=test');
if not PostRequest('http://www.bing.com/', Params, WebBrowser1) then
ShowMessage('An unexpected error occured!');
finally
Params.Free;
end;
end;
Related
I have this example I would like to get the result of GetRequest and transfer it to LJsonArray. But not adding
function TForm1.GetRequest: TJSONArray;
var
LResponse: IResponse;
LJson : TJSONObject;
begin
LResponse := TRequest
.New.BaseURL('myEndPoint')
.Accept('application/json')
.Get;
Result := LResponse.JSONValue.GetValue<TJSONArray>('structure');
end;
procedure TForm1.Button1Click(Sender: TObject);
var
LJsonArray : TJSONArray;
begin
LJsonArray := TJSONArray.Create;
try
LJsonArray.Add(GetRequest); //<-
Memo1.Lines.Clear;
Memo1.Lines.Add(LJsonArray.ToJSON);
finally
LJsonArray.DisposeOf;
end;
end;
TJSONArray has a Clone method:
function TForm1.GetRequest: TJSONArray;
var
LResponse: IResponse;
begin
LResponse := TRequest
.New.BaseURL('myEndPoint')
.Accept('application/json')
.Get;
Result := TJSONArray(LResponse.JSONValue.GetValue<TJSONArray>('structure').Clone);
end;
procedure TForm1.Button1Click(Sender: TObject);
var
LJsonArray : TJSONArray;
begin
LJsonArray := GetRequest;
try
Memo1.Text := LJsonArray.ToJSON;
finally
LJsonArray.Free;
end;
end;
May I ask for a little help using Indy to login to a website please?
Firstly, just as a 'proof of concept' I used a TWebBrowser to test my credentials in the following manner ...
procedure TfrmMain.cxButton1Click(Sender: TObject);
begin
webBrow.Navigate('http://assurance.redtractor.org.uk/rtassurance/services.eb');
end;
procedure TfrmMain.webBrowDocumentComplete(ASender: TObject;
const pDisp: IDispatch; var URL: OleVariant);
var
CurrentBrowser: IWebBrowser2;
TopBrowser: IWebBrowser2;
Document: OleVariant;
Doc3 : IHTMLDocument3;
Frm : IHtmlFormElement;
begin
CurrentBrowser := pDisp as IWebBrowser2;
TopBrowser := (ASender as TWebbrowser).DefaultInterface;
if Assigned(CurrentBrowser) and Assigned(TopBrowser) then
begin
if CurrentBrowser = TopBrowser then
begin
Doc3 := CurrentBrowser.Document as IHTMLDocument3;
Webbrow.OnDocumentComplete := nil; // remove handler to avoid reentrance
Doc3.getElementById('el9M9AQXIL51JI3_loginPnl_username').setAttribute('value', 'aValidUserName', 0);
Doc3.getElementById('el9M9AQXIL51JI3_loginPnl_password').setAttribute('value', 'aValidPassword', 0);
//Frm := Doc3.getElementById('ct100') as IHtmlFormElement;
Doc3.GetElementByID('el9M9AQXIL51JI3_loginPnl_button').click();
end;
end;
end;
I got the above from the whosrdaddy answer here Automated Log In (webBrowser)
That logs me into the site and takes me to a search page ... exactly what I need.
However, I'd like to avoid using a TWebBrowser as I thought my searches would be slow due to the fact the page would need to be rendered.
With that in mind I tried to use Indy 10 to login to the same address, passing the parameters like so ...
idRedTractor.Post(login_URL, Request, Response);
But all this returns is a 'Server Error, Unauthenticated UserName' response.
My full code for trying to login is ...
procedure TfrmMain.btnLogonClick(Sender: TObject);
var
Response : TMemoryStream;
searchResp : TMemoryStream;
Request : TStringList;
searchReq : TStringList;
resultStr : TStringList;
begin
with IdRedTractor do
begin
allowCookies := true;
cookieManager := cookieRedTractor;
IOhandler := IdSSLRedTractor;
request.Accept := 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8';
request.contentType := 'text/html';
request.userAgent := 'Mozilla/3.0 (compatible; Indy Library)';
end;
with IdSSLRedTractor do
begin
// SSLOptions does not make a difference. Still get a Server Error message
SSLOptions.Mode := sslmUnassigned;
//SSLOptions.Mode := sslmBoth;
//SSLOptions.Mode := sslmClient;
//SSLOptions.Mode := sslmServer;
end;
try
try
response := TMemoryStream.Create;
searchResp := TMemoryStream.Create;
try
request := TStringList.Create;
searchReq := TStringList.Create;
resultStr := TStringList.Create;
// Individual params via FireBug
Request.Add('__EVENTARGUMENT=login');
Request.Add('__EVENTTARGET=el9M9AQXIL51JI3$loginPnl');
Request.Add('__VIEWSTATE=/wEPDwULLTEzMjc3NzQ0ODEPZBYEAgEPZBYCZg9kFgJmDxYCHgRUZXh0BRNDaGVja2VycyAmIFNlcnZpY2VzZAIDD2QWBAICDxYCHgdWaXNpYmxlaGQCCQ9kFgICAg9kFgICBA8WAh8BZxYCAgEPFgIfAWhkZD3T1Ydwd12+6SzZOgVHrnka9LKB');
Request.Add('__VIEWSTATEGENERATOR=9D5BCA8C');
Request.Add('ebAbPwd=' + edtUserPass.text);
Request.Add('ebAbPwd=');
Request.Add('ebAbUser=' + edtUserName.text);
Request.Add('ebAbUser=');
Request.Add('el9M9AQXIL51JI3$loginPnl_...=' + edtUserName.Text);
Request.Add('el9M9AQXIL51JI3$loginPnl_...=' + edtUserPass.text);
Request.Add('el9OK3XX11WQS60_email=');{}
IdRedTractor.Request.Referer := 'http://assurance.redtractor.org.uk/rtassurance/schemes.eb';//initial_URL;
IdRedTractor.Post('http://assurance.redtractor.org.uk/rtassurance/services.eb', Request, Response);
if idRedtractor.ResponseCode = 200 then
begin
resultStr.Clear;
Response.Position := 0;
resultStr.LoadFromStream(Response);
mmoResponse.Lines.AddStrings(resultStr);
end;
finally
request.Free;
searchReq.Free;
resultStr.Free;
end;
finally
response.Free;
searchResp.Free;
end;
except
on e: Exception do
showMessage(e.Message);
end;
end;
Just is case there is some value in the versions of the SSL DLL's, they are 'libeay32.dll' v1.0.1.3 and 'ssleay32.dll', also v1.0.1.3.
May I ask for your help please in understanding what I have missed or done wrong that prevents me from logging into this site with a TidHTTP?
Ok, found your problem.
The site is doing a redirect to the same page after the POST login request.
The key to the solution is setting HandleRedirects to True and change the VMethod variable to GET in the OnHandleRedirect event. I cleaned up the code a bit:
unit SO35263785Test;
interface
uses
IdHttp,
SysUtils,
StrUtils,
StdCtrls,
Classes,
Controls,
Forms;
type
TForm1 = class(TForm)
Memo1: TMemo;
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
Client : TIdHttp;
procedure HandleRedirect(Sender: TObject; var dest: string; var NumRedirect: Integer; var Handled: boolean; var VMethod: TIdHTTPMethod);
procedure LoginToRedTractor(const Username, Password : String);
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.HandleRedirect(Sender: TObject; var dest: string; var NumRedirect: Integer; var Handled: boolean; var VMethod: TIdHTTPMethod);
begin
VMethod := Id_HTTPMethodGet;
Handled := True;
end;
procedure ExtractViewStateAndGenerator(const Html : String; var ViewState : String; var ViewStateGenerator: String);
var
Ps : Integer;
begin
ViewState := '';
ViewStateGenerator := '';
// we assume __VIEWSTATE and __VIEWSTATEGENERATOR inputs are there, NO error checking
Ps := Pos('__VIEWSTATE', Html);
Ps := PosEx('value', Html, Ps);
Ps := PosEx('"', Html, Ps);
ViewState := Copy(Html, Ps+1, PosEx('"', Html, Ps+1)-Ps-1);
Ps := Pos('__VIEWSTATEGENERATOR', Html);
Ps := PosEx('value', Html, Ps);
Ps := PosEx('"', Html, Ps);
ViewStateGenerator := Copy(Html, Ps+1, PosEx('"', Html, Ps+1)-Ps-1);
end;
procedure TForm1.LoginToRedTractor(const Username, Password : String);
var
GETResponse : String;
Request : TStringList;
ViewState : String;
ViewStateGenerator : String;
begin
Client := TIdHttp.Create;
try
Client.ProtocolVersion := pv1_1;
Client.HTTPOptions := [hoForceEncodeParams, hoKeepOrigProtocol];
Client.AllowCookies := True;
Client.HandleRedirects := True;
Client.Request.UserAgent := 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.103 Safari/537.36';
Client.OnRedirect := HandleRedirect;
GETResponse := Client.Get('http://assurance.redtractor.org.uk/rtassurance/schemes.eb');
ExtractViewStateAndGenerator(GETResponse, ViewState, ViewStateGenerator);
Request := TStringList.Create;
try
Request.Add('__VIEWSTATE='+ViewState);
Request.Add('__VIEWSTATEGENERATOR='+ViewStateGenerator);
Request.Add('__EVENTTARGET=el9M9AQXIL51JI3$loginPnl');
Request.Add('el9M9AQXIL51JI3$loginPnl_username='+Username);
Request.Add('el9M9AQXIL51JI3$loginPnl_password='+Password);
Client.Request.Referer := Client.URL.URI;
Memo1.Text := Client.Post('http://assurance.redtractor.org.uk/rtassurance/services.eb', Request);
finally
Request.Free;
end;
finally
Client.Free;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
LoginToRedTractor('MyUsername', 'MyPassword');
end;
end
This code has been verified and works in Delphi XE.
I have a program created in Delphi 7 that uses ftp downloading.
How can i insert into that program to check for a server status?
For example if server is online to produce a green image, if server is offline o produce a red image. Here is the code.
unit Download;
interface
uses
Classes, Wininet, Windows, SysUtils, Dialogs, Forms;
type
GFilesThread = class(TThread)
private
LTemp : Longword;
STemp : string;
FilesToGet : TStringList;
FilesSize : Longword;
CBackup : integer;
CRevision : integer;
CForceCheck : boolean;
CSwitch : integer;
UUrl : string;
USelfParam : string;
Dir: string;
FSource: TStream;
protected
procedure Execute; override;
procedure UpdateFileProgress;
procedure SetFileProgressMax;
procedure UpdateStatusLabel;
procedure UpdateFileDecompStat;
procedure UpdateFilesProgress;
procedure CheckFiles(FList : TStringList);
procedure BZProgress(Sender: TObject);
procedure LockFMain;
procedure UNLockFMain;
procedure GetFiles;
procedure SelfUpdate(SelfVal : string);
procedure UpdateRevision;
procedure ModHosts(Lines : TStringList);
procedure DoUncompressStream(ASource, ADest: TStream);
procedure DoUncompress(const ASource, ADest: TFileName);
function HTTPGetFile(const fileURL, FileName: string; sh_progress: boolean): boolean;
public
property CreateBackup : integer write CBackup;
property UpdatesUrl : string write UUrl;
property LocalRevision : integer write CRevision;
property ForceCheck : boolean write CForceCheck;
end;
implementation
uses Launcher, CheckFiles, BZip2, md5, FileList;
// -------- by 667
procedure GFilesThread.UpdateStatusLabel;
begin
FMain.Label3.Caption:=STemp;
end;
procedure GFilesThread.SetFileProgressMax;
begin
if(CSwitch=0) then
FMain.Gauge1.MaxValue:=LTemp;
if(CSwitch=1) then
FMain.Gauge2.MaxValue:=LTemp;
end;
procedure GFilesThread.UpdateFileProgress;
begin
FMain.Gauge1.Progress:=LTemp;
end;
procedure GFilesThread.UpdateFilesProgress;
begin
FMain.Gauge2.Progress:=LTemp;
end;
procedure GFilesThread.UpdateRevision;
begin
FMain.UpdateRevision(IntToStr(CRevision));
end;
procedure GFilesThread.UpdateFileDecompStat;
begin
FMain.Gauge1.Progress:=LTemp;
end;
procedure GFilesThread.BZProgress(Sender: TObject);
begin
LTemp:=FSource.Position;
Synchronize(UpdateFileDecompStat);
end;
procedure GFilesThread.LockFMain;
begin
Fmain.ImgBtn1.Visible:=False;
Fmain.ImgBtn2.Visible:=False;
Fmain.ImgBtn5.Enabled:=False;
end;
procedure GFilesThread.UNLockFMain;
begin
Fmain.ImgBtn1.Visible:=True;
Fmain.ImgBtn2.Visible:=True;
Fmain.ImgBtn5.Enabled:=True;
end;
// --------- by 667
function GFilesThread.HTTPGetFile(const fileURL, FileName: string; sh_progress: boolean): boolean;
const
BufferSize = 1024;
var
hSession, hURL: HInternet;
Buffer: array[1..BufferSize] of Byte;
BufferLen: Longword;
f: file;
sAppName: string;
begin
Result := False;
sAppName := 'L2ClientUpdater';
LTemp:=0;
hSession := InternetOpen(PChar(sAppName),
INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
try
hURL := InternetOpenURL(hSession, PChar(fileURL), nil, 0, 0, 0);
if (hURL <> nil) then begin
try
DeleteUrlCacheEntry(PChar(fileURL));
AssignFile(f, FileName);
Rewrite(f,1);
repeat
InternetReadFile(hURL, #Buffer, SizeOf(Buffer), BufferLen);
BlockWrite(f, Buffer, BufferLen);
if (sh_progress) then
begin
LTemp:=LTemp+BufferLen;
Synchronize(UpdateFileProgress);
end;
until
BufferLen = 0;
CloseFile(f);
Result := True;
finally
InternetCloseHandle(hURL);
end;
end;
finally
InternetCloseHandle(hSession);
end;
LTemp:=0;
Synchronize(UpdateFileProgress);
end;
procedure GFilesThread.DoUncompress(const ASource, ADest: TFileName);
var
Source, Dest: TStream;
begin
Source := TFileStream.Create(ASource, fmOpenRead + fmShareDenyWrite);
try
Dest := TFileStream.Create(ADest, fmCreate);
try
DoUncompressStream(Source, Dest);
finally
Dest.Free;
end;
finally
Source.Free;
DeleteFile(ASource);
end;
end;
procedure GFilesThread.DoUncompressStream(ASource, ADest: TStream);
const
BufferSize = 65536;
var
Count: Integer;
Decomp: TBZDecompressionStream;
Buffer: array[0..BufferSize - 1] of Byte;
begin
FSource := ASource;
LTemp:=FSource.Size;
CSwitch:=0;
Synchronize(SetFileProgressMax);
Decomp := TBZDecompressionStream.Create(ASource);
try
Decomp.OnProgress := BZProgress;
while True do
begin
Count := Decomp.Read(Buffer, BufferSize);
if Count <> 0 then ADest.WriteBuffer(Buffer, Count) else Break;
end;
finally
Decomp.Free;
FSource := nil;
LTemp:=0;
Synchronize(UpdateFileDecompStat);
end;
end;
procedure GFilesThread.CheckFiles(FList : TStringList);
var
i: integer;
FParam: TStringList;
FNameLocal: string;
begin
if(FList.Count>0) and (FList[0]<>'FAIL') and (not terminated) then
begin
STemp:='Checking files';
Synchronize(UpdateStatusLabel);
CSwitch:=1;
LTemp:=FList.Count-1;
Synchronize(SetFileProgressMax);
FParam:=TStringList.Create;
for i:=0 to FList.Count-1 do
begin
LTemp:=i;
Synchronize(UpdateFilesProgress);
FParam:=Tokenize(FList[i],'|');
FNameLocal:=Dir+FParam[2];
STemp:='Checking '+FParam[2];
Synchronize(UpdateStatusLabel);
if (not FileExists(FNameLocal)) then
begin
FilesToGet.Add(FList[i]);
FilesSize:=FilesSize+StrToInt(FParam[0]);
end
else
begin
if (MD5Print(MD5File(FNameLocal))<>FParam[1]) then
begin
FilesToGet.Add(FList[i]);
FilesSize:=FilesSize+StrToInt(FParam[0]);
end;
end;
end;
FParam.Free;
LTemp:=0;
Synchronize(UpdateFilesProgress);
STemp:='';
Synchronize(UpdateStatusLabel);
end;
end;
procedure GFilesThread.SelfUpdate(SelfVal : string);
var
FParam: TStringList;
FNameLocal: string;
F:boolean;
begin
if(SelfVal<>'') then
begin
FParam:=TStringList.Create;
FParam:=Tokenize(SelfVal,'|');
FNameLocal:=Dir+FParam[2];
if (MD5Print(MD5File(FNameLocal))<>FParam[1]) then
begin
FilesSize:=FilesSize+StrToInt(FParam[0]);
F:=HTTPGetFile(UUrl+FParam[2]+'.bz2',FNameLocal+'.bz2',True);
if(F) then begin
try
DoUncompress(FNameLocal+'.bz2',Dir+FParam[2]+'.New');
GenKillerBat(FParam[2]);
RunApp(Dir+'Update.bat');
except
STemp:='Update Failed';
DeleteFile(FNameLocal);
end;
end;
end;
FParam.Free;
end;
end;
procedure GFilesThread.ModHosts(Lines : TStringList);
var
Hosts : textfile;
H, HostsStrings, HostLineParam : TStringList;
HostsPath, temp : string;
i, z, funnyFlag : integer;
WindirP : PChar;
Res : cardinal;
begin
WinDirP := StrAlloc(MAX_PATH);
Res := GetWindowsDirectory(WinDirP, MAX_PATH);
if Res > 0 then
begin
if(FileExists(StrPas(WinDirP)+'\system32\drivers\etc\hosts.msn')) then
HostsPath := StrPas(WinDirP)+'\system32\drivers\etc\hosts.msn'
else
HostsPath := StrPas(WinDirP)+'\system32\drivers\etc\hosts';
AssignFile(Hosts,HostsPath);
Reset(Hosts);
HostsStrings:= TStringList.Create;
H:= TStringList.Create;
H.Add('#-------- Added by L2Updater --------');
while (not Eof(Hosts)) do
begin
ReadLn(Hosts, temp);
HostsStrings.Add(Trim(temp));
end ;
Reset(Hosts);
for i:=0 to Lines.Count-1 do
begin
funnyFlag:=0;
HostLineParam:=Tokenize(Lines[i],'|');
for z:=0 to HostsStrings.Count-1 do
begin
if (StrSearch(1,HostsStrings[z],HostLineParam[0])>0) and (HostsStrings[z][1]<>'#') then
begin
if (StrSearch(1,HostsStrings[z],HostLineParam[1]+#9)= 0) and (StrSearch(1,HostsStrings[z],HostLineParam[1]+' ')= 0 ) then
begin
HostsStrings[z]:= '#'+HostsStrings[z];
funnyFlag:=1;
end
else funnyFlag:=2;
end;
end;
if (funnyFlag=1) or (funnyFlag=0) then
H.Add(HostLineParam[1]+#9+HostLineParam[0]);
end;
H.Add('#-----------------');
if H.Count>2 then
begin
Rewrite(Hosts);
STemp:='Applying changes to Hosts';
Synchronize(UpdateStatusLabel);
for i:=0 to HostsStrings.Count-1 do
begin
WriteLn(Hosts,HostsStrings[i]);
end;
for i:=0 to H.Count-1 do
begin
WriteLn(Hosts,H[i]);
end;
STemp:='Hosts file chamged';
Synchronize(UpdateStatusLabel);
end;
H.Free; HostsStrings.Free; HostLineParam.Free;
CloseFile(Hosts);
end;
end;
procedure GFilesThread.GetFiles;
var
FParam : TStringList;
i : integer;
F, error : boolean;
LocalFile, BakFile: string;
begin
error := False;
if (FilesToGet.Count>0) then
begin
FParam:=TStringList.Create;
LTemp:=FilesToGet.Count-1;
CSwitch:=1;
Synchronize(SetFileProgressMax);
i:=0;
while (i < FilesToGet.Count) and (not terminated) do
begin
FParam:=Tokenize(FilesToGet[i],'|');
LocalFile:= Dir+FParam[2];
STemp:='Downloading '+ FParam[2];
Synchronize(UpdateStatusLabel);
CSwitch:=0;
LTemp:= StrToInt(FParam[0]);
Synchronize(SetFileProgressMax);
if (not DirectoryExists(ExtractFilePath(LocalFile))) then
ForceDirectories(ExtractFilePath(LocalFile));
F:=HTTPGetFile(UUrl+ReplaceStr(FParam[2],'\','/')+'.bz2',LocalFile+'.bz2',True);
if (F) then
begin
try
if (CBackup=1) then
begin
BakFile:=Dir+'backup\'+FParam[2];
if (not DirectoryExists(ExtractFilePath(BakFile))) then
ForceDirectories(ExtractFilePath(BakFile));
CopyFile(PChar(LocalFile),PChar(BakFile),false);
end;
STemp:='Extracting '+ FParam[2];
Synchronize(UpdateStatusLabel);
DoUncompress(LocalFile+'.bz2',Dir+FParam[2]);
except
STemp:='Update Failed';
error := True;
end;
end
else
begin
STemp:='Update Failed';
error := True;
Break;
end;
inc(i);
LTemp:=i;
CSwitch:=1;
Synchronize(UpdateFilesProgress);
end;
LTemp:=0;
Synchronize(UpdateFilesProgress);
FParam.Free;
if (not error) then
STemp:='All files have been updated.';
end
else STemp:='';
end;
procedure GFilesThread.Execute;
var
List: TListFile;
CFiles, NFiles, HostsLines : TStringList;
TRev, IsModHosts : integer;
F : boolean;
begin
Dir:=GetCurrentDir+'\';
FilesSize:=0;
Synchronize(LockFMain);
STemp:='Downloading updates list';
Synchronize(UpdateStatusLabel);
if(UUrl[length(UUrl)]<>'/') then UUrl:=UUrl+'/';
F:=HTTPGetFile(UUrl+'files.lst.bz2',Dir+'files.lst.bz2', True);
if (F) then
begin
STemp:='';
Synchronize(UpdateStatusLabel);
try
DoUncompress(Dir+'files.lst.bz2',Dir+'files.lst');
except
STemp:='Update Failed';
Synchronize(UpdateStatusLabel);
DeleteFile(Dir+'files.lst');
end;
if(FileExists(Dir+'files.lst')) then
begin
FilesToGet := TStringList.Create;
List := TListFile.Create(Dir+'files.lst');
CFiles:=TStringList.Create;
TRev:=StrToInt(List.GetKeyValue('settings','Rev'));
IsModHosts:=StrToInt(List.GetKeyValue('settings','ModHosts'));
if (IsModHosts = 1) then
begin
HostsLines:= TStringList.Create;
HostsLines:= List.GetFSection('hosts');
try
ModHosts(HostsLines);
finally
HostsLines.Free;
end;
end;
USelfParam:= List.GetFSection('self')[0];
if(USelfParam<>'FAIL') then SelfUpdate(USelfParam);
CFiles:=List.GetFSection('files_critical');
CheckFiles(CFiles);
CFiles.Free;
if (CForceCheck) or (TRev>CRevision) then
begin
if (CBackup=1) then
begin
DelDir(Dir+'backup');
MkDir(Dir+'backup');
end;
NFiles:=TStringList.Create;
NFiles:=List.GetFSection('files_normal');
CheckFiles(NFiles);
NFiles.Free;
end;
GetFiles;
List.Destroy;
FilesToGet.Free;
DeleteFile(Dir+'files.lst');
if TRev>CRevision then
begin
CRevision:=TRev;
Synchronize(UpdateRevision);
end;
end;
end
else
begin
STemp:='Update Failed';
DeleteFile(Dir+'files.lst');
end;
Synchronize(UpdateStatusLabel);
Synchronize(UNLockFMain);
end;
end.
function CanConnect(const aUserName, aPassword, aHost: String; out aErrm: string): boolean;
var
LocalIDFTP: TIdFTP;
begin
aErrm := '';
LocalIDFTP := TIdFTP.Create(nil);
try
LocalIDFTP.UserName := aUserName;
LocalIDFTP.Password := aPassword;
LocalIDFTP.Host := aHost;
LocalIDFTP.Passive := True;
try
LocalIDFTP.Connect;
LocalIDFTP.Quit;
result := true;
except
on E: Exception do
begin
aErrm := 'Unable to connect to FTP site: ' + E.Message;
Result := FALSE;
end;
end;
finally
if Assigned(LocalIDFTP) then
LocalIDFTP.Free
else
Result := FALSE;
end;
end; {CanConnect}
Before I explain my problem, I'm sorry for my bad english.
Okay, here my problem. when my Indy server sends bitmap frame to client, always appeared warning like this :
"EAccessViolation at address 004DD42A..."
And error syntax blue highlighted on this :
Athread.Connection.WriteInteger(MemoryStream.Size);
here my source code :
SERVER
procedure TFormHome.TCPServerConnect(AThread: TIdPeerThread);
var
NewClient: PClient;
begin
GetMem(NewClient, SizeOf(TClient));
NewClient.PeerIP := AThread.Connection.Socket.Binding.PeerIP;
NewClient.HostName := GStack.WSGetHostByAddr(NewClient.PeerIP);
NewClient.Connected := Now;
NewClient.LastAction := NewClient.Connected;
NewClient.Thread := AThread;
AThread.Data := TObject(NewClient);
try
Clients.LockList.Add(NewClient);
finally
Clients.UnlockList;
end;
procedure TFormHome.TCPServerExecute(AThread: TIdPeerThread);
var
pesan:string;
begin
pesan:=Athread.Connection.ReadLn;
if pesan = 'video' then
begin
Athread.Connection.WriteLn('send');
Timer1.Enabled:=true;
FormStream.Show;
Athread.Connection.WriteInteger(MemoryStream.Size);
Athread.Connection.OpenWriteBuffer;
Athread.Connection.WriteStream(MemoryStream);
AThread.Connection.CloseWriteBuffer;
FreeAndNil(MemoryStream);
FormStream.Image1.Picture.Bitmap.Free;
end;
procedure TFormHome.Timer1Timer(Sender: TObject);
begin
pic := TBitmap.Create;
MemoryStream:=TMemoryStream.Create;
VideoGrabber.GetBitmap(FormStream.image1.Picture.Bitmap);
pic := FormStream.Image1.Picture.Bitmap;
pic.SaveToStream(MemoryStream);
//Pic.Free;
//FreeAndNil(Pic);
end;
CLIENT
procedure TFormClient.TCPClientConnected(Sender: TObject);
var
pesan : string;
begin
IncomingMessages.Lines.Insert(0,'Connected to Server');
TCPClient.WriteLn('video');
pesan := TCPClient.ReadLn;
if pesan = 'send' then Timer1.Enabled:=true;
end;
procedure TFormClient.Timer1Timer(Sender: TObject);
var
Size : integer;
ReadStream : TMemoryStream;
begin
ReadStream := TMemoryStream.Create;
Size := TCPClient.ReadInteger;
TCPClient.ReadStream(ReadStream,Size,True);
Image1.Picture.Bitmap.LoadFromStream(ReadStream);
Image1.Picture.Bitmap.Free;
FreeAndNil(ReadStream);
end;
what's wrong witha my code? i need your help.
Thank you before.. ^^
You are trying to send the TMemoryStream before it has even been created. You can't use TTimer or TForm in a worker thread (which OnExecute is called in). Even if you could, when TTimer is enabled, its OnTimer event is not triggered immediately, but your code is expecting it to be.
You need to re-write your code to delegate all UI work to the main thread, where it belongs. Try something more like this:
Server:
Uses
..., IdSync;
type
TVideoStartNotify = class(TIdNotify)
protected
procedure DoNotify; override;
public
Thread: TIdPeerThread;
end;
procedure TFormHome.TCPServerDisconnect(AThread: TIdPeerThread);
begin
TIdNotify.NotifyMethod(VideoStop);
end;
procedure TFormHome.TCPServerExecute(AThread: TIdPeerThread);
var
pesan: string;
begin
pesan := AThread.Connection.ReadLn;
if pesan = 'videostart' then
begin
AThread.Connection.WriteLn('send');
with TVideoStartNotify.Create do
begin
Thread := AThread;
Notify;
end;
end
else if pesan = 'videostop' then
begin
AThread.Connection.WriteLn('stop');
TIdNotify.NotifyMethod(VideoStop);
end;
end;
procedure TVideoStartNotify.DoNotify;
begin
FormHome.VideoStart(Thread);
end;
procedure TFormHome.VideoStart(AThread: TIdPeerThread);
begin
ThreadToSendTo := AThread;
Timer1.Enabled := true;
FormStream.Show;
end;
procedure TFormHome.VideoStop;
begin
ThreadToSendTo := nil;
Timer1.Enabled := false;
FormStream.Hide;
end;
procedure TFormHome.Timer1Timer(Sender: TObject);
var
pic: TBitmap;
MemoryStream: TMemoryStream;
begin
if ThreadToSendTo = nil then
begin
Timer1.Enabled := False;
Exit;
end;
pic := FormStream.Image1.Picture.Bitmap;
try
MemoryStream := TMemoryStream.Create;
try
VideoGrabber.GetBitmap(pic);
pic.SaveToStream(MemoryStream);
try
ThreadToSendTo.Connection.WriteStream(MemoryStream, True, True);
except
ThreadToSendTo := nil;
Timer1.Enabled := False;
end;
finally
MemoryStream.Free;
end;
finally
FormStream.Image1.Picture := nil;
end;
end;
Client:
Uses
..., IdSync;
type
TLogNotify = class(TIdNotify)
protected
procedure DoNotify; override;
public
Msg: String;
end;
procedure TLogNotify.DoNotify;
begin
FormClient.LogMsg(Msg);
end;
procedure TFormClient.Button1Click(Sender: TObject);
begin
TCPClient.Connect;
end;
procedure TFormClient.Button2Click(Sender: TObject);
begin
try
TCPClient.WriteLn('videostop');
finally
TCPClient.Disconnect;
end;
end;
procedure TFormClient.TCPClientConnected(Sender: TObject);
var
pesan : string;
begin
with TLogNotify.Create do
begin
Msg := 'Connected to Server';
Notify;
end;
TCPClient.WriteLn('videostart');
pesan := TCPClient.ReadLn;
if pesan = 'send' then
TIdNotify.NotifyMethod(VideoStart);
end;
procedure TFormClient.TCPClientDisconnected(Sender: TObject);
begin
with TLogNotify.Create do
begin
Msg := 'Disconnected from Server';
Notify;
end;
TIdNotify.NotifyMethod(VideoStop);
end;
procedure TFormClient.LogMsg(const AMsg: string);
begin
IncomingMessages.Lines.Insert(0, AMsg);
end;
procedure TFormClient.VideoStart;
begin
Timer1.Enabled := true;
end;
procedure TFormClient.VideoStop;
begin
Timer1.Enabled := false;
Image1.Picture := nil;
end;
procedure TFormClient.Timer1Timer(Sender: TObject);
var
ReadStream : TMemoryStream;
begin
ReadStream := TMemoryStream.Create;
try
TCPClient.ReadStream(ReadStream, -1, False);
ReadStream.Position := 0;
Image1.Picture.Bitmap.LoadFromStream(ReadStream);
finally
ReadStream.Free;
end;
end;
I try to insert into blob field in SQLite with Delphi XE3.
I've been using TDBXCommand and TSQLConnection like this.
but blob field is not inserted and even i cannnot get any result from query
procedure TDBXCommandHelper.Init(const AQry: String);
begin
Parameters.ClearParameters;
Close;
Prepare;
Text := AQry;
end;
procedure dmDB.InsertPicture;
const
QRY = 'INSERT INTO Memo(Picture) VALUES(?)';
var
LTransaction: TDBXTransaction;
LBlob: TDBXParameter;
LStream: TFileStream;
begin
LTransaction := FDBCon.BeginTransaction;
LStream := TFileStream.Create('d:\sample.bmp', fmOpenRead);
LBlob := TDBXParameter.Create;
try
try
FDBXCmd := FDBCon.DBXConnection.CreateCommand;
FDBXCmd.CommandType := TDBXCommandTypes.DbxSQL;
FDBXCmd.Init(QRY);
LBlob.DataType := TDBXDataTypes.BlobType;
LBlob.SubType := TDBXSubDataTypes.BinarySubType;
LBlob.Value.SetStream(LStream, False);
FDBXCmd.Parameters.AddParameter(LBlob);
FDBXCmd.ExecuteUpdate;
except
on E: Exception do
FDBCon.RollbackFreeAndNil(LTransaction);
end;
FDBCon.CommitFreeAndNil(LTransaction);
finally
FreeAndNil(LStream);
FreeAndNil(LBlob);
end;
end;
using TSQLConnection but i cannot get any result
procedure TInsertThread.NoteInsertExcute;
const
QRY = 'INSERT INTO Memo(Picture) VALUES(:Picture)';
var
LTransaction: TDBXTransaction;
LParams: TParams;
LStream: TMemoryStream;
begin
LTransaction := FDBCon.BeginTransaction;
LParams := TParams.Create(nil);
LStream := TMemoryStream.Create;
LStream.LoadFromFile(FValues.Values[NAME_PICTURE]);
try
LParams.CreateParam(ftBlob, 'Picture', ptInput);
LParams.ParamByName('Picture').LoadFromStream(LStream, ftBlob);
FDBCon.Execute(QRY, LParams);
FDBCon.CommitFreeAndNil(LTransaction);
finally
FreeAndNil(LStream);
FreeAndNil(LParams);
end;
end;
That's easy like:
var
ms: TMemoryStream;
sq: TSQLQuery;
begin
ms := TMemoryStream.Create;
ms.LoadFromFile('C:\Pictures\l.jpg');
if ms <> nil then
begin
sq := TSQLQuery.Create(nil);
sq.SQLConnection := con1;
sq.SQL.Text := 'update db1 set picture= :photo ;';
sq.Params.ParseSQL(sq.SQL.Text, true);
sq.Params.ParamByName('photo').LoadFromStream(ms, ftBlob);
sq.ExecSQL();
end;
.
Where con1 is a TSQLConnection.
You can try the following:
function GetFileAsBytesValue(AFileName: TFileName): TArray<Byte>;
var
Len: Integer;
LStream: TMemoryStream;
begin
LStream := TMemoryStream.Create;
try
LStream.LoadFromFile(AFileName);
Len := LStream.Size;
SetLength(Result, Len);
Move(LStream.Memory^, Result[0], Len);
finally
LStream.Free;
end;
end;
procedure dmDB.InsertPicture;
const
QRY = 'INSERT INTO Memo(Picture) VALUES(?)';
var
LTransaction: TDBXTransaction;
LDBXCmd: TSQLQuery;
LParam: TParam;
begin
LTransaction := FDBCon.BeginTransaction;
LDBXCmd := TSQLQuery.Create(FDBCon);
try
try
LDBXCmd.SQLConnection := FDBCon;
LDBXCmd.SQL.Text := QRY;
LParam := LDBXCmd.Params.CreateParam(ftBlob, 'Picture', ptInput);
LParam.AsBlob := GetFileAsBytesValue('d:\sample.bmp');
LDBXCmd.ExecSQL;
except
on E: Exception do
FDBCon.RollbackFreeAndNil(LTransaction);
end;
FDBCon.CommitFreeAndNil(LTransaction);
finally
LDBXCmd.Free;
end;
end;