Read text from an URL on Codename One - url

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 :)

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.

Using DataConnectionDialog

When I am attempting to use the DataConnectionDialog from NuGet (version 1.2), I receive the Advanced Settings dialog for setting up the Database Connection. Is there some Setting I have missed or additional library to retreive?
Code:
using System;
using Microsoft.Data.ConnectionUI;
DataConnectionDialog dcd = new DataConnectionDialog();
DataSource.AddStandardDataSources(dcd);
dcd.SelectedDataSource = DataSource.SqlDataSource;
dcd.SelectedDataProvider = DataProvider.SqlDataProvider;
DataConnectionDialog.Show(dcd);
Output:
What I want (this comes from the datasource wizard in Visual Studio Community 2015):
I happened to stumble on the same issue. From my main form, I called an async method using Task.Factory.StartNew. This method tries to open the Data Connection Dialog but it would show the Advance Settings dialog box instead.
During troubleshooting, I replaced the DataConnectionDialog with a OpenFileDialog and this gave me a ThreadStateException which pointed me towards the solution.
To solve it, I had to put the code in a separate function, e.g. AskConnectionString and call it using Control.Invoke.
e.g.
public void btnConnString_Click(object sender, EventArgs e)
{
_connectionString = (string)this.Invoke(AskConnectionString);
}
public string AskConnectionString()
{
DataConnectionDialog dcd = new DataConnectionDialog();
DataSource.AddStandardDataSources(dcd);
dcd.SelectedDataSource = DataSource.SqlDataSource;
dcd.SelectedDataProvider = DataProvider.SqlDataProvider;
DataConnectionDialog.Show(dcd);
return dcd.ConnectionString;
}

ModelState.IsValid is false - But Which One - Easy Way

In ASP.NET MVC, when we call a post action with some data, we check ModelState and in case some validation error, it would be falst. For a big Enter User Information form, it is annoying to expand each Value and look at the count to see which Key (9 in attached example image) has validation error. Wondering if someone knows an easy way to figure out which element is causing validation error.
In VS2015+, you can use LINQ in the Immediate Window, which means you can just run the following:
ModelState.SelectMany(
x => x.Value.Errors,
(state, error) => $"{state.Key}: {error.ErrorMessage}"
)
I propose to write a method:
namespace System.Web
{
using Mvc;
public static class ModelStateExtensions
{
public static Tuple<string, string> GetFirstError(this ModelStateDictionary modelState)
{
if (modelState.IsValid)
{
return null;
}
foreach (var key in modelState.Keys)
{
if (modelState[key].Errors.Count != 0)
{
return new Tuple<string, string>(key, modelState[key].Errors[0].ErrorMessage);
}
}
return null;
}
}
}
Then during debugging open Immediate Window and enter:
ModelState.GetFirstError()
Sounds like you're looking for debugger enhancements. I recently came across this product in the visual studio gallery.
http://visualstudiogallery.msdn.microsoft.com/16acdc63-c4f1-43a7-866a-67ff7022a0ac
I have no affiliation with them, and haven't used it. It's also a trial version and have no idea how much it costs for the full thing.
If you're more focused on the debugger side of things, have a go with the trial copy of OzCode. It enhances the Visual Studio IDE by replacing the usual debugging tooltip with it's own, more powerful, debugging tooltip. It's hard to epxlain with words, check out their website, they have a gallery of features on there.
I've been playing around with the beta for a few weeks, and it's proved a very valuable tool. You can query against data in the debugger using OzCode. For example, you could query items in the ModelState by filtering against the Values collection.

Code cannot find a line on a website

I've been trying to find a line and print it out on this website: http://www.easports.com/player-hub/360/Its+McDoom
Right now it prints out everything on the website, but I cannot find the line I am looking for. I am trying to print out "H2h Skill Points: 1053", but I cannot find anything like that in the console.
I only really want it to print that 1 line, not the whole thing, but I can't even find it.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class ElectronicArtsStatHub {
/**
* #param args
*/
public static void main (String[] args) throws Exception{
URL oracle = new URL("http://www.easports.com/player-hub/360/Its+McDoom");
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
in.close();
}
}
The first problem is that the information your trying to find isn't actually in the data you are currently outputting.
When you open the page in your browser you get the main page elements but then your browser then runs some Javascript code which presumably uses AJAX to get the stats and fill in the table.
The URLConnection receives the same data that your browser initially does and does not execute the Javascript so if you check your output that data your looking for isn't actually there at all.
Possible solutions include finding a different source for this data or executing the Javascript in Java possibly by using HTMLUnit
There may be some helpful infomation on this related question

FileConnection on Storm 9550

I'm using the following code to create a file and write data into it:
fileName = "file:///store/home/user/myapp/groups.xml";
try {
fc = (FileConnection) Connector.open(fileName, Connector.READ_WRITE);
if (!fc.exists())
fc.create();
os = fc.openDataOutputStream();
String XMLString = "blablabla";
byte[] FinalXML = XMLString.getBytes();
os.write(FinalXML);
os.close();
fc.close();
} catch (IOException e) {
Dialog.alert(e.getMessage());
}
It works good on my bb 9700 with OS6 and on 9700 simulator. But it doesn't work on 9550 device and simulator. I'm getting IOException. The message says
File not found
Does anybody have some voodoo magic that will help me?
Looks like the folder "file:///store/home/user/myapp/" does not exist yet. Just check for its presence first, if not present - create and then go on with rest of your code.
BTW, the "file:///store/home/user/" path is valid for all mentioned devices.
IOExeption go if the firewall disallows a connection that is not btspp or comm. so you have to add permission for your program such as FILE_API ..... you can read book : Advance BB dev to do this

Resources