How to properly build HTTP connection suffix - blackberry

I have written code to get a location name using Google Maps reverse geocoding, for example:
http://maps.google.com/maps/geo?json&ll=9.6,73.7
How can I add an appropriate HTTP connection suffix to the above URL?
I have tried the following function:
private static String getConnectionStringForGoogleMap(){
String connectionString="";
if(WLANInfo.getWLANState()==WLANInfo.WLAN_STATE_CONNECTED){
connectionString="&interface=wifi";
}
else if((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS){
connectionString = "&deviceside=false";
}
else if((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT)==CoverageInfo.COVERAGE_DIRECT){
String carrierUid=getCarrierBIBSUid();
if(carrierUid == null) {
connectionString = "&deviceside=true";
}
else{
connectionString = "&deviceside=false&connectionUID="+carrierUid + "&ConnectionType=mds-public";
}
}
else if(CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE)
{
}
return connectionString;
}
When I run the application in the simulator, I create the URL like this:
http://maps.google.com/maps/geo?json&ll=9.6,73.7+getConnectionStringForGoogleMap();
But I get a tunnel exception and am not sure what to do next.
This URL also leads to an exception:
http://maps.google.com/maps/geo?json&ll=9.6,73.7&deviceside=false&ConnectionType=mds-public
As does:
http://maps.google.com/maps/geo?json&ll=9.6,73.7;deviceside=false;ConnectionType=mds-public
I am confused about what to do to get this to work.

You definitely want semi-colons (;) and not ampersands (&). Are you tring to run this on the simulator? If so, do you have the MDS simulator running? That is required in order to use devicside=false on the simulator.

Try using Versatile Monkey's networking helper class to find the best path for your HTTP connection and avoid those tunnel exceptions. And form the URL with the correct syntax.

There is a very good posting about this on the BlackBerry Java development forum, complete with sample HTTP connection code.

Try using following
It worked for me
http://maps.google.com/maps/geo?json&ll=9.6,73.7&;deviceside=false;ConnectionType=mds-public

If you are targeting OS5 and above you can use ConnectionFactory. This takes a lot of the hard work out of establishing the correct connection type.

Related

Xamarin Forms - iOS not processing correctly

I am using the CrossDownManager plugin for Xamarin Forms
Here
When I run the method on Android it processes as expected. On iOS Debug.Writeline("Success!") isn't being hit like it was on Android.
Here is the code:
void ViewImage(string imageLink)
{
var downloadManager = CrossDownloadManager.Current;
downloadManager.PathNameForDownloadedFile = new System.Func<IDownloadFile, string>(file =>
{
string path = DependencyService.Get<IImageSaver>().Save("YHTS" + DateTime.Today.Ticks.ToString() + ".jpg");
Debug.WriteLine("Success!");
return path;
});
try
{
var file = downloadManager.CreateDownloadFile(imageLink);
Debug.WriteLine("file created");
downloadManager.Start(file);
Debug.WriteLine("downloadstarted");
}
catch (Exception e)
{
Debug.WriteLine(e.ToString());
}
}
For the life of me I can't figure out why the that code block isn't processed. Any ideas?
This is an interesting issue as technically your code should work as expected. I've done a little digging and found a reply to a similar question here.
your options are many... including:
DEBUG preprocessor as you show in your question.
Use System.Diagnostic.Debug.WriteLine: Any calls to Debug.* will be
removed by the compiler due to the [Conditional("DEBUG")] attribute
being applied.
Create your own "Logger" class as a wrapper to the stdout writers and
[Conditional("DEBUG")] it
Use Fody and re-weave the assemblies to remove/NOP/redirect the
WriteLine I do this to redirect the calls to in internal log and upon
crash or user stat requests, forward this log to our crash reporting
servers. etc, .....
So there are a few alternatives to consider, one of the common suggestions I've seen is to use the fully qualified reference for WriteLine(); as such:
System.Console.WriteLine("woop woop");
I would suggest giving the above a try first.

How to handle errors while using Glib.Settings in Vala?

I am using Glib.Settings in my Vala application. And I want to make sure that my program will work okay even when the schema or key is not available. So I've added a try/catch block, but if I'm using the key that doesn't exist, the program segfaults. As I understood, it doesn't even reach the catch statement.
Here is the function that uses settings:
GLib.Settings settings;
string token = "";
try
{
settings = new GLib.Settings (my_scheme);
token = settings.get_string("token1");
}
catch (Error e)
{
print("error");
token = "";
}
return token;
And the program output is:
(main:27194): GLib-GIO-ERROR **: Settings schema 'my_scheme' does not contain a key named 'token1'
Trace/breakpoint trap (core dumped)
(of course I'm using my real scheme string instead of my_scheme)
So can you suggest me where I'm wrong?
I know this is super late, but I was looking for the same solution so I thought I'd share one. As #apmasell said, the GLib.Settings methods don't throw exceptions—they just abort instead.
However, you can do a SettingsSchemaSource.lookup to make sure the key exists first. You can then also use has_key for specific keys. For example,
var settings_schema = SettingsSchemaSource.get_default ().lookup ("my_scheme", false);
if (settings_schema != null) {
if (settings_schema.has_key ("token1")) {
var settings = new GLib.Settings ("my_scheme");
token = settings.get_string("token1");
} else {
critical ("Key does not exist");
}
} else {
critical ("Schema does not exist");
}
The methods in GLib.Settings, including get_string do not throw exceptions, they call abort inside the library. This is not an ideal design, but there isn't anything you can do about it.
In this case, the correct thing to do is fix your schema, install into /usr/share/glib-2.0/schemas and run glib-compile-schemas on that directory (as root).
Vala only has checked exceptions, so, unlike C#, a method must declare that it will throw, or it is not possible to do so. You can always double check the Valadoc or the VAPI to see.

Read text from an URL on Codename One

I'm relatively new to codename one. I'm trying to read text from a pure text url and store the text in a string. I tried using the java IO package but for some reason it doesn't seem to wirk with codename one. Please help.
David.
I think you might not really understand codenameone seeing as you tried to use the Java IO package. But anyway, this code might get you along
ConnectionRequest r = new ConnectionRequest();
r.setUrl("YOURURLHERE");
r.setPost(false);
r.addResponseListener(new ActionListener()
{
public void actionPerformed(ActionEvent ev)
{
try
{
NetworkEvent event = (NetworkEvent) ev;
byte[] data= (byte[]) event.getMetaData();
String decodedData = new String(data,"UTF-8");
System.out.println(decodedData);
} catch (Exception ex)
{
ex.printStackTrace();
}
}
});
NetworkManager.getInstance().addToQueue(r);
NOTE: Instead of using System.out.println, which works fine for debugging purposes, you probably want to add the text to your application with a GUI component. I'm not sure if this needs to be said, but it won't do any harm stating it again :)

Default DNS server in monotouch

I'm wondering how do I get default DNS server in monotouch?
this code works perfectly in simulator, but gives 0 records on device.
NetworkInterface.GetAllNetworkInterfaces();
foreach (IPAddress ipAddr in ipProps.DnsAddresses)
Console.WriteLine(ipAddr);
from the other hand, this code works on both simulator and device:
IPHostEntry he = Dns.GetHostEntry(domain);
dns = he.HostName.ToString();
having all this, I assume DNS server address is stored somewhere. I mean it is accessible. How to get its IP?
This will get the IP Address in MonoTouch:-
public string GetIPAddress()
{
string address = "Not Connected";
try
{
#if SIM
address = IPAddress.FileStyleUriParser("127.0.0.1");
#else
string str = Dns.GetHostName() + ".local";
IPHostEntry hostEntry = Dns.GetHostEntry(str);
address = (
from addr in hostEntry.AddressList
where addr.AddressFamily == AddressFamily.InterNetwork
select addr.ToString()
).FirstOrDefault();
#endif
}
catch (Exception ex)
{
// Add error handling....
}
return address;
}
Note the difference between using the simulator and device.
I do not believe such an API exists on iOS (but I would be happy to be proven wrong). Other projects, that needs this information, relies on hacks like using well known, static address to DNS servers) to overcome this.
Now the reason code like this:
var all = NetworkInterface.GetAllNetworkInterfaces ();
foreach (NetworkInterface ni in all) {
var props = ni.GetIPProperties ();
foreach (var dns in props.DnsAddresses) {
Console.WriteLine (dns);
}
}
works on the simulator is because it's a simulator and not an emulator. IOW the host (Mac) computer allows far more things than a real iOS device will allow.
More precisely props will be an instance of System.Net.NetworkInformation.MacOsIPInterfaceProperties, which inherits from UnixIPInterfaceProperties, and ends up reading the /etc/resolv.conf file (which iOS disallow your application from reading).
The second case, calling Dns.GetHostEntry, goes down into the Mono runtime but end up calling gethostname which does not require the caller to know the DNS server address.

URL-encode parameters in ActionLink?

I have the following route registered;
routes.MapRoute(
"LocationsByArea",
"Locations/{system}/{storage}/{area}",
new { controller = "StorageLocation", action = "Index" },
null
);
...and the following code in my view;
<%= Html.ActionLink("Platser", "Index", "StorageLocation", new { system = Model.System, storage = Model.Storage, area = item.Name }, null)%>
My problem is when the "area = item.Name" contains a colon, e.g. "Area 4:1". If I click the rendered link I get HTTP-error 400, Bad reqest. I guess I have to encode my area parameter in some way, but I cant figure out how. Any help is apreciated.
Thanks!
The built-in encoding/decoding does not work, so I suggest you roll your own, like this:
namespace MyProject.Helpers
{
public static class JobNameHelper
{
public static string JobNameEncode(string jobname)
{
return jobname.Replace(":", "---colon---");
}
public static string JobNameDecode(string jobname)
{
return jobname.Replace("---colon---", ":");
}
}
}
Can you not just use
Server.UrlEnconde(item.Name)
Or am I missing something?
In your routing you may have to use Server.UrlDecde as well although I think It should decode for you on request.
Try using the Routing Debugger to see what the url router is getting passed, then you can see where the decoding needs to happen
ASP.NET 3.5 SP1 and earlier have a number of restrictions on which URLs are valid. In ASP.NET 4 most of these issues have been fixes (or are at least customizable via web.config). I think that the colon character, even when encoded, might not be allowed in ASP.NET 3.5 SP1 and earlier due to security concerns. Allowing colons can be a security problem when performing file checks since they are a little-known syntax for NTFS Alternate Data Streams.
I recommend trying to choose a character other than a colon for these purposes. Maybe a comma, semi-colon, or equal sign might work instead?

Resources