DWScript Write/Read a simple text file - dwscript

I would like to write/read a simple text file using dwscript.
My code is here below... but I am non able to get it run, please someone might help...:
(I am using the Simple.exe in the Demos folder of DWS installation)
// uses Classes;
{$INCLUDE_ONCE 'c:/.../System.Classes.pas'}
var
s: TFileStream;
o: string; // out
i: integer;
f: word; // flag
f := fmOpenReadWrite;
if not FileExists('C:\Temp\Junkfile.txt') then
f := f or fmCreate;
s := TFileStream.Create('C:\Temp\Junkfile.txt', f);
try
s.Position := s.Size; // will be 0 if file created, end of text if not
for i := 1 to 10 do begin
o := Format('This is test line %d'#13#10, [i]);
s.Write(o[1], Length(o) * SizeOf(Char));
end;
finally
s.Free;
end;

By default the script engine keeps everything sand-boxed and nothing that gives access outside the sandbox is exposed. So if you want to give access to arbitrary files to script you need to expose functions & classes to achieve it (through TdwsUnit f.i.).
Also it won't compile the Delphi classes unit, DWScript is not meant to be an alternative to the Delphi compiler, but to offer scripting support, ie. allow end users to run code in a way over which you have full control over what they can do, and that can't crash or corrupt the host application (that last point being the key differentiation with the other notable Pascal scripting engines).
You can use dwsFileFunctions to get basic file I/O support, in which case an equivalent to the file creation portion of your code would be something like
var f := FileCreate('C:\Temp\Junkfile.txt');
for var i := 1 to 10 do
FileWrite(f, Format('This is test line %d'#13#10, [i]));
FileClose(f);

Related

Using encoding.com golang wrapper

I'm rather new to both golang and encoding.com and I'm trying to use the encoding.com API wrapper to transcode a simple video file, but I'm rather confused by the format to use.
When looking at the tests I can see how to call the AddMedia function (https://github.com/nytimes/encoding-wrapper/blob/master/encodingcom/media_test.go#L9-L39) but unfortunately it doesn't work for me.
package main
import ("github.com/NYTimes/encoding-wrapper/encodingcom")
func main() {
client, err := encodingcom.NewClient("https://manage.encoding.com", "123", "key")
format := encodingcom.Format{
Output: []string{"https://key:secret#bucket.s3.amazonaws.com/aladin.ogg"},
VideoCodec: "libtheora",
AudioCodec: "libvorbis",
Bitrate: "400k",
AudioBitrate: "64k",
}
addMediaResponse, err := client.AddMedia([]string{"https://samples.mplayerhq.hu/h264/Aladin.mpg"},
[]encodingcom.Format{format}, "us-east-1")
}
}
The error "raised" is
APIError.Errors.Errors0: Output format 'https://key:secret#bucket.s3.amazonaws.com/aladin.aac' is not allowed! (format #0)
APIError.Message:
and I really don't get it, the Output element in the Format looks missplaced, am I reading the test wrong? Using the API builder the format parameter should receive only the format, for example "ogg", and there's a "destination" parameter for S3. It also doesn't specify if the url must be urlencoded, but honestly I don't think so. Still keys and secrets can contain for example the char '/'
Any more experienced gopher?

Is there a FILE_READ equivalent in oracle?

I was trying to load data in to db on application startup.
With H2 I was using the below query and it worked perfectly. With Oracle it doesn't work. Can someone point me the right direction? I went through oracle documentation but didn't manage to find an equivalent.
INSERT INTO TEMPLATES(ID,NAME,BODY) VALUES('2b04469f31c445ca82c354322845b52b', 'Records', FILE_READ('/opt/bin/Records.txt'));
Oracle SQL has no equivalent of a file_read() function. However, it is possible to write your own.
However, before we start you need to known that Oracle is much more locked down when it comes to database interoperability with the OS. Many things are not enabled by default, and consequently you may require assistance from a friendly DBA to get this working.
For instance, we cannot use OS filepaths directly (at least in more recent versions) so we need to create a DIRECTORY object. Normally the privilege to do this is restricted to DBAs.
create directory opt_bin as '/opt/bin';
grant read on directory opt_bin to <<your_user>>;
Note that /opt/bin must be a directory to which the database has access. On a *nix environment that means the oracle OS user has at least read on the directory.
With that infrastructure in place we can create a function which loads an OS file into a blob. It uses the directory and file name to instantiate a BFILE then applies DBMS_LOB capability to load that BFILE into a BLOB.
create or replace file_to_blob
(p_dir in varchar2, p_file in varchar2)
return blob
is
bf bfile;
tmp_blob blob := empty_blob();
l_dest_offset pls_integer := 1;
l_src_offset pls_integer := 1;
begin
bf := bfilename(p_dir, b_file);
dbms_lob.createtemporary(tmp_blob, true);
dbms_open(bf, dbms_lob.file_readonly);
dbms_lob.loadblobfromfile(tmp_blob, bf, dbms_lob.lobmaxsize, l_dest_offset, l_src_offset);
dbms_lob.close(bf);
return tmp_blob;
end;
/
You can use this function in your insert statement like this:
INSERT INTO TEMPLATES(ID,NAME,BODY)
VALUES
('2b04469f31c445ca82c354322845b52b', 'Records', file_to_blob('opt_bin', 'Records.txt'));

Testing Go Web Scraper with Go-VCR

I'm newer to the Go language and it's resources, but have been looking around for quite some time without any luck of finding what I'm looking for. So if there is a resource out there for it, I apologize for the duplicate question and would appreciate being directed that way.
My goal is simply to build a web scraper. I'm using chromedp, which has features to focus on elements, fill in text, etc. I want to create a test environment/server to test it with during development. The main reason being that I do not want to constantly create GET requests from a website (out of common courtesy), but also be able to work offline and in addition it should also make testing a little faster. I stumbled across the go-vcr library and have been trying to get that to work, but to no avail. I can get it to record and create a .yaml, but I can't figure out how to test beyond the raw html that bounces back and gets stored in the .yaml file. My understanding is that it's possible to replicate the website and functionality of it using the library, but I'm unable to piece together how to do that.
Is what I'm trying to do possible, or is the go-vcr library (or any test/fake server for that matter) only capable of returning static data, therefore rendering anything I want to test with the web scraper not possible?
I haven't posted any code simply because I haven't pieced together much more than the examples given from the repository for the go-vcr.
I hope I was able to explain that in a way that made sense. If not I'd be happy to answer questions to clarify.
Update: Adding the example code for sake of ease. I understand how this part of it works (I think) and I can use it for testing whether or not I grabbed the proper elements of a static page, but ideally (as an example) I want to be able to fill in a text box with my program and test whether or not I successfully found the text box and filled it in without hitting the live webpage.
package vcr_test
import (
"io/ioutil"
"net/http"
"strings"
"testing"
"github.com/dnaeon/go-vcr/recorder"
)
func TestSimple(t *testing.T) {
// Start our recorder
r, err := recorder.New("fixtures/golang-org")
if err != nil {
t.Fatal(err)
}
defer r.Stop() // Make sure recorder is stopped once done with it
// Create an HTTP client and inject our transport
client := &http.Client{
Transport: r, // Inject as transport!
}
url := "http://golang.org/"
resp, err := client.Get(url)
if err != nil {
t.Fatalf("Failed to get url %s: %s", url, err)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Fatalf("Failed to read response body: %s", err)
}
wantTitle := "<title>The Go Programming Language</title>"
bodyContent := string(body)
if !strings.Contains(bodyContent, wantTitle) {
t.Errorf("Title %s not found in response", wantTitle)
}
}

How to bypass Internet Explorer Enhanced Security when using embedded WebBrowser control?

i have a native Windows application that embeds the WebBrowser, i.e.
CLSID_WebBrowser
8856F961-340A-11D0-A96B-00C04FD705A2
Shell.Explorer.2
Unfortunately, when running on Windows Servers, the Internet Explorer Enhanced Security mode interferes with the WebBrowser control, causing it to not render at all:
In this case, the UI of the software is driven as a WebBrowser control - making the software unusable.
i could disable Internet Explorer Enhanced Security mode, but that is not practical.
How can i instruct Internet Explorer browser to allow an embedded browser to render without the security dialog?
Note: i would have suggested adding about:security_Application.exe to the Trusted Zones list"
Sadly, that will require DRP/FRP validation, an ISO security assessment, and the security group will have to be called in to make the change. In addition, an RFC will need to be created so KPMG won't have hissy-fit next audit. i was hoping for the "good" solution.
See also
Customizing (disabling) security settings for IE control
Custom IInternetSecurityManager not being called with dialogs
You can specify a different URL. For example you can extract the content to a temp file and navigate to it. This will not put your content in the trusted zone, but it is better than the internet zone you get for the about protocol.
If you do not want to save the content, you can first navigate to about:blank, then in DocumentComplete, QI the document for IPersistMoniker, and call Load with a TInterfacedObject that basically simulates a url moniker.
The IMoniker.GetDisplayName implementation needs to return the URL. The url needs to be in a trusted zone.
IMoniker.BindToStorage implementation needs to send back a reference to a TMemoryStream when IStream is asked.
There's a third way, write a process-wide security manager that puts your url in a trusted zone.
The solution is to implement your own Internet Security Manager service creating an object that implements IInternetSecurityManager (see MSDN: Implementing a Custom Security Manager). There are five security zones:
Local: URLZONE_LOCAL_MACHINE (0)
Intranet: URLZONE_INTRANET (1)
Trusted: URLZONE_TRUSTED (2)
Internet: URLZONE_INTERNET (3)
Restricted: URLZONE_UNTRUSTED (4)
The only method you really need to worry about is MapUrlToZone:
TEmbeddedSecurityManager = class(TInterfacedObject, IInternetSecurityManager)
public
//...
function MapUrlToZone(pwszUrl: LPCWSTR; out dwZone: DWORD; dwFlags: DWORD): HResult; virtual; stdcall;
//...
end;
This method checks if the Url starts with about:security
about:security_Contoso.exe
and if so, returns that the zone should be Local:
function TEmbeddedSecurityManager.MapUrlToZone(pwszUrl: LPCWSTR; out dwZone: DWORD; dwFlags: DWORD): HResult;
var
url: UnicodeString;
begin
Result := INET_E_DEFAULT_ACTION;
{
https://msdn.microsoft.com/en-us/library/ms537133(v=vs.85).aspx
}
url := pwszUrl;
{
When IE Enchanced Security is enabled, the url goes from
about:blank_xxxx
to
about:security_xxxx
In that case we will put the page in the "Local" zone
}
if url.StartsWith('about:security') then
begin
dwZone := URLZONE_LOCAL_MACHINE; //Local
Result := S_OK;
end;
end;
Every other method must return INET_E_DEFAULT_ACTION (i.e. not S_OK nor E_NOTIMPL), e.g.:
function TEmbeddedSecurityManager.SetSecuritySite(Site: IInternetSecurityMgrSite): HResult;
begin
Result := INET_E_DEFAULT_ACTION;
end;
You give the embedded WebBrowser this service when it calls IServiceProvider.QueryService. In the case of Delphi's TEmbeddedWB control, it is exposed in the OnQueryService event:
function TForm1.EmbeddedWBQueryService(const rsid, iid: TGUID; out Obj: IInterface): HRESULT;
var
sam: IInternetSecurityManager;
begin
Result := E_NOINTERFACE;
//rsid ==> Service Identifier
//iid ==> Interface identifier
if IsEqualGUID(rsid, IInternetSecurityManager) and IsEqualGUID(iid, IInternetSecurityManager) then
begin
sam := TEmbeddedSecurityManager.Create;
Obj := sam;
Result := S_OK;
end;
end;
Maybe you could consider to load a different embedded browser. There is:
WebKit: http://www.webkit.org/
SWT (eclipse)

dbExpress TSQLConnection param problems

I am new to dbexpress and I cannot figure out how to set the TSQLConnection parm for the SQL Host name at runtime. When I install my program on a client system the TSQLConnectionHost is still reading the Host from my development system that I entered during development.
TSQLConnection.Params is of type TStrings, which means it holds a set of String items. In case of TSQLConnection, Params holds a set of Name=Value pairs, where Name is a parameter name and Value is that parameters value. To read a value of specific parameter, use:
var
s: String;
...
s := SQLConnection1.Params.Values['ParamName'];
To assign a value to specific parameter, use:
SQLConnection1.Params.Values['ParamName'] := 'NewValue';
(Substitute 'ParamName' with actual parameter name and 'NewValue' with actual new value.)
I faced this problem a few years ago when I started developing with dbExpress. On my development machine, the databases were in location X whereas the production machines had the databases in location Y. The way I got around this was to store the physical location of the database in the registry (via a small utility program which I wrote) and then use the following code to load the correct value. The location could be stored in an INI file which would require a slight alteration to my code, but that part is less important.
procedure TDm.SQLConnection1BeforeConnect(Sender: TObject);
var
dir: string;
begin
with TRegIniFile.create (regpath) do // this is where I get the physical value
begin
dir:= ReadString ('firebird', progname, '');
free
end;
with sqlconnection1 do
begin
close;
params.values['database']:= dir;
end;
end;
The reason for your problem is that you have not disconnected the SQLConnection AND all datasets before distrbuting your app.
Things to do
a) make sure all components are NOT connected.
b) set the params of the SQLConnection to blanks.
c) when you app starts, read the required connection params from an ini file, and populate the SQLConnection with those.
d) THEN connect and you will be fine!
Regards
Chris