ShellExecute fails for local html or file URLs - http

Our company is migrating our help systems over to HTML5 format under Flare. We've also added Topic based access to the help systems using Flare CSHID's on the URI command line for accessing the topic directly, such as index.html#CSHID=GettingStarted to launch the GettingStarted.html help page.
Our apps are written in C++ and leverage the Win32 ShellExecute() function to spawn the default application associated with HTTP to display the help system. We've noticed that ShellExecute() works fine when no hashtag is specified, such as
ShellExecute(NULL, _T("open"), _T("c:\\Help\\index.html"), NULL, NULL, SW_SHOWNORMAL);
This function will launch the default browser associated with viewing HTML pages and in this case, the File:/// protocol handler will kick in, the browser will launch and you will see file:///c:/Help/index.html in the address bar.
However, once you add the # information for the topic, ShellExecute() fails to open the page
ShellExecute(NULL,_T("open"),_T("c:\\Help\\index.html#cshid=GettingStarted"),NULL,NULL,SW_SHOWNORMAL);
If the browser opens at all, you'll be directed to file:///c:/Help/index.html without the #cshid=GettingStarted topic identification.
Note that this is only a problem if the File protocol handler is engaged through ShellExecute(), if the help system lives out on the web, and the Http or Https protocol handler is engaged, everything works great.
For our customers, some of whom are on a private LAN, we cannot always rely on Internet access, so our help systems must ship with the application.

After some back-and-forth with Microsoft's MSDN team, they reviewed the source code to the ShellExecute() call and it was determined that yes, when processing File:/// based URLs in ShellExecute(), the ShellExecute() call will strip off the # and any data it finds after the # before launching the default browser and sending in the HTML page to open. MS's stance is that they do this deliberately to prevent injections into the function.
The solution was to beef up the ShellExecute() call by searching the URL for a # and if one was found, then we would manually launch the default browser with the URL. Here's the pseudocode
void WebDrive_ShellExecute(LPCTSTR szURL)
{
if ( _tcschr(szURL,_T('#')) )
{
//
//Get Default Browser from Registry, then launch it.
//
::RegGetStr(HKCR,_T("HTTP\\Shell\\Open\\Command"),szBrowser);
::CreateProcess ( NULL, szBrowser + _T(" ") + szURL, NULL, NULL, FALSE, 0, NULL, NULL, &sui, &pi);
}
else
ShellExecute(NULL,_T("open"),szURL,NULL,NULL,SW_SHOWNORMAL);
}
Granted there's a bit more to the c++ code, but this general design worked for us.

I tried WebDrive's solution and it didn't really work on Windows 10.
"HTTP\Shell\Open\Command" default value is set to Internet Explorer path, regardless of what my default browser setting. However, for Internet Explorer that solution DOES work.
Process to fetch default browser path on Windows 10 is a bit different (How to determine the Windows default browser (at the top of the start menu)) but even then the solution is not guaranteed to work, depending on the browser. E.g. for me it didn't work with Edge.
To get it to work with Edge I had to add "file:///" to the URL -- but that also makes the URL work with ShellExecute(). So, at least on Windows 10, all I needed to do was this:
ShellExecute(NULL,_T("open"),_T("file:///c:/Help/Default.html#cshid=1648"),NULL,NULL,NULL);
UPDATE:
The above stopped working months ago. What I eventually did was go through temporary file, as described here: https://forums.madcapsoftware.com/viewtopic.php?f=9&t=28376#p130613

Use FindExecutable() to get the default browser and pass the full help file path with its queries (?) and fragments (#) as the lpParameters parameter to ShellExecute(). They won't get stripped off there.
Then handle the case if it is a Store App (most likely Microsoft Edge).
Pseudo C code:
if (FindExecutable(_T("c:\Help\index.html"), NULL, szBrowser)
{
if (szBrowser == _T("C:\WINDOWS\system32\LaunchWinApp.exe"))
{
// default browser is a Windows Store App
szBrowser = _T("shell:AppsFolder\Microsoft.MicrosoftEdge_8wekyb3d8bbwe!MicrosoftEdge");
}
}
else
{
szBrowser = szURL;
szURL = NULL;
}
ShellExecute(NULL, NULL, szBrowser, szURL, NULL, SW_SHOWNORMAL);

I solved the problem without using any method other than ShellExecute in a Qt Application
QString currentpath = QDir::currentPath();
QString url = "/help//html/index.html#current";
QString full_url = "file:///" + currentpath + url;
QByteArray full_url_arr= full_url.toLocal8Bit();
LPCSTR lp = LPCSTR(full_url_arr.constData());
ShellExecute(NULL, "open", lp, NULL, NULL, SW_SHOWNORMAL);

Related

Xamarin Forms Maps Geocoder Not Working on UWP Device

My app uses Xamarin.Forms.Maps to display a map and also for geocoding. The map is displayed on a separate page when the user navigates to it from the main page. I use the geocoder to reverse geocode the current location so that I have the address. This is done from various places other than the map page.
When I run the app on a device (even in debug mode) the geocoder works right away in iOS and Android, but does not work in UWP. After I navigate to the map page and display the map, then go back to a different page to use the geocoder it starts working.
I saw a thread about the map not working with release build so I added the following code:
var laRendererAssemblies = new[] { typeof(Xamarin.Forms.Maps.UWP.MapRenderer).GetTypeInfo().Assembly };
Xamarin.Forms.Forms.Init(e, laRendererAssemblies);
//Xamarin.Forms.Forms.Init(e);
Xamarin.FormsMaps.Init("MyBingMapsKey");
This has not helped the issue with the Xamarin.Forms.Maps.Geocoder. I also tried creating an instance of Xamarin.Forms.Maps.Map in my main page, but that did not help either. Is there a way to prime the map component so that the Geocoder will work on a device? (My test device is ARM, but it happens when I run on Local
Machine (Win 10) too)
Following is a snippet of the call to the Geocoder (which works fine once the user has navigated to the Map page and back - and it works fine in iOS and Android - and as such I don't believe it is a problem with the code, but here it is):
public static async Task<Plugin.Geolocator.Abstractions.Position> Geocode(string address)
{
try
{
var loGeocoder = new Xamarin.Forms.Maps.Geocoder();
System.Diagnostics.Debug.WriteLine("Get Lat/Lon");
var lcolPositions = await loGeocoder.GetPositionsForAddressAsync(address);
if (lcolPositions != null)
After doing some research and ensuring that your geodecode class being static wouldn't mess with the async/await pattern in the UWP build. I've come across a few references to this particular problem with the built in Forms.Map geodecoder elsewhere, not just for UWP it has also been noted for android‡.
I took some time to have a look at one of our current cross-platform applications that we have in the app stores, and according to our internal documentation we switched out both the xamarin.forms map, and the geodecoder for custom ones.
The plugin that we use for our cross-platform application is the 'GelocatorPlugin' created by james montemagno, and can be found here.
It can be added to your project as a Nuget package if you prefer, and the implementation of it is very similar to the default one, so there's very little code to change. The primary benefit is that the UWP element of the geodecode plugin has been modified to take into account windows advanced tracking scenarios (details found here).
It should be a lot more stable than the one your using, once installed you simply use it like so:
Reverse Geocoding
Based on a location that is passed in, thi swill grab a list of
addresses.
UWP requires a Bing Map Key, which you can acquire by reading this
piece of documentation.
try
{
var addresses = await locator.GetAddressesForPositionAsync (position, string mapKey = null);
var address = addresses.FirstOrDefault();
if(address == null)
Console.WriteLine ("No address found for position.");
else
Console.WriteLine ("Addresss: {0} {1} {2}", address.Thoroughfare, address.Locality, address.Country);
}
catch(Exception ex)
{
Debug.WriteLine("Unable to get address: " + ex);
}
‡ Links to similar problems - Link 1, Link 2
resolved after added following lines in APP.xaml.cs (UWP project)
Xamarin.FormsMaps.Init("bingmapkey");
Windows.Services.Maps.MapService.ServiceToken = "bingmapkey";

Google Maps from Firefox addon (without SDK)

I need to add a map in my adddon and I know how to do what I need in a "common webpage", like I did here: http://jsfiddle.net/hCymP/6/
The problem is I really don't know how to to the same in a Firefox Addon. I tryed importing the scripts with LoadSubScript and also tryed adding a chrome html with the next line:
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
But nothing works. The best solution I found was to add part of the code in this file (the code of the script src) in my function, to import this file with loadSubScript, and all my function is executed but an empty div is returned.
Components.utils.import("resource://gre/modules/Services.jsm");
window.google = {};
window.google.maps = {};
window.google.maps.modules = {};
var modules = window.google.maps.modules;
var loadScriptTime = (new window.Date).getTime();
window.google.maps.__gjsload__ = function(name, text) { modules[name] = text;};
window.google.maps.Load = function(apiLoad) {
delete window.google.maps.Load;
apiLoad([0.009999999776482582,[[["https://mts0.googleapis.com/vt?lyrs=m#227000000\u0026src=api\u0026hl=en-US\u0026","https://mts1.googleapis.com/vt?lyrs=m#227000000\u0026src=api\u0026hl=en-US\u0026"],null,null,null,null,"m#227000000"],[["https://khms0.googleapis.com/kh?v=134\u0026hl=en-US\u0026","https://khms1.googleapis.com/kh?v=134\u0026hl=en-US\u0026"],null,null,null,1,"134"],[["https://mts0.googleapis.com/vt?lyrs=h#227000000\u0026src=api\u0026hl=en-US\u0026","https://mts1.googleapis.com/vt?lyrs=h#227000000\u0026src=api\u0026hl=en-US\u0026"],null,null,null,null,"h#227000000"],[["https://mts0.googleapis.com/vt?lyrs=t#131,r#227000000\u0026src=api\u0026hl=en-US\u0026","https://mts1.googleapis.com/vt?lyrs=t#131,r#227000000\u0026src=api\u0026hl=en-US\u0026"],null,null,null,null,"t#131,r#227000000"],null,null,[["https://cbks0.googleapis.com/cbk?","https://cbks1.googleapis.com/cbk?"]],[["https://khms0.googleapis.com/kh?v=80\u0026hl=en-US\u0026","https://khms1.googleapis.com/kh?v=80\u0026hl=en-US\u0026"],null,null,null,null,"80"],[["https://mts0.googleapis.com/mapslt?hl=en-US\u0026","https://mts1.googleapis.com/mapslt?hl=en-US\u0026"]],[["https://mts0.googleapis.com/mapslt/ft?hl=en-US\u0026","https://mts1.googleapis.com/mapslt/ft?hl=en-US\u0026"]],[["https://mts0.googleapis.com/vt?hl=en-US\u0026","https://mts1.googleapis.com/vt?hl=en-US\u0026"]],[["https://mts0.googleapis.com/mapslt/loom?hl=en-US\u0026","https://mts1.googleapis.com/mapslt/loom?hl=en-US\u0026"]],[["https://mts0.googleapis.com/mapslt?hl=en-US\u0026","https://mts1.googleapis.com/mapslt?hl=en-US\u0026"]],[["https://mts0.googleapis.com/mapslt/ft?hl=en-US\u0026","https://mts1.googleapis.com/mapslt/ft?hl=en-US\u0026"]]],["en-US","US",null,0,null,null,"https://maps.gstatic.com/mapfiles/","https://csi.gstatic.com","https://maps.googleapis.com","https://maps.googleapis.com"],["https://maps.gstatic.com/intl/en_us/mapfiles/api-3/13/11","3.13.11"],[3047554353],1.0,null,null,null,null,1,"",null,null,1,"https://khms.googleapis.com/mz?v=134\u0026",null,"https://earthbuilder.googleapis.com","https://earthbuilder.googleapis.com",null,"https://mts.googleapis.com/vt/icon"], loadScriptTime);
};
//I can't use document.write but use loadSubScript insthead
Services.scriptloader.loadSubScript("chrome://googleMaps/content/Google-Maps-V3.js", window, "utf8"); //chrome://MoWA/content/Google-Maps-V3.js", window, "utf8");
var mapContainer = window.content.document.createElement('canvas');
mapContainer.setAttribute('id', "map");
mapContainer.setAttribute('style',"width: 500px; height: 300px");
mapContainer.style.backgroundColor = "red";
var mapOptions = {
center: new window.google.maps.LatLng(latitude, longitude),
zoom: 5,
mapTypeId: window.google.maps.MapTypeId.ROADMAP
}
var map = new window.google.maps.Map(mapContainer,mapOptions);
return mapContainer;
Can you help me? I'm developing a "Firefox for Android" addon and that's why I need to do things like *window.content.*document.createElement because document is not declared, only window and I think thats may be the problem... But I can't declare everything if I don't know what Google Maps uses.
Added: I also read that Google Maps API Team has specific code that disallows you from copying the main script locally. In particular, that code "expires" every so many hours. I'm combined part of this script: https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false because I can't execute this directly (Error: write called on an object that does not implement interface HTMLDocument). So I don't have any alternative!
Use an iframe (type=content if in XUL) to display web content. There you can include whatever scripts you like. The content in the iframe will not have any special privileges, or at least should not. If you need to communicate with the privileged add-on part of your code, you can use e.g. regular HTML events (createEvent, addEventListener and friends) or the postMessage web API to pass messages.
Do not try to load remote code directly into other pages, or worse, into the browser, as this is a compatibility and security nightmare.
Because loading remote code and/or code not properly reviewed for running in a privileged context, the platform will refuse to load such scripts from remote sources (http, etc.) via loadSubScript, etc.
Should be noted, that if you'd later like to host your add-on on addons.mozilla.org and still do include remote scripts in privileged code, your add-on will be rejected until you fix it.
Also, mozilla might blocklist your add-on even if you host elsewhere if it is discovered that there are known security vulnerabilities in your add-on, per the Add-on Guidelines.

How to store translations in a phonegap application and save the user preferences?

I'm developing a Phonegap application using jQuery Mobile. It's a very basic application, its purpose is to show information about a big organization in Spanish and English. On the first page the application shows 2 options, Spanish and English. If the user selects Spanish, the information displayed must be Spanish and vice versa.
Using SQLite DB will probably give some problems on Windows Phones since it is not yet supported (see Phonegap Storage).
There is the File Storage option too. And raw JSON files, as well.
The way I do it is to create a language specific json file to hold all my strings. In this case english.json and spanish.json. Structure the json like:
{
help: "Help",
ok: "Okay"
}
On the first page of your app when the user clicks the Spanish button for instance it should set a value in localStorage.
localStorage.setItem("lang", "spanish");
Then in the second page once you get the "deviceready" event you should load the correct json file using XHR.
var request = new XMLHttpRequest();
request.open("GET", localStorage.getItem("lang") + ".json", true);
request.onreadystatechange = function(){//Call a function when the state changes.
if (request.readyState == 4) {
if (request.status == 200 || request.status == 0) {
langStrings = JSON.parse(request.responseText);
}
}
}
request.send();
Now whenever you want to use a translated string you get it from langStrings.
langStrings.ok;
Make sense?
For persistance I successfully used Html5 Local Storage.
It works on Android, iOS and Windows Phone 7(I tried it on these platforms).
I use it like this.
For i18n you can use any javascript i18n library. I created own simple solution.

Silverlight MediaElement refusing to play audio

I am having the hardest time figuring this problem out. I have a Silverlight 4 application that loads audio and video files from URLs. The URLs are the same domain as the application is hosted on and it works great for video.
The URLs are actually asp.net mvc controllers that are responsible for reading the file from a shared location on and the server and serving back a filestream. The URLs look something like this:
http://localhost:31479/CourseMedia?path=\omnisandbox1\ILMSShare2\Demo-Fire+Behavior\media\Disclaim.wma&encrypted=False&id=00000000-0000-0000-0000-000000000000
If I put the URL directly into the browser the file loads and plays in windows media player just fine, and if I use a separate test silverlight project to load the url it also works, but for the life of me I can not get it to work properly in my main project.
This is the routine I use to actually do the source setting:
protected void SetPlayerURL(MediaElement player, string url)
{
if (player != null && url.Length > 0)
{
player.ClearValue(MediaElement.SourceProperty);
player.Source = new Uri(this.Packet.GetMediaUrl(url, false, Guid.Empty));
}
}
and the GetMediaURL function simply builds the URL format seen above:
public string GetMediaUrl(
string path,
bool encrypted,
Guid key)
{
StringBuilder builder = new StringBuilder();
builder.AppendFormat("http://{0}/CourseMedia?path={1}&encrypted={2}&id={3}",
this.Host,
System.Windows.Browser.HttpUtility.UrlEncode(path),
encrypted,
key);
return builder.ToString();
}
The request to the controller is never made for the media when it is audio. Seems odd to me as this exact code works fine for video. The MediaElement state never leaves "Closed" and the CurrentStateChanged,, MediaOpened, and MediaFailed events are never triggered.
I am at a loss!
Try setting ScrubbingEnabled of the MediaElement to false, there were some problems with Framework version 3.5 and audio and the workaround was setting that to false. Might be worth trying.
Also try capturing BufferingStarted, BufferingEnded, MediaEnded along with your MediaFailed and MediaOpened events. I'm curious if it is a buffering issue.

Seeking not working in HTML5 audio tag

I have a lighttpd server running locally. If I load a static file on the server (through an html5 audio tag), it plays and seeks fine.
However, seeking doesn't work when running a dev server (web.py/CherryPy) or if I return the bytes via a defined action url instead of as a static file. It won't load the duration either.
According to the "HTTP byte range requests" section in this Opera Page it's something to do with support for byte range requests/partial content responses. The content is treated as streaming instead.
What I don't understand is:
If the browser has the whole file downloaded surely it can display the duration, and surely it can seek.
What I need to do on the web server to enable byte range requests (for non-static urls).
Any advice would be most gratefully received.
Here's some web.py code to get you started (just happened to need this as well and ran into your question):
## experimental partial content support
## perhaps this shouldn't be enabled by default
range = web.ctx.env.get('HTTP_RANGE')
if range is None:
return result
total = len(result)
_, r = range.split("=")
partial_start, partial_end = r.split("-")
start = int(partial_start)
if not partial_end:
end = total-1
else:
end = int(partial_end)
chunksize = (end-start)+1
web.ctx.status = "206 Partial Content"
web.header("Content-Range", "bytes %d-%d/%d" % (start, end, total))
web.header("Accept-Ranges", "bytes")
web.header("Content-Length", chunksize)
return result[start:end+1]
Google tells me you have to use the staticFilter for byte ranges to work in CherryPy - but that is for static files only. Luckily this posting also includes pointers on how to do it for non-static data :-)

Resources