Windows Phone 8 Server Connection - windows-phone-8

I am want to make a 'hello world' application whereby I can send some data/make a request to a server or a WCF service. A simple query, save, delete etc application. I am targeting this learning app to be on the Windows Phone 8 platform.
I have done some work in WCF and RavenDB in the past but, not sure what to do in this situation.
Can someone please give me some tips/tutorials on how to achieve this please?

I used WCF to create a Service. The Service contained an Interface which were operations that were exposed and they were implemented in a different file. I then created a windows phone app and added the Service Reference by providing a URL to the service. The code to query the service was simply:
private void button1_Click(object sender, RoutedEventArgs e)
{
ServiceReference1.Service1Client myClient = new Service1Client();
myClient.AddNumbersCompleted += new EventHandler<AddNumbersCompletedEventArgs>(myClient_AddNumbersCompleted);
myClient.AddNumbersAsync(textBox1.Text, textBox2.Text);
}
void myClient_AddNumbersCompleted(object sender, AddNumbersCompletedEventArgs e)
{
textBlock1.Text = "Answer:" + e.Result.ToString();
}

Related

Azure Mobile Services authentication not working with Windows Phone 8.1 Universal app

I'm adding Azure Mobile Services authentication to a Universal Windows project. It's all set up and working properly on the server and in the Windows Store version of the app, however I can't get it to work with the Windows Phone 8.1 version of the app. I actually have two different apps that I've been working on with the same problem, so I created a test app based strictly on the steps outlined in this article. The sample app has one button on the UI that will attempt authenticate the user with Twitter when pressed.
The flow that I am seeing from the UI is:
Press the button
Screen goes black for a moment
Screen displays "Resuming..." with a spinner
InvalidOperationException gets caught
The exception details:
System.InvalidOperationException was caught
HResult=-2146233079
Message=Authentication was cancelled by the user.
Source=mscorlib
StackTrace:
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at Microsoft.WindowsAzure.MobileServices.MobileServiceAuthentication.<LoginAsync>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at MobileAuthTest.MainPage.<AuthenticateAsync>d__3.MoveNext()
InnerException:
The code I am using is copied almost verbatim from the article, but I'll paste it here too:
private async void Button_Click(object sender, RoutedEventArgs e)
{
await this.AuthenticateAsync();
}
// Define a method that performs the authentication process
// using a Twitter sign-in.
private async Task AuthenticateAsync()
{
while (user == null)
{
string message;
try
{
// Change 'MobileService' to the name of your MobileServiceClient instance.
// Sign-in using Twitter authentication.
user = await App.mobileService
.LoginAsync(MobileServiceAuthenticationProvider.Twitter);
message =
string.Format("You are now signed in - {0}", user.UserId);
}
catch (InvalidOperationException)
{
message = "You must log in. Login Required";
}
var dialog = new MessageDialog(message);
dialog.Commands.Add(new UICommand("OK"));
await dialog.ShowAsync();
}
}
And this override is in App.xaml.cs:
protected override void OnActivated(IActivatedEventArgs args)
{
// Windows Phone 8.1 requires you to handle the respose from the WebAuthenticationBroker.
#if WINDOWS_PHONE_APP
if (args.Kind == ActivationKind.WebAuthenticationBrokerContinuation)
{
// Completes the sign-in process started by LoginAsync.
// Change 'MobileService' to the name of your MobileServiceClient instance.
mobileService.LoginComplete(args as WebAuthenticationBrokerContinuationEventArgs);
}
#endif
base.OnActivated(args);
}
My testing is all on a real Windows Phone 8.1 device (Nokia 920 with 8.1 update).
It's also worth pointing out that the project I'm currently trying to get this to work in is also using Xamarin.Forms for Android, iOS and Windows Phone (I wanted a comparison between Xamarin.Forms for Windows Phone and Universal apps for Windows Phone). All of the apps work, EXCEPT for the two Windows Phone apps. The Xamarin.Forms Windows Phone app is a Windows Phone Silverlight 8.1 app which acts the same as described above for the Universal WP, but fails with the error, "Authentication failed with HTTP response code 0."
I've searched around and haven't found any other cases of people encountering the same issue I am. Is there something I need to do that is so simple nobody feels the need to say it in writing?
Well, it turns out that the issue I am seeing may just be my device. I sent the sample app to another dev for testing and he had no issues. I also was able to successfully log in with both the sample app and the real app on the simulator. That isn't exactly a thorough test sample, but it's enough for me to stop banging my head on this desk.

How to connect to remote MySQL database from Windows Phone 8 application?

I'm developing application for windows phone 8 and I need to get user data from remote MySQL database. This database is also used by the web-application.
What is the solution for this problem? Where I can read some information about using remote data storages with windows phone 8?
You can use the restsharp client for windows phone. Its fully documented and a nuget install is also available. heres the link http://restsharp.org/
A better and simpler way is to perform all the db operations in server side code (like php) and the information can be passed to the php file using a query string and the reverse by echo statement.
var webclient = new WebClient();
webclient.OpenReadAsync(new Uri("http://website.com/filename.php?name=" + myname.Text );
webclient.OpenReadCompleted += new OpenReadCompletedEventHandler(handler);
private void opener(object sender, OpenReadCompletedEventArgs e)
{
// throw new NotImplementedException();
using (var reader = new StreamReader(e.Result))
{
string response = reader.ReadLine();
MessageBox.Show(response);
}
}

Data session info on Windows Phone 8

I'm building an app and I would like to track my device data session information.
For example duration, received bytes, sent bytes, bearer, access point, local IP address, protocol when connected using wifi, 3g, gprs, cell network.
If I can get all would be perfect, but getting 1 is more than enough.
I hope someone could show me some solutions or possibles APIs, if possible.
Thanks a lot in advance.
There are 3 namespaces in WP8 that provide network information: System.Net.NetworkInformation, Microsoft.Phone.Net.NetworkInformation and the new WP8 WinPRT namespace Windows.Networking.Connectivity.
While DataUsage/DataPlan APIs are available in the new WP8 namespace, they aren't supported on WP8 and only exist for Win8 API compatibility. You can use either the new WP8 APIs or WP7 APIs to enumerate over all connected interface type and check if they're WiFi/Ethernet/3G/etc:
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
foreach (var network in new NetworkInterfaceList())
{
Debug.WriteLine(network.InterfaceType);
}
}

javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated

Simple codes
public class Demo {
public static void main(String[] args) {
HttpClient httpclient = new DefaultHttpClient();
try {
HttpGet httpget = new HttpGet("https://banweb.cityu.edu.hk/");
HttpResponse response = httpclient.execute(httpget);
} catch (Exception e) {
e.printStackTrace();
}
}
}
I have 2 desktops (A and B), 2 laptops (A and B), 3 android devices (A, B and C) and 3 android emulators (SDK v2.1, v4.0 and v4.03). When above code is run in desktop A, android emulator v4.0 and v4.0.3, it throws "javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated". But the code works fine in other devices and emulators.
Can anyone tell me why the same code shows different results in different machines?
Your help is appreciated.
See this message post: SSL "Peer Not Authenticated" error with HttpClient 4.1
I think the issue is related to whether the machine/environment that you are using has access to the system wide root certificates. If the OS is newer it may recognize ( and verify/trust?) your signed certificate. However, if the JRE/JDK is not aware of the root CA store then it may not work.
I have a basic app that is working in Netbeans but not after I deploy the JavaFX project. I have added my root certificate to the keystore but it is still not working.
It may be that one of the machines is behind a proxy and the other is not?

Execute exe-file from html-page?

I want to launch a local exe-file (without saving it to another location first) upon clicking on a link on a local html file.
It either needs to work in IE, Firefox, Chrome or Opera, I don't care. It's just for a presentation tomorrow.
It's simply not possible. If it was, it would be considered a security flaw and fixed. On Firefox within hours, on IE within some months.
UPDATE: You could try registering your custom protocol: http://openwinforms.com/run_exe_from_javascript.html
But I believe the browser will still prompt you whether you want to run the app.
I want to share my experience.
The accepted response says that it is not possible but it is quite possible indirectly.
If you want to execute an exe on a pc, it means that you have acces on this pc and you can install your exe on that machine.
In my case, I had to take a 3D scan from a 3D scanner via a web application. It seemed impossible at the beginning.
After lots of research, I found that we can send socket messages via javascript.
It means that if we had an application which listens a specific port, it can communicate with a website.
Let's explain how I did this.
In my web application, I created a javascript method like this :
function openCapron3DScanner(foot) {
$("#div-wait").show();
//Creates a web socket pointed to local and the port 21000
var ws = new WebSocket("ws://127.0.0.1:21000");
ws.onopen = function () {
//Sends the socket message to the application which listens the port 21000
ws.send(foot + "-" + #ProjectHelper.CurrentProject.Proj_ID);
};
ws.onerror = function myfunction() {
$("#div-wait").hide();
alert("Erreur connection scanner.");
}
ws.onmessage = function (evt) {
//Receives the message and do something...
var received_msg = evt.data;
if (received_msg == "ErrorScan") {
alert("Erreur scan.");
}
else {
refreshCurrentProject();
}
};
ws.onclose = function () {
$("#div-wait").hide();
};
};
And I created a windows forms application who listens the localhost and port 21000.
This application is hidden, only shown in icon tray.
The only thing to do is to add the application on windows startup via code on the first load to assure that the next restart of windows it will be executed and listen the port.
private static WebSocketServer wsServer;
static WebSocketSession LastSession;
private void Form1_Load(object sender, EventArgs e)
{
wsServer = new WebSocketServer();
int port = 21000;
wsServer.Setup(port);
wsServer.NewMessageReceived += WsServer_NewMessageReceived;
wsServer.Start();
}
private static void WsServer_NewMessageReceived(WebSocketSession session, string value)
{
if (value.StartsWith("ScanComplete-"))
{
//If the scan is ok, uploads the result to the server via a webservice and updates the database.
UploadImage(value);
//Sends a confirmation answer to the web page to make it refresh itself and show the result.
if (LastMacSession != null)
LastMacSession.Send("ScanComplete");
}
else if (value == "ErrorScan")
{
//If the C++ application sends an error message
if (LastMacSession != null)
LastMacSession.Send("ErrorScan");
}
else//call the 3D Scanner from the web page
{
LastSession = session;//Keeps in memory the last session to be able to answer via a socket message
//Calls the C++ exe with parameters to save the scan in the related folder.
//In could be don in this same application if I had a solution to consume the scanner in C#.
var proc = System.Diagnostics.Process.Start(#"C:\Program Files\MyProjectFolder\MyScannerAppC++.exe", projectID + " " + param);
}
}
I hope it will help.
Use System.Diagnostics.Process.Start() method.
protected void LinkButton1_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("notepad.exe");
}
You'll have to use C#, but since that's on your post, it should work. You'll also need the full path, if the file is not in your environment path that's loaded in memory.
For a 'regular link' you'd still need to place this in an ASPX page.....
Click me
We're getting really fugly now though.
You can't run an exe file on a website. (First, if it's a Linux server, exe files won't run on it and second, if you're on a Windows server, your host would kill the program immediately. And probably terminate your account.)
That link (assuming it was Play Now!) will just allow your user to download the file. (C:\Program Files\World of Warcraft\ exists on your computer, but it doesn't exist on the web server.)
You could setup a custom protocol on your local OS, if it's Windows, in regedit.
Check out this and this.
Then you create a simple HTML page, and place a link, something like this :
Start!
Given that you registered your custom "presentation" protocol, and configured it correctly in the registry, the application should launch when you click that link.