Object pascal. Read textfile to variable of WideChar - freepascal

I have my function determines if WideChar var is a letter:
function TWordCounter.IsAlpha(ch: WideChar): boolean;
Begin
ch := upcase(ch);
isalpha := (((ch >='A') and (ch <='Z')) or ((ch >='А') and (ch <='Я')));
end;
Here is code part using IsAlpha function:
Procedure TWordCounter.CountWords(path: string);
var
inputFile: TextFile;
chr: WideChar;
inWord: boolean;
currentWord: string[MAX_WORD_LENGTH];
Begin
SetLength(wordArray, 0);
if (not FileExists(path)) then begin
raise Exception.Create('Указанный путь не ведет к текстовому файлу');
exit;
end;
SetLength(wordArray, BASE_WORD_ARRAY_LENGTH);
currentArrayLimit := BASE_WORD_ARRAY_LENGTH;
currentArrayLength := 0;
AssignFile(inputFile, path);
Reset(inputFile);
inWord := false;
currentWord := '';
while not eof(inputFile) do begin
read(inputFile, chr);
if (isAlpha(chr)) then begin
inWord := true;
currentWord := currentWord + chr;
end
else begin
if (inWord) then begin
AddToDictionary(currentWord);
currentWord := '';
end;
inWord := false;
end;
end;
SetLength(wordArray, currentArrayLength);
CloseFile(inputFile);
end;
I use {$codepage UTF8} compiler directive as well. There are WideChar (2 byte) Russian symbols in the reading file and I can not get them with the way like above (*read(inputFile, chr)*), looks like I read only first byte of symbol with this way. If I directly assign some symbol to my WideChar variable and then call my IsAlpha function it works well, for example:
chr: WideChar;
chr := 'Й';
IsAlpha(chr); // true
I need to extract somehow the symbol from file.

Related

TwinCAT3: Data written into .txt file has gibberish together with actual values. How do I prevent this from happening?

I am currently running a file writer function block to save data being generated from my system. The data is put into an array of strings and then using File_Write is written into a text file. However, the end result shows gibberish together with the data I want.
Image of data captured:
Data in text file(Numbers are the date I want)
Variable declared:
sData : ARRAY [0..4] OF STRING := '123','234','345','456',567';
File writing code I use:
fbRisingEdge(CLK := bExecute);
CASE Step OF
0 :
IF fbRisingEdge.Q THEN
nFileHandle := 0;
bBusy := TRUE;
Step := 1;
END_IF
1 :
fbFileOpen(sPathName := sPathName, bExecute := FALSE);
fbFileOpen(sPathName := sPathName, nMode := nMode, bExecute := TRUE);
Step := 2;
2 :
fbFileOpen(bExecute := FALSE);
IF NOT fbFileOpen.bBusy THEN
IF fbFileOpen.bError THEN
bError := TRUE;
Step := 10;
ELSE
nFileHandle := fbFileOpen.hFile;
Step := 3;
END_IF
END_IF
3 :
fbFileWrite(bExecute := FALSE);
fbFileWrite(hFile := nFileHandle, pWriteBuff := ADR(GVL.sData), cbWriteLen := SIZEOF(GVL.sData), bExecute := TRUE);
Step := 4;
4 :
fbFileWrite(bExecute := FALSE);
IF NOT fbFileWrite.bBusy THEN
IF fbFileWrite.bError THEN
bError := TRUE;
Step := 10;
ELSE
Step := 5;
nBytesWritten := fbFileWrite.cbWrite;
END_IF
END_IF
5 :
fbFileClose(bExecute := FALSE);
fbFileClose(hFile := nFileHandle, bExecute := TRUE);
Step := 6;
6 :
fbFileClose(bExecute := FALSE);
IF NOT fbFileClose.bBusy THEN
IF fbFileClose.bError THEN
bError := TRUE;
END_IF
Step := 10;
nFileHandle := 0;
END_IF
10 :
IF nFileHandle <> 0 THEN
Step := 6;
ELSE
Step := 0;
bBusy := FALSE;
END_IF
END_CASE
I don't see where you are defining nMode in fbFileOpen. You would need to have something like nMode := FOPEN_MODEWRITE OR FOPEN_MODETEXT.
I think that writing an array of strings in a single action could be causing your problem. You didn't specify the string length in your declaration, and the string datatype includes an extra byte at the end. You may want to try concatenating all of the array elements into a single string before writing.

How to clear child nodes in XML Document after loading in from file (Delphi)? (avoiding "attempt to modify a read-only node" error)

I have the following problem. I'm creating a XML Document in several steps and saving it after it to *.html file (after form execution):
procedure TOutputDlg.Execute;
var
Sl : TStringList;
I : Integer;
begin
OKClick := False;
if ShowModal = mrOK then begin
if not AddAnother then begin
SaveDialog1.InitialDir := PrjPath;
if SaveDialog1.Execute then begin
InitFile(ExtractFileName(SaveDialog1.FileName));
if not AddAnotherCheckBox.Checked then
with XMLDoc.DocumentElement.ChildNodes['head'].ChildNodes['style'] do begin
Text := StringReplace(Text, 'counter(h1counter) "." ', '', []);
Text := StringReplace(Text, 'counter-reset: h1counter', 'counter-reset: h2counter', []);
end
else //16.09-wip JDC 26/10/2016 Added input box for first number (not included localization of input box label)
with XMLDoc.DocumentElement.ChildNodes['head'].ChildNodes['style'] do begin
Text := StringReplace(Text, 'counter-reset: h1counter', 'counter-reset: h1counter '
+ IntToStr(Round(GetRealDlg.Execute('Start numbering at:', 1)) - 1), []);
if GetRealDlg.CancelClick then
Exit;
end;
for I := 0 to Config.Count - 1 do
if ModuleCheckListBox.Checked[I] then
AddModule(Config.Names[I], Config.ValueFromIndex[I]);
Sl := TStringList.Create;
try
Sl.Assign(XMLDoc.XML) ;
// Sl.Insert(0, '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">');
Sl.Insert(0, '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">');
Sl.Insert(0, '<?xml version="1.0"?>');
Sl.Text := StringReplace(Sl.Text, ' xmlns=""', '', [rfReplaceAll]);
Sl.Text := StringReplace(Sl.Text, '&', '&', [rfReplaceAll]);
Sl.WriteBOM := False;
Sl.SaveToFile(SaveDialog1.FileName, TEncoding.UTF8);
finally
Sl.Free;
end;
OKClick := True;
end;
end else begin
Form1.OpenExecute(nil);
XMLDoc.LoadFromFile(SaveDialog1.FileName);
Body := XMLDoc.DocumentElement.ChildNodes['body'];
for I := 0 to Config.Count - 1 do
if ModuleCheckListBox.Checked[I] then
AddModule(Config.Names[I], Config.ValueFromIndex[I]);
XMLDoc.SaveToFile(SaveDialog1.FileName);
OKClick := True;
end;
if AddAnotherCheckBox.Checked then begin
AddAnother := True;
Execute;
end;
end;
if (not AddAnotherCheckBox.Checked) and OKClick then begin
ShellExecute(0, 'OPEN', PChar(SaveDialog1.FileName), '', '', SW_SHOWNORMAL);
OKClick := False;
end;
AddAnother := False;
end;
This block of the code above creates the html from several locations (multiple times):
end else begin
Form1.OpenExecute(nil);
XMLDoc.LoadFromFile(SaveDialog1.FileName);
Body := XMLDoc.DocumentElement.ChildNodes['body'];
for I := 0 to Config.Count - 1 do
if ModuleCheckListBox.Checked[I] then
AddModule(Config.Names[I], Config.ValueFromIndex[I]);
XMLDoc.SaveToFile(SaveDialog1.FileName);
OKClick := True;
end;
So far this works fine. The problem comes when I try to make new html output for completely new file.
There I initialize the XMLDoc with: InitFile(ExtractFileName(SaveDialog1.FileName));
I get then the following error "attempt to modify a read-only node" on the ChildNodes.Clear; line.
It looks like the XMLDoc is loaded already and cannot be modified anymore. Is there any way to unload it or something similar, so I can perform my InitFile procedure over it?
Thank you for the support!
procedure TOutputDlg.InitFile(FName : WideString);
procedure locAddStyle(Head: IXMLNode; FileName, Media: WideString);
var
Style : IXMLNode;
begin
Style :=Head.AddChild('style');
Style.SetAttribute('type', 'text/css');
if Media <> '' then
Style.SetAttribute('media', Media);
Style.Text := FileToStr(ResPath + FileName);
end;
var
Head, N : IXMLNode;
begin
with XMLDoc do begin
Active := False;
Active := True;
ChildNodes.Clear;
DocumentElement := AddChild('html');
DocumentElement.SetAttribute('xmlns', 'http://www.w3.org/1999/xhtml');
DocumentElement.SetAttribute('xml:lang', Model.OutputLanguage);
DocumentElement.SetAttribute('lang', Model.OutputLanguage);
Head := DocumentElement.AddChild('head');
N := Head.AddChild('title');
N.Text := 'StrEngS results';
N := Head.AddChild('meta');
N.SetAttribute('http-equiv', 'Content-Type');
N.SetAttribute('content', 'text/html; charset=utf-8');
locAddStyle(Head, 'strengs.css', '');
locAddStyle(Head, 'strengs-screen.css', 'screen');
if UseMathJax then begin
N := Head.AddChild('script');
N.SetAttribute('type', 'text/javascript');
N.SetAttribute('src', 'http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML');
end;
{ locAddStyle(Head, 'strengs-print.css', 'print');} // Waitng for browser implementation of #page CSS element
Body := DocumentElement.AddChild('body');
// Header
{ N := Body.AddChild('div');
N.SetAttribute('id', 'print-header');
M := N.AddChild('img');
M.SetAttribute('class', 'alignright logo');
M.SetAttribute('src',
ExtractRelativePath(ExtractFileDir(SaveDialog1.FileName) +
'\', ExePath + 'res\Znak.gif'));
M := N.AddChild('p');
M.SetAttribute('class', 'alignleft');
M.Text := LocList['OUTPUT_PROJECT_ID'] + Model.Metadata.ProjectID;
// Footer
N := Body.AddChild('div');
N.SetAttribute('id', 'print-footer');
M := N.AddChild('p');
M.SetAttribute('class', 'alignleft');
M.Text := DateToStr(Date);
M := N.AddChild('p');
M.SetAttribute('class', 'alignright');
M.Text := AU_VERSION_STRING; } // Waitng for browser implementation of #page CSS element
end;
end;

Get correspondence of screen line to TStrings line in TMemo descendant

TRichEdit is causing too much access violations and issues in popup menu when styles are set, therefore I am trying to make a simple colorful TMemo descendant where each line from Lines could be painted with its own color as a whole.
I cannot influence the edit control from Windows, but can paint strings over it.
At first I tried to iterate through Lines property, but it caused problems with scrolling. So I decided to query strings from edit control directly using Win API.
For now everything is painted fine except colors: The lines requested from Windows edit control are the screen lines, not the lines from Lines property when WordWrap := True; and ScrollBars := ssVertical;.
How to find out the screen -> Lines line number correspondence?
unit ColoredEditMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TMyMemo = class(TMemo)
private
procedure WMPaint(var msg: TWMPaint); message WM_PAINT;
end;
TForm1 = class(TForm)
private
_memo: TMyMemo;
public
constructor Create(AOwner: TComponent); override;
end;
var
Form1: TForm1;
implementation
uses
Vcl.Themes;
{$R *.dfm}
{ TMyMemo }
procedure TMyMemo.WMPaint(var msg: TWMPaint);
var
Buffer: Pointer;
PS: TPaintStruct;
DC: HDC;
i: Integer;
X, Y: Integer;
OldColor: LongInt;
firstLineIdx: Integer;
charsCopied, lineCount: Integer;
lineLength: Word;
bufLength: Integer;
begin
try
DC := msg.DC;
if DC = 0 then
DC := BeginPaint(Handle, PS);
try
X := 5;
Y := 1;
SetBkColor(DC, Color);
SetBkMode(DC, Transparent);
OldColor := Font.Color;
firstLineIdx := SendMessage(Handle, EM_GETFIRSTVISIBLELINE, 0, 0);
lineCount := SendMessage(Handle, EM_GETLINECOUNT, 0, 0);
for i:=firstLineIdx to lineCount-1 do begin
SelectObject(DC, Font.Handle);
if odd(i) then
SetTextColor(DC, clRed)
else
SetTextColor(DC, OldColor);
lineLength := SendMessage(Handle, EM_LINELENGTH, WPARAM(i), 0);
bufLength := lineLength*2 + 2;
GetMem(Buffer, bufLength);
try
ZeroMemory(Buffer, bufLength);
PWord(Buffer)^ := lineLength;
charsCopied := SendMessage(Handle, EM_GETLINE, WPARAM(i), LPARAM(Buffer));
//ShowMessage(IntToStr(lineLength) + ' ' + IntToStr(charsCopied) + '=' + Strpas(PWideChar(Buffer)));
if Y > ClientHeight then Exit();
TextOut(DC, X, Y, PWideChar(Buffer), lineLength);
finally
FreeMem(Buffer, bufLength);
end;
Inc(Y, Abs(Font.Height) + 2);
end;
finally
if msg.DC = 0 then
EndPaint(Handle, PS);
end;
except
on ex: Exception do MessageBox(Handle, PWideChar('WMPaint: ' + ex.Message), nil, MB_ICONERROR);
end;
end;
{ TForm1 }
constructor TForm1.Create(AOwner: TComponent);
var
i, j: Integer;
txt: string;
begin
inherited;
Left := 5;
Top := 5;
_memo := TMyMemo.Create(Self);
_memo.Parent := Self;
_memo.Align := alClient;
_memo.WordWrap := True;
_memo.ReadOnly := True;
_memo.ScrollBars := ssVertical;
for i := 0 to 10 do begin
txt := '';
for j := 0 to 100 do
txt := txt + 'Line ' + IntToStr(i) + '.' + IntToStr(j) + ' ';
_memo.Lines.Add(txt);
end;
end;
end.
Update
I always thought that TMemo keeps original lines in its Lines collection, but in fact it spoils its Lines just after adding an item. When Word wrapping is on, adding a really long line converts it to several screen lines.
BUT! Surprisingly Windows edit control internally keeps the original lines as a whole on control resize.

Free Pascal Strip Only Some HTML Tags from a string

I would like to know if it's possible to strip an especific html tag from a string.
I would like to strip tags starting with <img> only. But all the <img ...> content must be removed. It's because I need to remove the images from the string.
I have tryed to adapt this routine:
function StripHTML(S: string): string;
var
TagBegin, TagEnd, TagLength: integer;
begin
TagBegin := Pos( '<', S); // search position of first <
while (TagBegin > 0) do begin // while there is a < in S
TagEnd := Pos('>', S); // find the matching >
TagLength := TagEnd - TagBegin + 1;
Delete(S, TagBegin, TagLength); // delete the tag
TagBegin:= Pos( '<', S); // search for next <
end;
Result := S; // give the result
end;
This way (changing two lines):
TagBegin := Pos( '<img', S); // search position of first <
...
TagBegin:= Pos( '<img', S); // search for next <
But the code falls in an unbreakable loop. :(
I applied the tips from #Abelisto and it's working now.
Here's the code (I must quote that the original code was found here:
http://www.festra.com/eng/snip12.htm)
function StripHTML(S: string): string;
var
TagBegin, TagEnd : integer;
begin
TagBegin := Pos( '<img', S); // search position of first <
while (TagBegin > 0) do begin // while there is a < in S
TagEnd := PosEx('>', S, TagBegin); // find the matching >
Delete(S, TagBegin, (TagEnd - TagBegin) + 1); // delete the tag
TagBegin:= Pos( '<img', S); // search for next <
end;
Result := S; // give the result
end;

twitter api 1.1 , and oauth delphi implementation

Is there an implementation for Delphi, which connects to twitter new API, 1.1, and do operations on twitter?
they also removed all xml support, so there needs to be json operations.
the explanation from twitter site:
first we need to set an indy connection like so:
POST /oauth2/token HTTP/1.1
Host: api.twitter.com
User-Agent: My Twitter App v1.0.23
Authorization: Basic eHZ6MWV2RlM0d0VFUFRHRUZQSEJvZzpMOHFxOVBaeVJn
NmllS0dFS2hab2xHQzB2SldMdzhpRUo4OERSZHlPZw==
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Content-Length: 29
Accept-Encoding: gzip
grant_type=client_credentials
Then we could use the indy to get the twitter response :
HTTP/1.1 200 OK
Status: 200 OK
Content-Type: application/json; charset=utf-8
...
Content-Encoding: gzip
Content-Length: 140
{"token_type":"bearer","access_token":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA%2FAAAAAAAAAAAAAAAAAAAA%3DAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}
this looks simple enough, however we need to use ssl, which force no debug with wireshark.
the code i used:
Uses EncdDecd;
Const
Consumer_Key = 'xvz1evFS4wEEPTGEFPHBog';
Consumer_Secret = 'L8qq9PZyRg6ieKGEKhZolGC0vJWLw8iEJ88DRdyOg';
Host = 'api.twitter.com/';
Request_token_URL = 'https://api.twitter.com/oauth/request_token';
Twitter_Content_Type = 'application/x-www-form-urlencoded;charset=UTF-8';
var
Response:TStream;
twittersite:TIdHttp;// assume on Form
Trace:TMemo; //assume on Form
IdSSLIOHandlerSocketOpenSSL1:TIdSSLIOHandlerSocketOpenSSL;//assume on Form
function EncodeBase64String(s: string): string;
var
sIn:TSTringSTream;
begin
sIn := TStringStream.create(s);
result := String (EncodeBase64(Sin.Memory, sIn.Size));
sin.Free;
end;
begin
Response:= TMemoryStream.Create;
try
//Headers
twittersite.Request.Host := Host;
twitterSite.Request.UserAgent := 'Fucy Town 1.0';
twitterSite.Request.CustomHeaders.Add('Authorization=Basic '+EncodeBase64String(Consumer_Key+':'+Consumer_Secret));
twitterSite.Request.ContentType := Twitter_Content_Type;
twitterSite.Request.CustomHeaders.Add('grant_type=client_credentials');
//SSL
twitterSite.IOHandler := IdSSLIOHandlerSocketOpenSSL1;
TwitterSite.Post(Request_token_URL,response);
Trace.Lines.LoadFromStream(Response);
finally
FreeAndNil(Response);
end;
end;
this result in 401 unauthorized.
what can be done to fix this code and get 200 ok?
DUMP
unit twitter;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, IdIntercept, IdLogBase, IdLogDebug, IdIOHandler, IdIOHandlerSocket,
IdIOHandlerStack, IdSSL, IdSSLOpenSSL, IdBaseComponent, IdComponent,
IdTCPConnection, IdTCPClient, IdHTTP, StdCtrls, IdCoder, IdCoder3to4,
IdCoderMIME;
const
//https://dev.twitter.com/docs/auth/application-only-auth
URL = 'https://api.twitter.com/oauth2/token';
key = 'xvz1evFS4wEEPTGEFPHBog'; //this is example, replace with yours.
secret = 'L8qq9PZyRg6ieKGEKhZolGC0vJWLw8iEJ88DRdyOg';//this is example, replace with yours.
type
TForm5 = class(TForm)
Button1: TButton;
Memo1: TMemo;
IdHTTP1: TIdHTTP;
IdSSLIOHandlerSocketOpenSSL1: TIdSSLIOHandlerSocketOpenSSL;
IdLogDebug1: TIdLogDebug;
IdEncoderMIME1: TIdEncoderMIME;
procedure IdLogDebug1Receive(ASender: TIdConnectionIntercept;
var ABuffer: TBytes);
procedure IdLogDebug1Send(ASender: TIdConnectionIntercept;
var ABuffer: TBytes);
procedure Button1Click(Sender: TObject);
private
parameters:TStringList;
ringBear:string;
keySecretBase64:string;
procedure initConnection;
function getRingBear(input:TStringstream):string;
function requestRingBear:TStringStream; //bearer token
procedure requestTwits;
function logoff:TStringStream;
public
{ Public declarations }
end;
var
Form5: TForm5;
implementation
{$R *.dfm}
uses IdGlobal, superobject;
procedure TForm5.initConnection;
begin
with IdSSLIOHandlerSocketOpenSSL1 do begin
SSLOptions.Method := sslvSSLv3;
SSLOptions.Mode := sslmUnassigned;
SSLOptions.VerifyMode := [];
SSLOptions.VerifyDepth := 2;
end;
with IdHTTP1 do begin
IOHandler := IdSSLIOHandlerSocketOpenSSL1;
ReadTimeout := 0;
AllowCookies := True;
ProxyParams.BasicAuthentication := False;
ProxyParams.ProxyPort := 0;
Request.ContentLength := -1;
Request.ContentRangeEnd := 0;
Request.ContentRangeStart := 0;
Request.ContentType := 'application/x-www-form-urlencoded';
Request.Accept := 'text/html, */*';
Request.BasicAuthentication := False;
Request.UserAgent := 'Mozilla/3.0 (compatible; Indy Library)';
HTTPOptions := [hoForceEncodeParams];
end;
IdHTTP1.Intercept := IdLogDebug1;
parameters.Clear;
IdHTTP1.Request.CustomHeaders.Clear;
end;
function TForm5.logoff:TStringStream;
begin
result := TStringStream.Create;
idhttp1.Request.CustomHeaders.AddValue('Authorization','Basic '+keySecretBase64);
parameters.Add('access_token='+ringBear);
IdHTTP1.Post('https://api.twitter.com/oauth2/invalidate_token',parameters,result);
keySecretBase64:='';
ringBear := '';
end; //the caller needs to free the stream
function TForm5.requestRingBear:TStringStream;
begin
result := TStringStream.create;
keySecretBase64 := TIdEncoderMIME.EncodeString(key+ ':' + secret, IndyTextEncoding_UTF8);
parameters.Add('grant_type=client_credentials');
Memo1.Lines.Add('secret and key ' + keySecretBase64);
IdHTTP1.Request.CustomHeaders.AddValue('Authorization','Basic '+keySecretBase64);
IdHTTP1.post(URL,parameters,result);
end;//the caller needs to free the stream
procedure TForm5.requestTwits;
begin
IdHTTP1.Request.CustomHeaders.AddValue('Authorization','Bearer ' + ringBear);
memo1.lines.add('twits response : ' +
IdHTTP1.Get('https://api.twitter.com/1.1/statuses/user_timeline.json?count=100&screen_name=twitterapi'));
end;
procedure TForm5.Button1Click(Sender: TObject);
var
json:ISuperObject;
stream:TStringStream;
begin
stream:=TStringStream.Create;
parameters:=TStringList.Create;
try
cursor := crHourGlass;
initConnection;
// return this: {"access_token":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA%2FAAAAAAAAAAAAAAAAAAAA%3DAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","token_type":"bearer"}
ringBear := getRingBear(requestRingBear);//the caller needs to free the stream
initConnection;
requestTwits;
initConnection;
logoff;//the caller needs to free the stream
finally
cursor := crDefault;
memo1.Lines.Add('stream reposne' +stream.DataString);
stream.Free;
parameters.Free;
end;
end;
function TForm5.getRingBear(input: TStringstream): string;
var
json : ISuperObject;
begin
json := TSuperObject.ParseStream(input,true);
result := json.S['access_token'];
input.Free;
end;
procedure TForm5.IdLogDebug1Receive(ASender: TIdConnectionIntercept;
var ABuffer: TBytes);
var
i: Integer;
s: String;
begin
s := '';
for i := Low(ABuffer) to High(ABuffer) do
s := s + chr(ABuffer[i]);
Memo1.Lines.Add('Recived: '+s);
end;
procedure TForm5.IdLogDebug1Send(ASender: TIdConnectionIntercept;
var ABuffer: TBytes);
var
i: Integer;
s: String;
begin
s := '';
for i := Low(ABuffer) to High(ABuffer) do
s := s + chr(ABuffer[i]);
Memo1.Lines.Add('SEND: '+s);
end;
end.
dfm needs to contain :
object Form5: TForm5
Left = 0
Top = 0
Caption = 'Form5'
ClientHeight = 546
ClientWidth = 605
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = []
OldCreateOrder = False
DesignSize = (
605
546)
PixelsPerInch = 96
TextHeight = 13
object Button1: TButton
Left = 288
Top = 513
Width = 75
Height = 25
Caption = 'Button1'
TabOrder = 0
OnClick = Button1Click
end
object Memo1: TMemo
Left = 8
Top = 8
Width = 589
Height = 499
Anchors = [akLeft, akTop, akRight, akBottom]
Lines.Strings = (
'Memo1')
ScrollBars = ssVertical
TabOrder = 1
end
object IdHTTP1: TIdHTTP
Intercept = IdLogDebug1
IOHandler = IdSSLIOHandlerSocketOpenSSL1
AllowCookies = True
ProxyParams.BasicAuthentication = False
ProxyParams.ProxyPort = 0
Request.ContentLength = -1
Request.Accept = 'text/html, */*'
Request.BasicAuthentication = False
Request.UserAgent = 'Mozilla/3.0 (compatible; Indy Library)'
HTTPOptions = [hoForceEncodeParams]
Left = 280
Top = 136
end
object IdSSLIOHandlerSocketOpenSSL1: TIdSSLIOHandlerSocketOpenSSL
Intercept = IdLogDebug1
MaxLineAction = maException
Port = 0
DefaultPort = 0
SSLOptions.Mode = sslmUnassigned
SSLOptions.VerifyMode = []
SSLOptions.VerifyDepth = 0
Left = 296
Top = 48
end
object IdLogDebug1: TIdLogDebug
OnReceive = IdLogDebug1Receive
OnSend = IdLogDebug1Send
Left = 136
Top = 192
end
object IdEncoderMIME1: TIdEncoderMIME
FillChar = '='
Left = 424
Top = 256
end
end
remarks:
you must have application registered in twitter.
you need the key and secret from the twitter.
this is application to application api mentioned here
implementing the user oauth with pin code is another order of magnitude in complex, and need user activity to input the pin code. if you need more info on that look here which contains the detail explanation here with a very good diagram. the code there is not complete, and the dfm is missing. there is a full example somewhere on dropbox oauth, but i cant find it at the moment.
in delphi xe5 there is oauth client that comes with delphi, that should make your life easier.
the log out does not work.
and ringBear is reference to barney stinson ring bear in his wedding and not ring bearer, since twitter called it Bear(i think from beacon consents, not weddings)
The idea is simple. request a ringBear, then request the twits then logoff.