UWP programming - Can't get SMS store - c#

I'm the new one in C# and UWP development and I'm trying to create an app for win-mobile 10.
One of the tasks of this app is reading SMS messages.
On one of my xaml pages I use this code:
public sealed partial class TileSettings : Page
{
public TileSettings()
{
this.InitializeComponent();
GetMessages();
}
public async Task GetMessages()
{
ChatMessageStore store = await ChatMessageManager.RequestStoreAsync();
}
}
Problem appears when I call the ChatMessageManager.RequestStoreAsync() function. The function is called but never returns any value and never exits from this function.
I have not a special permissions of Microsoft
as a developer. Can I use this function?
I'm trying to use Google and Stackoverflow search and found code like this with RequestStoreAsync() function, but it seems that no one ever faced this particular problem
May be I have logical error in the code and don't know how to use async functions in c# :)
Waiting for your comments about this behavior.
Best Regards.

You have to need Company account. Please check it out below URL what are the benefits
https://msdn.microsoft.com/windows/uwp/packaging/app-capability-declarations

I found a problem.
There is UnauthorizedAccessException in this function.
I coudn't see this exception cause call of this task is incorrect.
I try use this code:
public TileSettings()
{
this.InitializeComponent();
cts = new CancellationTokenSource();
Task.Run(() => GetMessages(), cts.Token);
}
private async void GetMessages()
{
ChatMessageStore store;
store = await ChatMessageManager.RequestStoreAsync();
var List = store.GetMessageReader();
}
and caught this exception.
Do I need a special permissions to use this function to get sms messages?

Related

How to wait for EventHandler being triggered in UWP app?

I made a simple app in UWP and I'm having trouble with the EventHandlers not being triggered... I made the same app in Core.NET and it works great if I add "Console.ReadLine()" at the end of the main function so it seems like the thread of the main function dies before EventHandlers can be triggered.
Is there a way, in UWP, for the instance to stay alive a while (ie: timeout) to give a chance for the EventHandlers to be triggered.
Note: This is an example of the problem; the real context will happen in the reception of a web request.
Here's the code:
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
test();
}
private async void test() {
Client DiscoverClient;
DiscoverClient = new Client();
DiscoverClient.DeviceHandler += Client_DeviceHandler;
await DiscoverClient.DiscoverAsync();
}
static private void Client_DeviceHandler(object sender, BroadlinkDevice device)
{
int x = 0;
}
}
Instead of using
await DiscoverClient.DiscoverAsync()
you could use
_ = DiscoverClient.DiscoverAsync().Result
This enforces test() to wait for DiscoverAsync() to return.
.Result may only be used if the return type is not void, so you could just let DiscoverAsync() return a boolean when it is finished. The discard is then used to have an assignment that makes the constructor block until DiscoverAsync() is done.
I tried to integrate the library mentioned in your comment into my UWP app, it will throw 'Access Denied' exption when call method GetActiveTcpConnections(line 60 in Network.cs). Since that the event Client_DeviceHandler will not be triggerred. Please see this issue(issue#24369) in github.
This document shows how to use socket in UWP. You may refer the server sample to modify or implement the feature.
https://learn.microsoft.com/en-us/windows/uwp/networking/sockets
I tryed multiple ways found on the internet (some using sockets) but I did'nt find a working solution...
I ended up using a workaround: looping through ip searching for the device's hostname. Since the IP only changes when my router is restarded, the discovery process is rarely needed so even if it's a little on the heavy side, it's quite ok for me :-)
Thanks for you help guys

Task<bool> error in Xamarin.Forms make program stop

i recently started working with Xamarin and my level of noob its very high right now, i will resume my problem.
I am developing an app that can reach a WebService to send and import data from DB, right now i am currently working on a login page and i have a method so I can check if the user exits in the data base, when i added the service reference in Xamarin all the methods turned into async, and because of that i need to use tasks.
So, i implemented the Tasks and it worked perfectly but i had one problem i couldnĀ“t send the response of the server back, i did some research and found that tasks methods dont have returns and for that i could use Task < TResult>, and i implemented in this way:
CheckUser Method in Service
serclient = new Service.WebService1SoapClient()
public async Task<bool> CheckUser(string UserName)
{
var resp = await serClient.CheckUserAsync(UserName);
bool result = resp.Body.CheckUserResult;
return result;
}
gesTab.CheckUser Is the method to check the database.
public bool CheckUser(string username)
{
bool e = gestTab.CheckUser(username);
return e;
}
When the program is runnig just stops in the first line of that function and i cant understand why.
I already tried it by using pointers by keeping getting that pointers must only be used in unsafe context.
If i cant do it this way, what can i do for return the data?
Thank you all.
You must await the method which retrieves data from db or etc. like this ,
public async Task<bool> CheckUser(string username)
{
bool e = await gestTab.CheckUser(username);
return e;
}
Since your method making starting async request but not awaiting response, your application crashes unexpectedly.

RavenDb LoadAsync Not Returning and Not Throwing Exceptions

I am trying to load a document out of RavenDb via a WebAPI call. When I open an async IDocumentSession and call LoadAsync, I get no exception or result, and the thread exits instantly with no error code.
I was able to bypass all the structure of my API and reproduce the error.
Here is the code that will not work:
public IHttpActionResult GetMyObject(long id)
{
try
{
var session = RavenDbStoreHolderSingleton.Store.OpenAsyncSession();
var myObject= session.LoadAsync<MyObject>("MyObject/1").Result;
return Ok(myObject);
}
catch (Exception e)
{
return InternalServerError(e);
}
}
I simply hard coded the object's Id to 1 for testing, but calling the function for an object that doesn't exist (such as "MyObject/1") has the same result.
However, this code works:
public async Task<IHttpActionResult> GetMyObject(long id)
{
try
{
var session = RavenDbStoreHolderSingleton.Store.OpenAsyncSession();
var myObject= await session.LoadAsync<MyObject>("MyObject/1");
return Ok(myObject);
}
catch (Exception e)
{
return InternalServerError(e);
}
}
Things I tried/fiddled with:
Changing the exceptions that are caught in debugging
Carefully monitoring Raven Studio to see if I could find any problems (I didn't, but I'm not sure I was looking in the right places)
Running the API without the debugger attached to see if the error occurred or if something showed up in Raven Studio (no changes)
So I guess I have stumbled on a "fix", but can someone explain why one of these would fail in such an odd way while the other one would work perfectly fine?
In the real application, the API call did not have the async/await pair, but the code that was making the call was actually using async/await.
Here is the repository class that was failing which caused me to look into this issue:
public async Task<MyObject> Load(string id)
{
return await _session.LoadAsync<MyObject>(id);
}
The first part that is failing is as per design, for ASP.Net async call, you are blocking the Synchronization context, when you call the Result on a Task returned and same Synchronization context is required for call to return the data. Check out the following link by Stephen Cleary, where the same mechanism is explained in detail.
Second part works since that is correct way of using it and it's not getting into the deadlock anymore. First part can only work if you are using the Console application, which doesn't have a synchronization context to block, even other UI like winforms will have a similar issue and need to use the use the Second part of the code

LiveAuthClient InitializeAsync hangs

I am having trouble with a demo from msdn
The demo
On the method updateUserName:
public static async Task updateUserName(TextBlock userName, Boolean signIn)
{
try
{
// Open Live Connect SDK client.
LiveAuthClient LCAuth = new LiveAuthClient();
LiveLoginResult LCLoginResult = await LCAuth.InitializeAsync();
try
{
//this is never reached
LiveLoginResult loginResult = null;
if (signIn)
......
the code hangs at ht InitialuzeAsync() method and never enters the try statement. Can someone who has used the live SDK please tell me what migh be wrong? The code is a direct copy-paste from the demo and the live SDK was installed via NuGet on VS2012.
I predict that you are calling Task.Wait or Task<T>.Result somewhere further up your call stack. As I describe on my blog, you are causing a deadlock because the await is attempting to resume on the UI thread.
The correct solution is to use await "all the way", which is one of the best practices I describe in my article. If you have a situation where you think you "can't" use await, then take a look at my async/OOP blog series, which describes various code patterns for async code, most notably constructors and properties.
Seems you have to associate your app with the store to use this feature, or else it hangs. After associating it, everything started working.

Correct way to get the CoreDispatcher in a Windows Store app

I'm building a Windows Store app, and I have some code that needs to be posted to the UI thread.
For that, i'd like to retrieve the CoreDispatcher and use it to post the code.
It seems that there are a few ways to do so:
// First way
Windows.ApplicationModel.Core.CoreApplication.GetCurrentView().CoreWindow.Dispatcher;
// Second way
Window.Current.Dispatcher;
I wonder which one is correct? or if both are equivalent?
This is the preferred way:
Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
// Your UI update code goes here!
});
The advantage this has is that it gets the main CoreApplicationView and so is always available. More details here.
There are two alternatives which you could use.
First alternative
Windows.ApplicationModel.Core.CoreApplication.GetCurrentView().CoreWindow.Dispatcher
This gets the active view for the app, but this will give you null, if no views has been activated. More details here.
Second alternative
Window.Current.Dispatcher
This solution will not work when it's called from another thread as it returns null instead of the UI Dispatcher. More details here.
For anyone using C++/CX
Windows::ApplicationModel::Core::CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(
CoreDispatcherPriority::Normal,
ref new Windows::UI::Core::DispatchedHandler([this]()
{
// do stuff
}));
await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
CoreDispatcherPriority.Normal,
() => { // your code should be here});
While this is an old thread, I wanted to draw attention to a possible issue developers may run across which impacted me and made it extremely difficult to debug in large UWP apps. In my case, I refactored the following code from the suggestions above back in 2014 but would occasionally be plagued with the occasional app freezes that were random in nature.
public static class DispatcherHelper
{
public static Task RunOnUIThreadAsync(Action action)
{
return RunOnUIThreadAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, action);
}
public static async Task RunOnUIThreadAsync(Windows.UI.Core.CoreDispatcherPriority priority, Action action)
{
try
{
await returnDispatcher().RunAsync(priority, () =>
{
action();
});
}
catch (Exception ex)
{
var noawait = ExceptionHandler.HandleException(ex, false);
}
}
private static Windows.UI.Core.CoreDispatcher returnDispatcher()
{
return (Windows.UI.Xaml.Window.Current == null) ?
CoreApplication.MainView.CoreWindow.Dispatcher :
CoreApplication.GetCurrentView().CoreWindow.Dispatcher;
}
}
From the above, I had used a static class to allow the calling of the Dispatcher through-out the application - allowing for a single call. For 95% of the time, everything was fine even through QA regression but clients would report an issue every now and then. The solution was to include the call below, not using a static call in the actual pages.
await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
});
This is not the case when I need to ensure the UI Thread was called from App.xaml.cs or my Singleton NavigationService which handled pushing/popping on to the stack. The dispatcher apparently was losing track of which UI Thread was called, since each page has it's own UI thread, when the stack had a variety of Messages triggering from the MessageBus.
Hope this helps others that may be impacted and it is also where I think each platform would do a service to their developers by publishing a complete project covering the best practices.
Actually, I would propose something in the line of this:
return (Window.Current == null) ?
CoreApplication.MainView.CoreWindow.Dispatcher :
CoreApplication.GetCurrentView().CoreWindow.Dispatcher
That way, should you have openend another View/Window, you won't get the Dispatchers confused...
This little gem checks whether there is even a Window. If none, use the MainView's Dispatcher. If there is a view, use that one's Dispatcher.

Categories

Resources