Receive WNS push notfication on Windows phone silverlight 8.1 - c#

I have windows phone 8.1 silverlight application where I want to receive Notfications using the new framework, WNS.
I have in the package.appxmanifest: <identity name="4657xxxxxxx" publisher="CN=xxxxx" version="1.0.0.0"/> and added it to the Mobile Service Hub.
For this I have removed old references to MPNS usings, and added the following for WNS:
using Windows.UI.Notifications;
using Windows.Networking.PushNotifications;
using Windows.UI.StartScreen;
This resulted in a new way of getting the channelURI:
public static PushNotificationChannel CurrentChannel { get; private set; }
public async static Task<bool> UploadChannel()
{
bool newChannel = false;
var channel = await Windows.Networking.PushNotifications.PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
var settings = Windows.Storage.ApplicationData.Current.LocalSettings.Values;
object oldChannel;
settings.TryGetValue("channelURI", out oldChannel);
if ((oldChannel as PushNotificationChannel).Uri != CurrentChannel.Uri)
{
settings.Add("channelURI", CurrentChannel);
newChannel = true;
}
try
{
await App.MobileService.GetPush().RegisterNativeAsync(channel.Uri);
}
catch (Exception exception)
{
CurrentChannel.Close();
HandleRegisterException(exception);
}
CurrentChannel.PushNotificationReceived += CurrentChannel_PushNotificationReceived;
return newChannel;
}
private static void HandleRegisterException(Exception exception)
{
MessageBox.Show("error - retry pushchannel");
}
Additionally I removed the ID_CAP_PushNotification based on microsofts update info
I do not get a channel I get an error:
The application does not have the cloud notification capability. (Exception from HRESULT: 0x803E0110)
solution
Searched for the error and found this link, This can be solved as stated in the answer below by accessing package.appxmanifest and enable Internet (Client & Server).
ERROR 2
Then it the UploadChannel()function should work. However the Register API call await App.MobileService.GetPush().RegisterNativeAsync(channel.Uri); results in an error on the server:
Message='Could not register with the 'mpns' platform. Error received: 'Unsupported channel uri: 'https://db3.notify.windows.com . . . .
The error makes sense but I have no idea on how to solve it.
Ekstra
On the server I can subscribe with the URI, and receive notifications. But not on the client. Is this how it should be or?

On Client side:
Ideally, to use WNS, you should remove all references to MPNS from WMAppManifest.xml and add the info provided by Windows Store to your package.appxmanifest.
I understand that you are migrating from WP8 to WP8.1. So in your package.appxmanifest, edit the code so that it looks like this:
<Identity Name="4657xxxxxxx" Publisher="CN=xxxxx" Version="1.0.0.0" />
<mp:PhoneIdentity PhoneProductId="xxxx" PhonePublisherId="00000000-0000-0000-0000-000000000000" />
Note: The 0s in the PhonePublisherId are intentional. I have no idea why, but the app wouldn't work when I did not provide them as such.
You are doing the channel uri request right:
PushNotificationChannel channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
string channelUri = channel.Uri;
You should also set the Internet (Client & Server) capability in Package.appxmanifest to be checked.
To receive notifications on the client, you should intercept the received notification as described here:
https://msdn.microsoft.com/en-us/library/windows/apps/xaml/jj709907.aspx
On Server Side:
The error "Unsupported Channel URI" occurs because you are using the MPNS methods to process the URI in your Azure server.
Refer here for the proper way to do it using WNS: http://azure.microsoft.com/en-us/documentation/articles/mobile-services-dotnet-backend-windows-universal-dotnet-get-started-push/

Adding internetClient capability should resolve this error.
Creating a notification channel results in an WPN_E_CLOUD_INCAPABLE error
Cause: Your app has not declared the Internet capability in its app manifest (package.appxmanifest).
Fix: Ensure that your app manifest has declared Internet capability. In the Visual Studio manifest editor, you will find this option under the Capabilities tab as Internet (Client).

The .NET client SDK for Azure Mobile doesn't currently support using WNS in Windows Phone 8.1 Silverlight applications. You have to use MPN or change your project to a NON-silverlight project type.
Reference (see Elio's response): https://social.msdn.microsoft.com/Forums/azure/en-US/1aa29977-a26d-4054-89b2-c853cbd35c18/wns-for-windows-phone-silverlight-81-apps-with-azure-mobile-services?forum=azuremobile
I'm not sure if they'll update it to support this as Silveright for 8.1 is primarily for backwards compat with existing apps and not many of them were using Mobile Services as it is newer.

In my case, select the ARM platform in my project settings did the trick. I was in "Any CPU".

Related

C# DCOM event binding Unathorized Execption

For a project I am working on I have to interface with a third-party DCOM library. I started with COM interop and this worked just fine locally, then I switched to DCOM and now I keep getting an unauthorized access exception (0x80070005) when trying to bind an event handler to the exposed event. Below is a summary of what I do in code:
public void connect(string server)
{
object dcomObj = null;
var guidB = Guid.Parse("c8c1f57f-0d7c-40b3-b17c-2eac12512006");
var typ = Type.GetTypeFromCLSID(guidB, server, true);
object[] url = { new UrlAttribute(server) };
dcomObj = Activator.CreateInstance(typ, null, url);
user = (RemoteObjectInterface)dcomObj ;
user.getState(); //works fine locally and remotely
user.stateChange += this.User_StateChange; //only works locally
}
I tried setting every permission I could find on the web but I without success. Does anyone have an Idea as to why only the binding of events fails?
RemoteObjectInterface inherits from both the IRemoteObjectEvents and the IRemoteObject. These interface come from the interop ms generated for me when I imported the original dll.
The server is a windows server 2003 VM in virtual box with a bridged network adapter. On the server Everyone is admin (including guest) and limits are set to full access and defaults are set to full access. I am building and running my code on c# .net 4.5.2 from a Windows 10 machine using visual studio 2015.
The sample application that comes with the SDK also fails when I try to use it remotely, the server registers the user but the sample application never realizes that it logged in successfully, I suspect that this behaviour is related to the failing of event binding.
TL;DR I can get and use a remote object but when I try to add an event handler I get an unauthorized exception (0x80070005), why does this happen on event binding? And how do I fix it?
I had the same problem.
For me the issue was I had a AD running on the same device and had to disable the loopback check in the registry. Other solution could be better I assume, but for me the registry hack will do.

Xamarin HttpClient.GetStringAsync not working on Xamarin.Droid

I'm really new in Xamarin development, and I just tried Xamarin.Forms to Develop Android & iOS App with shared Code, and what I'm trying to do here is to get data from API with Plugin.RestClient NuGet package.
Here's my MainViewModel.
public MainViewModel(){
InitializeDataAsync();
}
public async Task InitializeDataAsync(){
var employeeServices = new EmployeeServices();
EmployeesList = await employeeServices.getEmployeesAsync();
}
And here's my Services
public async Task<List<Employee>> getEmployeesAsync(){
RestClient<Employee> restClient = new RestClient<Employee>();
var employeeList = await restClient.GetAsync("http://localhost:3000/employee");
return employeeList;
}
And this is my RestClient
public async Task<List<T>> GetAsync(string WebServiceUrl){
var httpClient = new HttpClient();
var json = await httpClient.GetStringAsync(WebServiceUrl);
Debug.WriteLine(WebServiceUrl);
Debug.WriteLine(json);
var taskModels = JsonConvert.DeserializeObject<List<T>>(json);
return taskModels;
}
The code works fine on my iPhone Emulator. I can see my Debug for the url and json response. But on my Android Emulator there's nothing on the list. I can't even find my Debug for url and json response, I already checked my Application Output and my Device Log (I used Xamarin Studio for Mac btw).
I also already add internet permission on my Android Manifest.
What should I do?
You can only access localhost on your local machine. You need to change localhost to the IP address of the machine on which your api is hosted.
So the api endpoint for
http://localhost:3000/employee
should be something like
http://192.168.0.5:3000/employee
If you are getting a timed out error then it's probably because "localhost" to the Android OS means the phone itself, which is probably not where you're not running the web server. There are some special IP addresses you can use while testing with Android emulators to reach the host OS:
The Google emulators allow you to reach the host OS from 10.0.2.2.
The Microsoft Android emulator allows you to reach the host OS from 169.254.80.80.
You could try changing your URL based on the type of emulator you are using. Alternatively, you can plugin your workstations IP address instead, but this is less desirable because it can change.
If this doesn't allow you to reach the server then you may consider looking at any firewalls to see if your traffic is being blocked.

LoadAsync doesn't work in windows phone 8 with WCF data service

My friend and I just created a WCF data service and would like to consume it with a Windows Phone 8 client. For the WCF data service part, the OData is proved to work with a windows form project which an do CRUD for the database.
So to get WP8 consume WCF Data Service, we followed the tutorial step by step and downloaded the sample code on the MSDN tutorial
http://msdn.microsoft.com/en-us/library/windows/apps/hh394007(v=vs.105).aspx
However,the examples don't work.There's no display of data from database on the phone.
We find the
Customers.LoadAsync(Query)
under function public void LoadData in MainViewModel Class doesn't load the XML data in :http://services.odata.org/Northwind/Northwind.svc/Customers().
public void LoadData()
        {
            // Instantiate the context and binding collection.
            _context = new NorthwindEntities(_rootUri);
            Customers = new DataServiceCollection<Customer>(_context);
            // Specify an OData query that returns all customers.
            var query = from cust in _context.Customers
                        select cust;
            // Load the customer data.
            Customers.LoadAsync(query);
        }
We modified the function OnCustomerLoaded to display the error message if there's any:
private void OnCustomersLoaded(object sender, LoadCompletedEventArgs e)
{
if (e.Error != null)
{
MessageBox.Show(e.Error.Message+e.Error.InnerException);
}
// Make sure that we load all pages of the Customers feed.
if (Staffs.Continuation != null)
{
Staffs.LoadNextPartialSetAsync();
}
//MessageBox.Show(Staffs.ToString());
IsDataLoaded = true;
}
We get the following error:
We are using VS2012 premium, created Windows Phone 8 with data bind project, using OData 5.0.0.
We have to admit that this error may not be the root cause of the problem, but we can't figure it out since we are new to it. We appreciate if anyone can point out what shall we change to make the example work if this is not the error root.
Thanks so much!!
This looks like your app does not have access to the internet, it probably caused by setting issue of your WP Emulator.
You can first try the built-in internet explorer, and check whether it has internet access. If not, you can go to the Hyper-V configuration page, and try change the network adapter settings, or refer to the following page for detail.

How to consume java REST webservice in windows phone 8?

I am trying to consume Java REST Webservice in windows phone 8.But it is always giving 404 (page not found) exception (system.net.http.httpexception).That means not able to connect to webservice.
Following is the client code which i used for consuming webservice.
try
{
HttpClient http = new HttpClient();
String result = await http.GetStringAsync("http://192.168.0.56:8078/sample/page/name");
MessageBox.Show(result);
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
Please help.Thanks in advance.
Issue solved.Emulator was not able to connect to internet,which was the problem.I tried in windows phone and its working fine.Thanks #akshay2000.
Check your Network Adapters and Verify that there are Hyper-V in their names or 'v' prefixes on the Adapter names, if there are you should check if they are enabled, and enable them if disabled.
If you have nothing like that you should repair the sdk, and that will fix the issue.

StreamSocketListener Access denied

What I am wanting to do is create a SocketStreamListener and connect to it (on localhost). Then connect to it and send it a message. Very simple stuff and it's all done here in an official demo but I want to understand it and use this logic in my own application.
The Problem
I have created a new Windows Metro C# application project and have this code to create a listener on my MainPage:
private void Button_Click(object sender, RoutedEventArgs e)
{
StreamSocketListener listener = new StreamSocketListener();
greetingOutput.Text = "Hello, " + nameInput.Text + "!";
}
but I get this error:
An exception of type 'System.UnauthorizedAccessException' occurred in
HelloWorld.exe but was not handled in user code
WinRT information: At least one of either InternetClientServer or
PrivateNetworkClientServer capabilities is required to listen for or
receive traffic
Additional information: Access is denied.
If there is a handler for this exception, the program may be safely
continued.
The same code works in the official demo though.
What am I missing?
What am I doing wrong?
You need to configure your application to require one or both of the necessary capabilities depending on your needs:
internetClientServer
Your Internet connection, including incoming unsolicited connections from the Internet – the app can send information to or from your computer through a firewall. You do not need to declare internetClient if this capability is declared.
privateNetworkClientServer
A home or work network – the app can send information to or from your computer and other computers on the same network.
(From the documentation at http://msdn.microsoft.com/en-us/library/windows/apps/br211423.aspx)
Also see this article for more information on how capabilities works: http://msdn.microsoft.com/en-us/library/windows/apps/hh464936.aspx
Internet and public networks
The internetClient capability provides outbound access to the Internet and public networks through the firewall. Almost all web apps use this capability. The internetClientServer capability provides inbound and outbound access to the Internet and public networks through the firewall.
Home and work networks
The privateNetworkClientServer capability provides inbound and outbound access to home and work networks through the firewall. This capability is typically used for games that communicate across the local area network (LAN), and for apps that share data across a variety of local devices. If your app specifies musicLibrary, picturesLibrary, or videosLibrary, you don't need to use this capability to access the corresponding library in a Home Group.
You need to declare which capabilities your app requires (and therefore has access to)
in your package manifest. Here's a step by step guide on how to do that: http://msdn.microsoft.com/en-us/library/windows/apps/br211477.aspx
You can use the Manifest Designer in Visual Studio to edit these capabilities.
Just locate and open the file in your solution named package.appxmanifest and the Manifest Designer should open.
Select the capabilities tab and the network related capabilities your app requires and you should be good to go.
Link to the documentation about the App Manifest Designer: http://msdn.microsoft.com/en-us/library/windows/apps/br230259(v=vs.110).aspx
Regarding the last paragraph
If there is a handler for this exception, the program may be safely continued.
It is simply saying that you may wrap your code using the StreamSocketListener in a try-catch block. This is a good thing if you want to handle the missing capabilities gracefully inside your application:
private void Button_Click(object sender, RoutedEventArgs e)
{
try
{
StreamSocketListener listener = new StreamSocketListener();
greetingOutput.Text = "Hello, " + nameInput.Text + "!";
}
catch(UnauthorizedAccessException exc)
{
// Act on the missing capability. Log it and/or warn the user.
}
}

Categories