How To solve the following error in windows phone 8 application? - c#

I'm developing windows phone 8 application.
I need to get user current location Details.
I try with following code taken from MSDN
C# :
1 private void OneShotLocationButton_Click(object sender, RoutedEventArgs e)
2 {if ((bool)IsolatedStorageSettings.ApplicationSettings["LocationConsent"] != true)
3 {
4 return;
5 }
6 Geolocator geolocator = new Geolocator();
7 geolocator.DesiredAccuracyInMeters = 50;
8 try
9 {
10 Geoposition geoposition = await geolocator.GetGeopositionAsync(
maximumAge: TimeSpan.FromMinutes(5),
timeout: TimeSpan.FromSeconds(10)
);
LatitudeTextBlock.Text = geoposition.Coordinate.Latitude.ToString("0.00");
LongitudeTextBlock.Text = geoposition.Coordinate.Longitude.ToString("0.00");
}
catch (Exception ex)
{
if ((uint)ex.HResult == 0x80004004)
{
// the application does not have the right capability or the location master switch is off
StatusTextBlock.Text = "location is disabled in phone settings.";
}
//else
{
// something else happened acquring the location
}
}
}
I Got error in line number 10.
The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
I 'm new to windows phone application. now only i start the learn basic in WP8 .
Plz tell how to solve this ...

In your code you have used await geolocator.GetGeopositionAsync() now you can only use await with async methods.
so what you have to do is whenever you used async method just declare the method aysnc
like:private async void OneShotLocationButton_Click(object sender, RoutedEventArgs e)
instead of private void OneShotLocationButton_Click(object sender, RoutedEventArgs e)

Follow the error instruction. Change
private void OneShotLocationButton_Click
to
private async void OneShotLocationButton_Click

Related

Multiple instances of same app throws StackOverflow Exception

In my Solution I've 3 main projects (Server, Client and Special Client). In my test environment, (1) Special Client just displays a count of Buy/Sell/Executed orders every 5 seconds, (2) Client submits Buy/Sell order and (3) Server processes the order client submitted and send back to Client and Special Client. If I launch all 3 Apps by hitting Ctrl+F5 and let Client submit an order every 10 millisecond, all those app work without any problem and on Windows Task Manager I've observed that the memory usage by Client fluctuates between 115MB and 320MB, none of those crash (I've tested for long time).
If I launch 2 more Client from ../Client/bin/Debug/... (3 instances of Client altogether, 1 Special Client and 1 Server) and let each Client submit 20 orders a second, it also works fine (not sure BUT probably performance of each Client deteriorates slightly). If I, however, launch 4th Client from ../Client/bin/Debug/... and let each of them submit 20 orders a second, I eventually get the StackOverflow exception on one of those Client.
So, in a nutshell, a single Client can submit 100 orders/second and get all those back from Server and present info on a moderately complex UI without trouble on a single Computer, 3 Client together can handle 60 orders/second BUT 4 Client together can't handle 80 orders/second!
Why?
EDIT
This is the message I get in Call Stack window:
[External Code]
> Client.dll!Client.AsyncObsetion<Data.AllOrder>.OnPropertyChanged(System.ComponentModel.PropertyChangedEventArgs e) Line 29 C#
[External Code]
Client.dll!Client.ClientCode.UpdateOrderOnExecution(Data.AllOrderStruct order) Line 431 C#
Client.dll!Client.ClientCode.Receive(object sender, System.Net.Sockets.SocketAsyncEventArgs e) Line 390 C#
Client.dll!Client.ClientCode.Receive(object sender, System.Net.Sockets.SocketAsyncEventArgs e) Line 402 C#
Client.dll!Client.ClientCode.Receive(object sender, System.Net.Sockets.SocketAsyncEventArgs e) Line 402 C#
Client.dll!Client.ClientCode.Receive(object sender, System.Net.Sockets.SocketAsyncEventArgs e) Line 402 C#
.
.
.
Client.dll!Client.ClientCode.Receive(object sender, System.Net.Sockets.SocketAsyncEventArgs e) Line 402 C#
Client.dll!Client.ClientCode.Receive(object sender, System.Net.Sockets.SocketAsyncEventArgs e) Line 402 C#
Client.dll!Client.ClientCode.Receive(object sender, System.Net.Sockets.SocketAsyncEventArgs e) Line 402 C#
[External Code]
Line 29 C# refers to this line else context.Send(RaisePropertyChanged, e); of this piece of code:
public class AsyncObsetion<T> : ObservableCollection<T>
{
SynchronizationContext context = SynchronizationContext.Current;
readonly object _lock = new object();
public AsyncObsetion() { BindingOperations.EnableCollectionSynchronization(this, _lock); }
public AsyncObsetion(IEnumerable<T> list) : base(list) { BindingOperations.EnableCollectionSynchronization(this, _lock); }
void RaiseCollectionChanged(object param) => base.OnCollectionChanged((NotifyCollectionChangedEventArgs)param);
void RaisePropertyChanged(object param) => base.OnPropertyChanged((PropertyChangedEventArgs)param);
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
if (SynchronizationContext.Current == context) RaiseCollectionChanged(e);
else context.Send(RaiseCollectionChanged, e);
}
protected override void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (SynchronizationContext.Current == context) RaisePropertyChanged(e);
else context.Send(RaisePropertyChanged, e);
}
public void InsertRange(IEnumerable<T> items)
{
CheckReentrancy();
foreach (var item in items) Items.Add(item);
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
}
BUT I don't have any subscriber in my code for that event! Line 431 refers to this line if (order.ExType == ExecutionType.Full) list.Remove(o); this piece of code:
void UpdateOrderOnExecution(AllOrderStruct order)
{
bool buyOrder = order.OrderType == OrderType.Buy;
var list = buyOrder ? BuyOrders : SellOrders;
var o = buyOrder ? list.Where(x => x.BuyOrderNo == order.BuyOrderNo).First() : list.Where(x => x.SellOrderNo == order.SellOrderNo).First();
o.ExType = order.ExType;
if (order.ExType == ExecutionType.Full) list.Remove(o);
else
{
var index = list.IndexOf(o);
o.Quantity -= order.QtyTraded;
list[index] = o;
}
AddExecutedOrder(order);
if (order.BrokerBought == BrokerName || order.BrokerSold == BrokerName) UpDatePendingOrders(o);
App.Current.Dispatcher.Invoke(CommandManager.InvalidateRequerySuggested);
}
Line 390 refers to this Line case Data.Action.Execute: UpdateOrderOnExecution(order); break; and 402 refers to this line if (!e.AcceptSocket.ReceiveAsync(e)) Receive(null, e); of this piece of code:
void Receive(object sender, SocketAsyncEventArgs e)
{
if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success)
{
var data = PacMan<MessageHeader>.Unpack(e.Buffer);
if (data.Type == Message.Trade)
{
e.SetBuffer(orderBuffer, 0, orderBuffer.Length);
e.AcceptSocket.Receive(e.Buffer);
var order = PacMan<AllOrderStruct>.Unpack(e.Buffer);
switch (order.Action)
{
case Data.Action.Add: AddNewOrder(order); break;
case Data.Action.Delete: RemoveOrder(order); break;
case Data.Action.Modify: ModifyOrder(order); break;
case Data.Action.Execute: UpdateOrderOnExecution(order); break;
}
}
else
{
SetBuffer(e, data.Size);
e.AcceptSocket.Receive(e.Buffer);
var array = e.Buffer.ToArray();
Task.Run(() => AddNews(array));
}
e.SetBuffer(headerBuffer, 0, headerBuffer.Length);
if (!e.AcceptSocket.ReceiveAsync(e)) Receive(null, e);
}
else Disconnect4mServer(null);
}
You should use multithreading approach i dont see any problem in your code because you are using 3 project at the same time try using multithreading and let the cpu handle it for you
That 'iterative' keyword of Charles gave me a hacky Idea. For anyone interested to solve this type of problem, here's my hacky approach with heap:
1) create these three variables in Client and Special Client:
Queue<byte[]> Orders = new Queue<byte[]>();
Timer orderProcessTimer;
bool OPTstarted;
2) make changes in Receive function in both of those projects to transfer orders to heap and start the orderProcessTimer there once by replacing that with these:
void Receive(object sender, SocketAsyncEventArgs e)
{
if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success)
{
var data = PacMan<MessageHeader>.Unpack(e.Buffer);
if (data.Type == Message.Trade)
{
e.SetBuffer(orderBuffer, 0, orderBuffer.Length);
e.AcceptSocket.Receive(e.Buffer);
Orders.Enqueue(e.Buffer.ToArray());
}
else
{
SetBuffer(e, data.Size);
e.AcceptSocket.Receive(e.Buffer);
AddNews(e.Buffer.ToArray());
}
e.SetBuffer(headerBuffer, 0, headerBuffer.Length);
if (!OPTstarted)
{
orderProcessTimer.Start();
OPTstarted = true;
}
if (!e.AcceptSocket.ReceiveAsync(e)) Receive(null, e);
}
else Disconnect4mServer(null);
}
3) initialize the orderProcessTimer in constructor, set processing inverval and hook it into an order processing function:
orderProcessTimer = new Timer(500);
orderProcessTimer.Elapsed += ProcessOrder;
4) do the time consuming tasks in ProcessOrder function:
void ProcessOrder(object sender, EventArgs e)
{
orderProcessTimer.Stop();
var count = Orders.Count;
if(count > 0)
{
for (int i = 0; i < count; i++)
{
var order = PacMan<AllOrderStruct>.Unpack(Orders.Dequeue());
switch (order.Action)
{
case Data.Action.Add: AddNewOrder(order); break;
case Data.Action.Delete: RemoveOrder(order); break;
case Data.Action.Modify: ModifyOrder(order); break;
case Data.Action.Execute: UpdateOrderOnExecution(order); break;
}
}
}
orderProcessTimer.Start();
}
UpdateOrderOnExecution takes the most of the time for processing a order and making a real time Price-Volume chart in order view.
It works BUT I probably will not go with this approach, I'll make the machine, that runs such type of app, a half-stack machine for the performance.

Problem Invoking operations in a Windows Form which triggers async API calls

I have a console application which either invokes a class and runs as a console application or triggers a windows form. The windows form inturn sends parameters and invokes the same operation done otherwise.
Invocation point:
static void Main(string[] args)
{
if(AppSettingsHelper.GetValue<bool>("EnableWindowsForm"))
{
System.Console.WriteLine("EnableWindowsForm is set to true - Running Windows form");
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//Application.Run(new Form1(0));
//First Time
var form = new ReportGeneratorForm();
Application.Run(form);
}
else
{
System.Console.WriteLine("EnableWindowsForm is set to false - Running direct program in console");
PortalMonitoring monitoring = new PortalMonitoring();
monitoring.Process();
}
}
Now In Click of Button the Same Class is triggered
private void button1_Click(object sender, EventArgs e)
{
PortalMonitoring monitoring = new PortalMonitoring();
monitoring.Process(DateTime.Now); //Date as paramater- Default is null
}
If i trigger the console app, it works well.
However if i click the button the code is stuck at point of async web api call -below code
int reportID = GetReportIDAsync().Result;
private static async System.Threading.Tasks.Task<int> GetReportIDAsync()
{
var reportName = "Portal name";
var reportID = await ops.GetReportId(reportName);
LogAndWriteToConsole("Report ID Feched : " + reportID.ToString());
return reportID;
}
Kindly help me here, i think windows form doesnt seem to allow multi threads by defauly. How to fix this ?
You don't show the complete path from monitoring.Process() to GetReportIDAsync() but it needs to be async/await all the way.
The top level should look like this:
private async void button1_Click(object sender, EventArgs e)
{
// probably add a try/catch here
PortalMonitoring monitoring = new PortalMonitoring();
await monitoring.Process(DateTime.Now); //Date as paramater- Default is null
}
Your no-winforms branch shoud then use monitoring.Process().Wait()

uwp speech recognition different level control

I'm creating a speech interactive App using UWP. which can show news and weather information, also can play music (I have done that part),but I have some problems about speech recognition:
The functions that I expect:
first command must include "Jason" to activate the App, after that you just need to say the function you want not need to add Jason anymore (like"show me some news."), and after 30 secs, this activate section end, your command need to add "Jason" again to activate the App.
The function I have achieved so far:
Can continuously recognize user's speech, but every command must has "Jason" to trigger the function (like "Jason, show me some news.")
The following is the code I have used.
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
CoreDispatcher dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
SpeechRecognizer contSpeechRecognizer = new Windows.Media.SpeechRecognition.SpeechRecognizer();
await contSpeechRecognizer.CompileConstraintsAsync();
contSpeechRecognizer.ContinuousRecognitionSession.ResultGenerated += ContinuousRecognitionSession_ResultGenerated;
contSpeechRecognizer.ContinuousRecognitionSession.AutoStopSilenceTimeout = TimeSpan.FromDays(1);
contSpeechRecognizer.ContinuousRecognitionSession.Completed += ContinuousRecognitionSession_Completed;
await contSpeechRecognizer.ContinuousRecognitionSession.StartAsync();
}
private async void ContinuousRecognitionSession_Completed(SpeechContinuousRecognitionSession sender, SpeechContinuousRecognitionCompletedEventArgs args)
{
await contSpeechRecognizer.ContinuousRecognitionSession.StartAsync();
}
private async void ContinuousRecognitionSession_ResultGenerated(SpeechContinuousRecognitionSession sender, SpeechContinuousRecognitionResultGeneratedEventArgs args)
{
await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
speechResult = args.Result.Text;
try
{
if (speechResult.Contains("jason"))
{
Functions();//Control functions
}
catch
{
}
});
}
Questions: 1.How can I change to achieve the expected function? 2. Can grammar solve this problem? 3. And how to add the grammar?

windows phone 8 change start page according to result from sqlite database

i want to change the start page of my app according to the result from sqlite db. I have removed the nevigationpage parameter from appmenifist file. In App.xaml.cs in application launching function i am using
Conn = new SQLiteAsyncConnection(DB_PATH);
var BabayData = Conn.QueryAsync<baby>("SELECT * FROM baby");
if (BabayData.Count == 0)
{
RootFrame.Navigate(new Uri("/Profile.xaml", UriKind.Relative));
}
else
{
RootFrame.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
}
But it shows wrong result. (I checked, query doesn't give any results.) How can i solve this issue that if there is a baby MainPage.xaml shuld b start page.
Regards
i think your app is starting before it connects to the database. So u can create a prelogin page or try this:
private async void Application_Launching(object sender, LaunchingEventArgs e)
{
try
{
await ApplicationData.Current.LocalFolder.GetFileAsync(DB_PATH);
Connection = new SQLiteAsyncConnection(DB_PATH);
}
catch (FileNotFoundException)
{
CreateDbAsync(); // create if not exists
}
}
example here

When is taking a photo done?

I'm working on a wp8-app that takes a photo and then takes you to the next screen to decide whether you like it or not.
The current approach was this:
private void ShutterButton_Click(object sender, RoutedEventArgs e)
{
if (cam != null)
{
try
{
cam.CaptureImage();
await Task.Delay(1500);
NavigateFront();
}
catch (Exception ex)
{
...
}
}
}
public void NavigateFront()
{
string naviString = "/confirmPicture.xaml?parameter=" + fileName.ToString();
_rootFrame.Navigate(new Uri(naviString, UriKind.Relative));
}
On my Lumia 520 it crashed sometimes. If I increase the wait-time to 2,5sec it works. But of course this should not be the way to do it.
If I catch the void cam_CaptureImageAvailable(object sender, Microsoft.Devices.ContentReadyEventArgs e)-Event and try to navigate after everything is done and all streams are closed I still get in a NavigateFailed-State and the app crashes.
My question is: is there any other useful event that ensures that all work is done and I can navigate without using static time-based values?
Navigation with a PhotoCamera is possible, just subscribe to its CaptureCompleted event handler
cam.CaptureCompleted += new EventHandler<CameraOperationCompletedEventArgs>(camera_CaptureCompleted);
and this would be the event
void camera_CaptureCompleted(object sender, CameraOperationCompletedEventArgs e)
{
try
{
Deployment.Current.Dispatcher.BeginInvoke(delegate()
{
try
{
cam.Dispose();
NavigationService.Navigate(new Uri("URI nething", UriKind.Relative));
}
catch (Exception)
{
MessageBox.Show("Problem occured!!");
}
});
}
catch
{
MessageBox.Show("Problem in camer_capturecompleted");
}
}
I did it in one of my apps targeting windows phone 7. Check if this works for you as well.

Categories

Resources