Get Microsoft Store updates available for the UWP app - c#

I want user to notify if the Microsoft store has updates for the app.After researching I found below code and implemented it.
public static async Task<bool> IsStoreUpdatesAvailable()
{
try
{
if (context == null)
context = StoreContext.GetDefault();
IReadOnlyList<StorePackageUpdate> updates = await context.GetAppAndOptionalStorePackageUpdatesAsync();
Logs.Write.Success("Store updates are available? :" + updates.Any().ToString());
return updates.Any();
}
catch (Exception ex)
{
return false;
}
}
When I run it in my machine in debug mode or release mode it works fine.But when I try a release build in another machine it logs the following error.
Message: Exception from HRESULT: 0x8024500C StackTrace: at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() + 0x21
at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task) +
0x70 at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task)
0x38 at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task) + 0x17
at
com.IronOne.BoardPACWinApp.Helpers.WindowsStoreServiceHelper.d__3.MoveNext()
0x105
Any suggestion on how to fix it?

Related

Strange bug where function doesn't get evaluated at all

I have this strange situation where I have an Outlook VSTO add-in written in c# targeting Outlook 2007 and 2010. The add-in works fine in 2007 environment. It also works fine in debug mode with Outlook 2010 in Visual Studio (2010) when I press start. However, once I deploy to UAT one of the functions doesn't get evaluated at all.
One of the functions is
private static bool HTTPTransmitEmailItem(string username, string email_file_name)
{
// DEBUG
Utils.LogDebug("Got into HTTPTransmitEmailItem");
try
{
Stopwatch timer = new Stopwatch();
timer.Start();
try
{
Utils.LogDebug("Msg saved as : " + full_file_name_and_path);
if (HTTPPostDataToEP(username, temp_path, email_file_name))
{
File.Delete(full_file_name_and_path);
return true;
}
else
{
Utils.LogWarn("Trans Fail, Storing for later sending. " + email_file_name);
//if need start resend timer
TransmitFailed();
}
}
catch (Exception ex)
{
Utils.HandleException("OFE HHTP Ex", ex);
   
TransmitFailed();
}
timer.Stop();
Utils.LogDebug("Email File Thread took " + timer.ElapsedMilliseconds.ToString() + "(ms)");
}
catch (Exception ex)
{
}
return false;
}
The culprit is the part:
if (HTTPPostDataToEP(username, temp_path, email_file_name))
{
File.Delete(full_file_name_and_path);
return true;
}
else
{
Utils.LogWarn("Trans Fail, Storing for later sending. " + email_file_name);
//if need start resend timer
TransmitFailed();
}
The application never enters the method HTTPPostDataToEP... The method definition is
private static bool HTTPPostDataToEP(string username, string path, string name)
{
// DEBUG
Utils.LogDebug("Got into HTTPPostDataToEP");
try
{
var content = new MultipartFormDataContent();
content.Add(new StringContent(username), "userAddress");
content.Add(new StreamContent(File.Open(path + name, FileMode.Open)), "msg", name);
// DEBUG
Utils.LogDebug("In Line 174 in OutlookTransmitRaw");
var client = new HttpClient();
HttpResponseMessage result = client.PostAsync(Utils.configEndPoint, content).Result;
// DEBUG
Utils.LogDebug("In Line 178 in OutlookTransmitRaw. Result is " + result);
if (result.IsSuccessStatusCode)
Utils.LogDebug("Msg Transmit Response : " + result.ToString());
else
Utils.LogInfo("Msg Fail Transmit Response: " + result.ToString());
return result.IsSuccessStatusCode;
}
catch (Exception ex)
{
throw new Exception("Failed to dispatch email to API. Caused by ", ex);
}
}
The application doesn't raise any exception. It simply walks pass that if block and executes Utils.LogDebug("Email File Thread took " + timer.ElapsedMilliseconds.ToString() + "(ms)"); This only happens when I publish the project and install it using set.exe file. In debug mode it works as expected...
The empty catch block would explain your problem: an exception is raised and you simply ignore that and happily carry on.
I could imaging something going wrong with file permissions after you deploy your solution, for instance. But whatever goes wrong gets swallowed up and you'll never hear about it...
Either throw from that catch block, or log something before you throw, but blindly ignoring exceptions like this is never a good idea. Something goes wrong, you get an exception with information, and you refuse to look at it.
Wrong:
catch (Exception ex)
{
}
Weird and useless:
catch (Exception ex)
{
throw;
}
Often useful:
catch (Exception ex)
{
Logger.Log(ex);
throw;
}

Unable to start Azure Worker Role, exception code 0xe0434352 & 0xC0000035

When running locally in the emulator the web worker works fine. However whenever I update my web worker running on an Azure VM I get the following exceptions exceptions in the event viewer and the role won't start:
Application: WaWorkerHost.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.AggregateException
Stack:
at System.Threading.Tasks.Task.Wait(Int32, System.Threading.CancellationToken)
at System.Threading.Tasks.Task.Wait()
at Foo.PushProcess.WorkerRole.Run()
at Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment.StartRoleInternal()
at Microsoft.WindowsAzure.ServiceRuntime.Implementation.Loader.RoleRuntimeBridge.b__2()
at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
at System.Threading.ThreadHelper.ThreadStart()
Inner Exception: A task was canceled.
Faulting application name: WaWorkerHost.exe, version: 2.6.1198.712, time stamp: 0x54eba731
Faulting module name: KERNELBASE.dll, version: 6.3.9600.17415, time stamp: 0x54505737
Exception code: 0xe0434352
Fault offset: 0x0000000000008b9c
Faulting process id: 0xfb8
Faulting application start time: 0x01d11e3128981a5d
Faulting application path: E:\base\x64\WaWorkerHost.exe
Faulting module path: D:\Windows\system32\KERNELBASE.dll
Report Id: 30631c5c-8a25-11e5-80c6-000d3a22f3ec
Faulting package full name:
Faulting package-relative application ID:
Session "MA_ETWSESSION_WAD_415df88f8a0447178dbd4c18f1349f0e_Foo.PushProcess_Foo.PushProcess_IN_0" failed to start with the following error: 0xC0000035
This is the relevant code:
public override void Run()
{
Trace.TraceInformation("Foo.PushProcess is running");
try
{
RunAsync(_cancellationTokenSource.Token).Wait(); // This is where the exceptions point to
}
catch (Exception ex)
{
Trace.TraceError("[WORKER] Run error: " + ex);
}
finally
{
_runCompleteEvent.Set();
}
}
public override bool OnStart()
{
// Set the maximum number of concurrent connections
ServicePointManager.DefaultConnectionLimit = 12;
// For information on handling configuration changes
// see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.
bool result = base.OnStart();
_storageAccount = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("StorageConnectionString"));
var queueClient = _storageAccount.CreateCloudQueueClient();
_pushQueue = queueClient.GetQueueReference("pushes");
_pushQueue.CreateIfNotExists();
CreatePushBroker();
Trace.TraceInformation("Foo.PushProcess has been started");
return result;
}
private async Task RunAsync(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
Trace.TraceInformation("Working");
CloudQueueMessage message = null;
try
{
message = _pushQueue.GetMessage();
if (message != null)
{
ProcessItem(message);
}
}
catch (Exception ex)
{
if (message != null && message.DequeueCount > 5)
_pushQueue.DeleteMessage(message);
Trace.TraceError("[WORKER] Retrieval Failure: " + ex);
}
await Task.Delay(1000, cancellationToken);
}
}
Note some code has been omitted, however that is all run after the initialisation and in theory isn't reached by this exception.
I am completely at a loss as to what could cause this issue. Any help would be appreciated - even if only to aid me getting a helpful exception.
UPDATE
I have now reduced my code to the below - it is as simple as a web worker can possibly be - and I am still getting the exceptions. I believe that either the old worker is being cached, or there is an issue in the deployment procedure.
public override void Run()
{
Trace.TraceInformation("Foo.PushProcess is running");
try
{
RunAsync(_cancellationTokenSource.Token).Wait(); // This is where the exceptions point to
}
catch (Exception ex)
{
Trace.TraceError("[WORKER] Run error: " + ex);
}
finally
{
_runCompleteEvent.Set();
}
}
public override bool OnStart()
{
// Set the maximum number of concurrent connections
ServicePointManager.DefaultConnectionLimit = 12;
// For information on handling configuration changes
// see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.
bool result = base.OnStart();
return result;
}
private async Task RunAsync(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
Trace.TraceInformation("Working");
// code removed for testing - no work is being done.
await Task.Delay(1000, cancellationToken);
}
}
I gave this a whirl and wasn't able to get this to repro on my end. I have VS 2015 Enterprise (14.0.23107.0 D14REL) from a MSDN Azure image I deployed running with .Net Fx version 4.6. I have Azure Tools and SDK 2.8 installed. I created a new Azure Cloud Service using .NET Fx 4.5.2 and I add a single worker role.
I just ran some sparse code template from yours as follows:
public class WorkerRole : RoleEntryPoint
{
private readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
private readonly ManualResetEvent runCompleteEvent = new ManualResetEvent(false);
private CloudQueue _pushQueue;
private CloudStorageAccount _storageAccount;
public override void Run()
{
Trace.TraceInformation("WorkerRole1 is running");
try
{
this.RunAsync(this.cancellationTokenSource.Token).Wait();
}
catch (Exception ex)
{
Trace.TraceError("[WORKER] Run error: " + ex);
}
finally
{
this.runCompleteEvent.Set();
}
}
public override bool OnStart()
{
// Set the maximum number of concurrent connections
ServicePointManager.DefaultConnectionLimit = 12;
// For information on handling configuration changes
// see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.
bool result = base.OnStart();
_storageAccount = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("StorageConnectionString"));
var queueClient = _storageAccount.CreateCloudQueueClient();
_pushQueue = queueClient.GetQueueReference("pushes");
_pushQueue.CreateIfNotExists();
CreatePushBroker();
Trace.TraceInformation("Foo.PushProcess has been started");
return result;
}
private void CreatePushBroker()
{
return;
}
public override void OnStop()
{
Trace.TraceInformation("WorkerRole1 is stopping");
this.cancellationTokenSource.Cancel();
this.runCompleteEvent.WaitOne();
base.OnStop();
Trace.TraceInformation("WorkerRole1 has stopped");
}
private async Task RunAsync(CancellationToken cancellationToken)
{
// TODO: Replace the following with your own logic.
while (!cancellationToken.IsCancellationRequested)
{
Trace.TraceInformation("Working");
CloudQueueMessage message = null;
try
{
message = _pushQueue.GetMessage();
if (message != null)
{
ProcessItem(message);
}
}
catch (Exception ex)
{
if (message != null && message.DequeueCount > 5)
_pushQueue.DeleteMessage(message);
Trace.TraceError("[WORKER] Retrieval Failure: " + ex);
}
await Task.Delay(1000, cancellationToken);
}
}
private void ProcessItem(CloudQueueMessage message)
{
return;
}
}
}
That runs without issue in the local emulator, and I went ahead and deployed it to West US with IntelliTrace enabled, on a small instance VM, and had n deployment issues. It is running on a WA-GUEST-OS-4.26_201511-0 guest worker role image, and I was able to RDP into the machine, and I didn't see any issues related to the code or the machine. DO you have any other binaries you might not be including in your packages, or perhaps there are some dependencies not defined properly, or storage account naming issues?
Here was the deployment log for me. As you can see, it took about 7 minutes as I had it pull storage from East US just for fun:
1:11:25 AM - Warning: There are package validation warnings.
1:11:26 AM - Checking for Remote Desktop certificate...
1:11:26 AM - Uploading Certificates...
1:11:42 AM - Applying Diagnostics extension.
1:12:24 AM - Preparing deployment for AzureCloudService1 - 11/24/2015 1:11:19 AM with Subscription ID '9a4715f5-acb8-4a18-8259-1c28b92XXXXX' using Service Management URL 'https://management.core.windows.net/'...
1:12:24 AM - Connecting...
1:12:24 AM - Verifying storage account 'ericgoleastus'...
1:12:24 AM - Uploading Package...
1:12:28 AM - Creating...
1:13:15 AM - Created Deployment ID: c5f26568707b46a3bd42466dd0bf7509.
1:13:15 AM - Instance 0 of role WorkerRole1 is creating the virtual machine
1:13:15 AM - Starting...
1:13:32 AM - Initializing...
1:14:36 AM - Instance 0 of role WorkerRole1 is starting the virtual machine
1:16:11 AM - Instance 0 of role WorkerRole1 is in an unknown state
1:16:43 AM - Instance 0 of role WorkerRole1 is busy
Details: Starting role... System is initializing. [2015-11-24T01:16:08Z]
1:19:50 AM - Instance 0 of role WorkerRole1 is ready
1:19:50 AM - Created web app URL: http://quequetest.cloudapp.net/
1:19:50 AM - Complete.
Let us know if you can get some more details possibly with IntelliTrace enabled.
Regards,
Eric
To fix this issue I simply deleted the original Cloud VM instance which held the worker role, recreated it and re-published the role. From that point it has worked absolutely fine.
I am still unable to determine what caused the error, and have had no further issues like this with any other worker role. My assumption here was that there was a configuration issue with the VM which could not be amended through code or the Azure portal.

MessageDialog crashes when called - Windows Phone Store app

I am having a message dialog to prompt the user when there is no internet.
public async void validateInternet()
{
if (!isInternet())
{
Action cmdAction = null;
MessageDialog _connectAlert = new MessageDialog("We are currently experiencing difficulties with your conectivity. Connect to internet and refresh again.", "No internet");
_connectAlert.Commands.Add(new UICommand("Retry", (x) => { cmdAction = () => validateInternet(); }));
_connectAlert.DefaultCommandIndex = 0;
_connectAlert.CancelCommandIndex = 1;
await _connectAlert.ShowAsync();
cmdAction.Invoke();
}
}
public static bool isInternet()
{
ConnectionProfile connections = NetworkInformation.GetInternetConnectionProfile();
bool internet = connections != null && connections.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess;
return internet;
}
Now, I call this function validateInternet when MainPage has loaded. The app opens the message dialog, and crashes immediately. What's wrong with the code?
A A first chance exception of type 'System.UnauthorizedAccessException' occurred in BusTrack.exe Additional information: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
is thrown at
await _connectAlert.ShowAsync();
As #yasen rightly pointed out, the validateInternet() was called both in MainPage_loaded() and OnNavigatedTo().
Hence, System.UnauthorizedAccessException occurs since both of those methods will try to show a messageDialog. So, never try to call two message dialogs at the same time.

Installing windows service Using C# gives error

Im working in windows service syncmysqldb.exe i need the service to run a process ie syncing of two mysql databases in n intervals of time given in setting.xml file
When i install this service service manager i see the service not in started state and when i try to run in manually by right clicking it gives following error
When i install service it gives following error
The description for Event ID ( 11001 ) in Source ( MsiInstaller ) cannot be found. The local computer may not have the necessary registry information or message DLL files to display messages from a remote computer. You may be able to use the /AUXSOURCE= flag to retrieve this description; see Help and Support for details. The following information is part of the event: Product: SetupSynMysqldb -- Error 1001. Error 1001. An exception occurred during the Commit phase of the installation. This exception will be ignored and installation will continue. However, the application might not function correctly after installation is complete. --> The savedState dictionary contains inconsistent data and might have been corrupted., (NULL), (NULL), (NULL), (NULL), , .
When i run service in service manager it gives following error
The SyncMysqlDb service failed to start due to the following error:
The system cannot find the file specified.
C# code
protected override void OnStart(string[] args)
{
try
{
//add this line to text file during start of service
EventLog.WriteEntry("SyncMysqlDb in OnStart. at " + DateTime.Now);
//handle Elapsed event
tmrSync.Elapsed += new ElapsedEventHandler(OnElapsedTime);
tmrSync.Interval = GetIntervals();
//enabling the timer
tmrSync.Enabled = true;
//TraceService(" tmrSync.Interval =" + tmrSync.Interval + " at " + DateTime.Now);
ThreadPool.QueueUserWorkItem(new WaitCallback(ServiceWorkerThread));
}
catch (Exception ex)
{
EventLog.WriteEntry("Service failed to start.", EventLogEntryType.Error, (int)Service1EventIds.Start_InitializationFailure, ex);
}
}
private void ServiceWorkerThread(object state)
{
// Periodically check if the service is stopping.
while (!this.stopping)
{
// Perform main service function here...
Thread.Sleep(2000); // Simulate some lengthy operations.
}
// Signal the stopped event.
this.stoppedEvent.Set();
}
protected override void OnStop()
{
tmrSync.Enabled = false;
//TraceService("stopping service" + DateTime.Now);
EventLog.WriteEntry("SyncMysqlDb in OnStop. at " + DateTime.Now);
this.stopping = true;
this.stoppedEvent.WaitOne();
}
private void OnElapsedTime(object source, ElapsedEventArgs e)
{
try
{
EventLog.WriteEntry(#"Executing C:\SyncMysqlDbRepository\task.bat at " + DateTime.Now);
Process.Start(#"C:\SyncMysqlDbRepository\task.bat");
}
catch (Exception ex)
{
EventLog.WriteEntry("Service failed to start.at " + DateTime.Now, EventLogEntryType.Error, (int)Service1EventIds.Start_InitializationFailure, ex);
}
// TraceService("syncing db at " + DateTime.Now);
}
protected int GetIntervals()
{
var dt = new DataTable();
try
{
dt.ReadXmlSchema(#"C:\SyncMysqlDbRepository\SettingsDs.xml");
dt.ReadXml(#"C:\SyncMysqlDbRepository\Settings.xml");
}
catch (Exception ex)
{
EventLog.WriteEntry("GetIntervals failed at " + DateTime.Now, EventLogEntryType.Error, (int)Service1EventIds.Start_InitializationFailure, ex);
return 0;
}
return Convert.ToInt16(dt.Rows[0].ItemArray[2]); //Intervals from settings.xml
}

Tracking where error was generated using stacktrace from Bugsense report in Windows Phone app

I have had an app on the windows phone store for awhile now and a few people have been emailing me about bugs. I could not replicate the issues so I added bugsense to my app. Now I am starting to get error reports which is great.
One of the reports I recieved today had the following in the stacktrace
at Microsoft.Phone.Reactive.ObservableExtensions.b__3[TSource](Exception exception)
at Microsoft.Phone.Reactive.AnonymousObserver`1.Error(Exception exception)
at Microsoft.Phone.Reactive.AbstractObserver`1.OnError(Exception exception)
at Microsoft.Phone.Reactive.AnonymousObservable`1.AutoDetachObserver.Error(Exception exception)
at Microsoft.Phone.Reactive.AbstractObserver`1.OnError(Exception exception)
at Microsoft.Phone.Reactive.Observable.<>c__DisplayClass161`1.<>c__DisplayClass163.b__160()
at Microsoft.Phone.Reactive.CurrentThreadScheduler.Trampoline.Run()
at Microsoft.Phone.Reactive.CurrentThreadScheduler.EnsureTrampoline(Action action)
at Microsoft.Phone.Reactive.AnonymousObservable`1.Subscribe(IObserver`1 observer)
at Microsoft.Phone.Reactive.Observable.<>c__DisplayClass323`1.<>c__DisplayClass325.b__31e()
at Microsoft.Phone.Reactive.ThreadPoolScheduler.<>c__DisplayClass5.b__3(Object _)
at System.Threading.Timer.ring()
Comment was The operation has timed-out.
The problems is I use Observable in various places through out the app so how can I track where the error is being generated?
EDIT:
I have just spotted the Observable.TimeOut that I am using, could this be the cause?
IObservable<IEvent<TheWeatherBug.GetLocationListCompletedEventArgs>> observable =
Observable.FromEvent<TheWeatherBug.GetLocationListCompletedEventArgs>(WeatherBugService, "GetLocationListCompleted").Take(1);
var ObservableTimeout = Observable.Timeout(observable, TimeSpan.FromSeconds(10));
ObservableTimeout.Subscribe(w =>
{
pbarSearch.Visibility = System.Windows.Visibility.Collapsed;
if (w.EventArgs.Error == null)
{
locations = w.EventArgs.Result;
foreach (TheWeatherBug.ApiLocationData ap in locations)
{
if (ap.City.Contains(location))
if (!lbxLocations.Items.Contains(ap.City + " - " + ap.Country))
lbxLocations.Items.Add(ap.City + " - " + ap.Country);
}
if (lbxLocations.Items.Count == 0)
MessageBox.Show("Sorry could not find a city called " + location);
}
});

Categories

Resources