Simple function to read file from an URL to a string buffer ( C++ / MQL{4|5} using WinInet.dll ) - wininet

I am looking for a simple function which is able to read a text or binary file from the internet into a string variable.
It´s unbelievable that I could not find anything in the web, just low level descriptions of all the WinInet functions and useless samples, that do not work at all, at the MQL-forums.
What I need is a function like:
string buffer = ReadTextFileFromWeb( "www.myurl.net/textfile.txt" );
No more, no less. I am not very familiar with internet programming stuff at all, but I am sure there is anybody out there who is able to present the reason just like that.
The code will be used in MQL4/MQL5. I know that there is already a WebRequest() function which works, but it is restricted to expert advisors and cannot be used in Custom Indicator type of code.
I need this solution to load data into a custom indicator.

Go get this on github https://github.com/sergeylukin/mql4-http
//For MT4 Add HTTP Access
#include <mql4-http.mqh>
string URLr = "www.myurl.net/textfile.txt";
Print("URLr return is: ", URLr);
For MT5 you are on your own.
The above dose not have the issues that WebRequest() has. Or I have not seen it have any issues. I use it all the time in a lot of EA and never had a chart lockup or have a issue.

Related

Display player count on website from another website

I'm trying to fetch "current / max Players" from this site:
http://rust-servers.net/server/64099/
I would like to display just the player numbers, eg. "70 / 175" on another website and have it update every time someone visits my .html page (I can change that one to .php if needed.)
How would I go about doing that in the most simple and efficient way?
I've googled the issue for some hours without any luck, I'm no closer to understanding what I would want to use to do this as everyone seems to suggest widely different methods and most seem way too verbose for the simple thing I'm trying to do - many examples fetch the data as JSON (?) with some JS/jQuery (?) and use a bit of code to find specific items in that data, define it as a variable or array and then display it later.
I've figured that the information I want can be referred to using XPath "/html/body/div[4]/div/div/div[9]/div[1]/table/tbody/tr[4]/td[2]/strong" but that's about it. How do I proceed from there?
Thank you.
It depends on which platform do you want to use.
If you use C#, you can use HtmlAgilityPack library.
It is basically like this:
var webClient.DownloadString("http://rust-servers.net/server/64099/");
var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(htmlCode);
var node = doc.DocumentNode.SelectSingleNode("/html[1]/body[1]/div[4]/div[1]/div[1]/div[9]/div[1]/table[1]/tbody[1]/tr[4]/td[2]");
var nodeValue = node.InnerText;

Reading from a text file into HTML

I want to make a small html based game for a school project. I would like to be able to extract data from a text file, then insert if necessary in order to save data. So my question is:
What programming language can i use in order to read from a .txt file into a HTML page?
Thanks in advance for any help you are able to provide.
My suggestion would be php. There are dozens of methods to achieve this. Note, however, that this task will be much easier to accomplish if your text file is on the same domain as the code. This is best for single levels that dont change.
Php
In php, you could use
$file = fopen('pathtofile.txt', r);
Note that the second parameter, r, signifies that the file should be readable. Use w if you want to write to the file.
There are a lot of tutorials on google for this.
Ajax
If you'd prefer not to use php, Ajax is also available to you via javascript. This method is best if you need to change files while the game is running, ie loading new levels.
$.ajax({
method: 'get',
path: 'pathtofile.txt',
success: function(data){
//level info is in **data**
},
error: function(x, h, r){
// this will display error info, ie file does not exist
}
})
The code above most likely won't work, it is intended as a demo. Again, there are plenty of examples for this on google.
Have fun and happy coding.

What is the best way to make a configurable text elements for HTML5 App

I am doing a HTML5 app. Everything works well. The client suddenly requested that he needs to change error messages and text labels as he wish after completing the code, but without touching the HTML5. So I got two solutions in to my mind.
1 Use javascript variables
// Error Messages
var msg_authentication_failed = "The username or password is invalid. Please try again";
and use this variable as I wanted.
2 Use XML file (Or JSON)
<?xml version="1.0" encoding="ISO-8859-1"?>
<ErrorMessages>
<AuthenticationFail>The username or password is invalid. Please try again</AuthenticationFail>
</ErrorMessages>
Load XML file and set values using it's tag names.
However I feel that the 2nd solution is easy to maintain by the client but performance wise it's not good.
Is there any other possible way to get done this kind of requirement? Appreciate your suggestions.
I'm running a jQuery Mobile project which supports around 6 languages (from Europe) and what I did was simply maintaining the labels in a JSON string.
using the event pagebeforeshow I update the labels when showing form element's labels. If it is an error message, I wrote a custom function that can access the string based on the labelID.
More than XML, JSON is extremely easy to handle. I would suggest you to go ahead with it.

What is background to have ServerHandler.addCallbackElement method?

Frequently GAS users (me too) do not use the ServerHandler.addCallbackElement method or use in a way which does not cover all controls.
What is a background to have this method at all? Why GAS developers introduced it? Is it simpler to pass all input widgets values to all server handlers as parameters?
The documentation does not provide answers to these questions.
I see the following causes
Adding widgets as callback elements reduces traffic between browsers and GAS servers in case of several handlers which handle different sets of controls. Here is a question. How much traffic it saves? I think maximum a few kilobytes, usually hundreds of bytes. Is it worth, considering the modern internet connections speed, even mobile connections.
A form contains a table-like edit controls with multiple buttons and it is comfortable to handle row elements with the same name. This issue is easily avoided by using tags. See the following example. If the tags are used for other purposes it is not a problem to parse the source button id and extract the row number.
Limits of technology used behind the scenes. If there are such limits, then what are they?
function doGet(e) {
var app = UiApp.createApplication();
var vPanel = app.createVerticalPanel();
var handler = app.createServerHandler("onBtnClick");
var lstWidgets = [];
for (var i = 0; i < 10; i++) {
var hPanel = app.createHorizontalPanel().setTag('id_' + i);
var text = app.createTextBox().setName("text_" + i);
text.setText(new Date().valueOf());
var btn = app.createButton("click me").addClickHandler(handler);
btn.setTag(i).setId('id_btn' + i);
var lbl = app.createLabel().setId("lbl_" + i);
hPanel.add(text);
hPanel.add(btn);
hPanel.add(lbl);
lstWidgets.push(text);
lstWidgets.push(btn);
vPanel.add(hPanel);
}
// The addCallbackElement calls simulate situation when all widgets values are passed to a single server handler.
for (var j = 0; j < lstWidgets.length; j++) {
handler.addCallbackElement(lstWidgets[j]);
}
app.add(vPanel);
return app;
}
function onBtnClick(e) {
var app = UiApp.getActiveApplication();
var i = e.parameter[e.parameter.source + '_tag'];
var lbl = app.getElementById("lbl_" + i);
lbl.setText("Source ButtonID: " + e.parameter.source + ', Text: ' + e.parameter["text_" + i]);
return app;
}
Great Question.
"How much traffic it saves?" I don't think we know yet, but I expect it will get more efficient over time. Here is another discussion on performance. Only extensive testing and improvements from Google will really allow us to identify best practices, for now all I can say is that ClientHandlers are clearly going to be better than ServerHandlers whenever possible.
As JavaScript developers I think we are predominantly use to doing stuff client-side, then we think of PHP/ASP as server-side tools. My understanding so far is that our GAS code is actually running both client and server side (at the very least it's calling server side functionality) but it sure seems like there's more going on server-side than we realize, and on the client-side this seems to result in somewhat "compiled" code. I kinda recognize some of this multi-tier deployment from my Java experience.
Since there are a lot of ways of doing the same thing, Google can take advantage of the fact that our code is not directly interpreted (by either side) to do things that would not necessarily make sense if we were writing the code by hand. This is why I think it will become more efficient than other solutions, eventually but probably not yet. For now I'd suggest steering clear of GAS if you are worried about performance. Maybe just for fun try looking at the source of your client-side Web-Apps at runtime (view source). So in order for them to do things most efficiently, I imagine they will benefit by having us define things in a very high-level way. This gives them the most flexibility in how they interpret our code.
To specifically address your second question I personally think of the Handler Function onBtnClick() as running on the Server-Side, whereas the Tags you refer to (and most of the doGet) would be in the browser's engine on the client-side. I can see how the functionality would be much more flexible (efficient and powerful) on the server-side if they have an idea ahead of time as to how much memory they would need to handle specific events/requests. (Clearly if each getElementById() call was running a separate request, that would be like clicking a link to a new mini-webpage each time.)
So now the question is why can't my handler just automatically create parameters with just the stuff I use in my handler function? The only reason we are asking this question in the first place is because there is some stuff in the UiApp which seems to be available on both ends. The UiApp is already in the scope of both the doGet and onClick but the variables defined in doGet are not, so these values need to be either
explicitly saved like ScriptProperties.setProperty() or
put into the UiApp somewhere with an Id or
explicitly given to the Handler function using addCallbackElement()
Notice how you had to addCallbackElement(lstWidget), because it was not created with an app.create... constructor within the UiApp object. My guess is that GAS is implementing XML compliant SOAP calls to a web-service on the Google end, we may be able to figure this out by really studying the client-side source code. Just to reiterate we could also use setProperty() it does not really matter, or even save them via JDBC and then retrieve them with another connection from within your handler function but somehow the data needs to be passed from the Client to the Server and vice-versa.
From a programming perspective there is a lot of stuff available in the scope of your client-side doGet function that you probably would never want to pass to the server, or there may be functions in the scope of the server-side doClick() with the same name as functions on the client-side but they may actually be calls to totally different library functions maybe even on totally different hardware (even though from the developer's perspective they work the same way).
Maybe the Google team has not yet really decided on how the UiApp really works yet, otherwise they would just force or at least allow us to put everything in there. Yet another observation when we call UiApp.getActiveApplication() based on it's name it does not seem like a constructor, but rather a method that returns a private instance from the UiApp object. (Object being a class that was previously instantiated and supposedly initialized somewhere.) I may not have 100% answered your question but I sure did try, any further insight from the community would clearly be appreciated.
Now I may be straying off-topic but I also imagine the actual product will continue to change as they do more to improve performance in the long-term, and if we still feel like we are writing client-side code as a developer then that is a success for Google. Now please correct me if I have stated anything wrong, I have just recently started using these tools and plan to follow up on this question with more specifics as I learn more but as of right now that is my best interpretation.
If you use a formpanel all the sub elements will be sent to your dopost function. With the button as source. And your UIapp will be cleaned.
If you don't want that use a callback to specify what element and siblings will be sent.
This is how the UIapp is designed.

Web automation

I'm developing an interface between an old web based application and another one. That old web-based application works fine but there no exists any API to communicate with.
There is any programmatic way to say a web-form something like: enter this value on this field, this one ins other and submit form?
UPDATE: I looking for something like this:
WebAutomation w = new WebAutomation("http://apphost/report");
w.forms[0].input[3].value = 123;
w.forms[0].input[4].value = "hello";
Response r = w.forms[0].submit();
...
Despite the tag on your question, the answer is going to be highly language specific. There are also going to be wide range of solutions depending on how complex of a solution you are willing to implement and how flexible a result you are looking for.
On the one hand you can accomplish a lot in a very short period of time with something like Python's mechanize, but on the other hand, you can really get into the guts and have a lot of control by automating a browser using a COM object such as SHDocVw (Windows-only, of course).
Or, as LoveMeSomeCode suggested, you can really hit your head against the concrete and start forging POST requests, but good-luck figuring out what the server expects if is doing any front-end processing of the form data.
EDIT:
One more option, if you are looking for something that you can come up to speed on quickly, is to use a AutoIt's IE module, which basically provides a programmatic interface over an instance of Internet Explorer (its all COM in underneath, of course). Keep in mind that this will likely be the least supportable option you could choose. I have personally used this to produce proof-of-concept automation suites that were then migrated to a more robust C# implementation where I handled the COM calls myself.
In .NET: http://watin.sourceforge.net/
In ruby: http://wtr.rubyforge.org/
Cross platform: http://seleniumhq.org/
You can, but you have to mock up a POST request. The fields (textboxes, radio buttons, etc.) are transmitted as key-value pairs back to the resource. You need to make a request for this resource(whichever one is used in the SUBMIT action for the FORM tag) and put all your field-value pairs in a POST payload no the request.
Here's a good program to see what values are being transmitted: http://www.httpwatch.com
Or, you can use Firebug, a free Firefox extension.
The Perl module WWW::Mechanize does exactly that. Your
example would look something like this:
use WWW::Mechanize;
my $agent = WWW::Mechanize->new;
$agent->get("http://apphost/report");
my $response = $agent->submit_form(
with_fields => {
field_1_name => 123,
field_2_name => "hello",
},
);
There is also a Python port, and I guess similar libraries exist for many other languages.