App has exited with code 1 (0x1), When runnin on local machine - c#

I am developing a Universal windows app and its working fine on Windows Phone, Phone Emulators but when I try to run this on local machine (desktop) it keep exiting with message " App has exited with code 1" which I think someone send an exit signal with 1, but why ...? no info available.
I found some related questions but non of them have definite answer.
Any help and suggestions would be appreciated.
App.xaml.cs code
public App()
{
this.InitializeComponent();
this.ExtendedSplashScreenFactory = (splashscreen) => new ExtendedSplashScreen(splashscreen);
#if DEBUG
HockeyClient.Current.Configure("Appid");
HockeyClient.Current.SendCrashesAsync();
#endif
// start live tiles updates
SportsClassLibrary.Common.SportsLiveTiles.StartPeriodicTileUpdate("https://tve.rpc.org/windows/sportsTile.cgi");
}
protected override Task OnInitializeAsync(IActivatedEventArgs args)
{
_container.RegisterType<IAlertDialogService, AlertDialogService>(new ContainerControlledLifetimeManager());
_container.RegisterType<IAccountService, AccountService>(new ContainerControlledLifetimeManager());
_container.RegisterType<IConfigService, ConfigServices>(new ContainerControlledLifetimeManager());
_container.RegisterInstance <INavigationService>(this.NavigationService);
_container.RegisterInstance<IEventAggregator>(new EventAggregator());
ServiceLocator.SetUnityContainer(_container);
// override the default viewmodel assembly location
Prism.Mvvm.ViewModelLocationProvider.SetDefaultViewTypeToViewModelTypeResolver((viewType) =>
{
var viewModelTypeName = string.Format(System.Globalization.CultureInfo.InvariantCulture, "SportClassLibrary.ViewModels.{0}ViewModel,SportClassLibrary", viewType.Name);
var viewModelType = Type.GetType(viewModelTypeName);
return viewModelType;
});
return Task.FromResult<object>(null);
}
protected override object Resolve(Type type)
{
return _container.Resolve(type);
}
protected override async Task OnLaunchApplicationAsync(LaunchActivatedEventArgs args)
{
if (args.PreviousExecutionState != ApplicationExecutionState.Running)
{
IConfigService configServices = (IConfigService)ServiceLocator.getServiceInstanceForType(typeof(IConfigService));
await configServices.GetConfigAsync();
}
this.NavigationService.Navigate(Experiences.Experience.Epg.ToString(), null);
}
}
All methods execute fine

Okay I found the issue, actually I was sending crash report to hockey asynchronously in constructor method, HockeyClient.Current.SendCrashesAsync(); moving this code to OnInitializeAsync method fix this issue.

Related

Unknown command: --environment=Development during testing

I created an ASP.NET project and wrote some integration tests for it. But when I tried to run dotnet test this shows up:
Starting test execution, please wait...
A total of 1 test files matched the specified pattern.
The active test run was aborted. Reason: Test host process crashed : Unknown command: --environment=Development
Test Run Aborted with error System.Exception: One or more errors occurred.
---> System.Exception: Unable to read beyond the end of the stream.
at System.IO.BinaryReader.Read7BitEncodedInt()
at System.IO.BinaryReader.ReadString()
at Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.LengthPrefixCommunicationChannel.NotifyDataAvailable()
at Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.TcpClientExtensions.MessageLoopAsync(TcpClient client, ICommunicationChannel channel, Action`1 errorHandler, CancellationToken cancellationToken)
--- End of inner exception stack trace ---.
As I understand something tries to run dotnet executable with --environment=Development but this argument is invalid even though it is used in Microsoft docs.
I tried creating new ASP.NET project (no controllers, services, database etc. just API that does nothing and an empty test) but I couldn't reproduce the error again.
Initially I created my project and solution in the same folder by accident and had to manually move project to subfolder. Everything worked fine after I did that so I assumed it's fine. Maybe that is the reason.
Here's how I access application during testing:
// TestingApplication.cs
public class TestingApplication : WebApplicationFactory<Program>
{
private readonly Guid _appId = Guid.NewGuid();
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
// Add mock/test services to the builder here
builder.ConfigureServices(services =>
{
services.AddMvcCore().AddApplicationPart(typeof(Program).Assembly);
services.AddScoped(sp => new DbContextOptionsBuilder<EfDbContext>()
.UseSqlServer(
$"DATABASE CONNECTION STRING")
.UseApplicationServiceProvider(sp)
.Options);
});
}
protected override IHost CreateHost(IHostBuilder builder)
{
var host = base.CreateHost(builder);
using (var serviceScope = host.Services.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetRequiredService<EfDbContext>();
context.Database.EnsureCreated();
}
return host;
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
using (var serviceScope = Server.Services.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetRequiredService<EfDbContext>();
context.Database.EnsureDeleted();
}
}
}
// BaseTest.cs
public class BaseTest : IDisposable, IClassFixture<TestingApplication>
{
protected readonly TestingApplication Application;
private HttpClient? _client;
protected HttpClient Client => _client ??= Application.CreateClient();
public BaseTest(TestingApplication testingApplication)
{
Application = testingApplication;
}
public void Dispose()
{
Application.Dispose();
}
}
Some more info:
Unit tests work just fine
Initially I forgot to add <InternalsVisibleTo Include="NameOfTestsProject" /> to the main project file, but it doesn't work either way.
.NET 6, OS - Linux, IDE - Jetbrains Rider
Rebuilding solution does not work
Creating new project for unit tests doesn't help either
Does anyone know what the problem is?
UPD I figured it out
Okay, So this is just another example of copy-pasting someone else's code without checking. I had copied something along the lines of:
if (args[0] == "something") {
...
} else if (args[0] == "something else") {
...
} else {
// exit with code 1 here and print error
}
in my Program.cs. It worked fine by itself but when testing it caused this problem.

Correct Xamarin Forms Shell initializing with async data loading

I am working on a rather complex xamarin forms app for a while now and now I came over a problem related to the async initialization of the app. Some context before I come to the problem.
I am using the current version of Xamarin Forms, my main target is
xamarin android
I am building on top of the xamarin forms Shell
pattern
I am using a sqlite database for the main part of the apps
configuration
The app layout is mainly dependent on the configuration stored in the sqlite database (what I call a data driven app)
Therefore I am building the whole shell page layout not in xaml but in code behind of the AppShell.xaml.cs - in the constructure to be concrete (first weird point in my personal opinion).
So first remarkable point here - I need the fully loaded configuration BEFORE the AppShell is initiated.
At first a started with a mockup data service where the whole config was inside a large mocked object so it ran fully synchronized - everything perfect!
After switching over to the sqlite implementation where I am using async methods the problem started to show up because I try to load the configuration in the constructor (second weird point because such a task should never be part of a constructor in my point of view)
So my constructor of AppShellView.xaml looks like this.
public App()
{
InitializeComponent();
InitApp().SafeFireAndForget(onException: ErrorHandler);
MainPage = new AppShellView();
}
the InitApp Method where the database is queried looks like this.
private async Task InitApp()
{
_settingsService = ViewModelLocator.Resolve<ISettingsService>();
ViewModelLocator.UpdateDependencies(_settingsService.UseDemoMode);
_dataService = ViewModelLocator.Resolve<IDataService>();
ActiveConfiguration = await _dataService.GetActiveConfigurationAsync().ConfigureAwait(false);
//MainPage = new AppShellView(); this was added to reload the MainPage after the config was fully loaded
}
what obviously happens is that the MainPage = new AppShellView() in the App's constructor is called before the config is loaded - because its called in a fireandforget way. Therefore the following construction of the AppShellView does not work as intendet because the pages cannot be added because of the missing config. I hope this is clear so far.
To overcome this issue I added another MainPage = new AppShelLView() as last step of the InitApp method.
The constructor of the AppShellView looks like this:
public AppShellView()
{
InitializeComponent();
BuildMainNavigation();
BuildSettingsNavigation();
InitRoutes();
this.CurrentItem.CurrentItem = startSection;
}
This seems to work on thirst sight but triggers side effects when the app is started from AppLink Shortcuts and not to forget I ended up initializing the same object again and again which causes performance issues and simply smells...
So I hope I made my point clear so far - I know that I have a view issues in my implementation but I simply don't see the correct way of doing it.
What I would naturally would try to do is doing the configuration loading in the android init part behind the splash screen which I implemented like this: https://learn.microsoft.com/en-us/xamarin/android/user-interface/splash-screen but I also found no way to pass the data from the android Activity to the App class.
To sum up and ask a concrete question:
What is the best practice way of loading async configuration BEFORE initializing the Shell
#Jason: thanks for your fast response. So this idea seems promising, sounds like another Splash Screen but thats ok.
I tried that - for the initial setup that works fine.
App's constructor is simplified to this:
public App()
{
InitializeComponent();
MainPage = new Splashscreen();
}
The OnStart looks like this now:
protected async override void OnStart()
{
base.OnStart();
if (!IsInitiated)
{
_settingsService = ViewModelLocator.Resolve<ISettingsService>();
ViewModelLocator.UpdateDependencies(_settingsService.UseDemoMode);
_dataService = ViewModelLocator.Resolve<IDataService>();
ActiveConfiguration = await _dataService.GetActiveConfigurationAsync().ConfigureAwait(true);
MainPage = new AppShellView();
App.Current.UserAppTheme = _settingsService.OSAppTheme;
}
else
{
App.Current.UserAppTheme = _settingsService.OSAppTheme;
}
base.OnResume();
}
But I have app link functionality, where OnAppLinkRequestReceived is called.
protected override async void OnAppLinkRequestReceived(Uri uri)
{
if(MainPage is Splashscreen)
{
MainPage = new AppShellView();
}
IsInitiated = true;
var targets = uri.ToString().Replace(GlobalSetting.AppShortcutUriBase, "");
var subtargets = targets.Split('/');
App.CurrentPageId = new Guid(subtargets[0]);
if(subtargets.Length > 1 && !string.IsNullOrWhiteSpace(subtargets[1])){
await Shell.Current.GoToAsync($"//{App.CurrentPageId}?buildingPartId={new Guid(subtargets[1])}");
}
else
{
await Shell.Current.GoToAsync("//" + App.CurrentPageId);
}
}
The Problem is that its called before OnStart. So its calling the correct page first but the reinit in OnStarts resets the app to base.
I could overcome this issue with performing the init only of OnAppLinkRequestReceived is not called but then I have one last issue.
I call App.Current.UserAppTheme = _settingsService.OSAppTheme; as displayed above inside OnStart end the call inside the else black is failing with NullpointerException because App.Current seems to be null in this case. Do you know why?
Here are the final code bits that made the whole thing work. The key aspects are as follows:
Add another SplashScreen which is initiated inside App.xaml.cs constructor
Perform the long running async method in the OnStart()
Perform path based navigation which is triggered by an AppLinkRequest also inside the OnStart after storing the AppLinkRequest Uri inside a property
public App()
{
InitializeComponent();
_settingsService = ViewModelLocator.Resolve<ISettingsService>();
ViewModelLocator.UpdateDependencies(_settingsService.UseDemoMode);
_dataService = ViewModelLocator.Resolve<IDataService>();
AppLinkUri = null;
MainPage = new SplashScreen();
}
private async Task InitApp()
{
ActiveConfiguration = await _dataService.GetActiveConfigurationAsync().ConfigureAwait(true);
}
protected override async void OnStart()
{
base.OnStart();
if (ActiveConfiguration == null)
{
await InitApp().ConfigureAwait(true);
}
MainPage = new AppShellView();
if (AppLinkUri != null)
{
var targets = AppLinkUri.ToString().Replace(GlobalSetting.AppShortcutUriBase, "");
var subtargets = targets.Split('/');
App.CurrentPageId = new Guid(subtargets[0]);
if (subtargets.Length > 1 && !string.IsNullOrWhiteSpace(subtargets[1]))
{
await Shell.Current.GoToAsync($"//{App.CurrentPageId}?buildingPartId={new Guid(subtargets[1])}");
}
else
{
await Shell.Current.GoToAsync("//" + App.CurrentPageId);
}
}
base.OnResume();
}
protected override void OnAppLinkRequestReceived(Uri uri)
{
AppLinkUri = uri;
}

Xamarin.Android using async method on background thread causes screen flash

So I'm trying to create a loading/splash screen for an app that I'm creating. Basically, if the user isn't authenticated, then they shouldn't be able to access the other parts of the app. Additionally, I'd like the app to attempt to sync the necessary database objects before it loads up the main activity.
The problem is that when I call the Authenticate() method and the InitLocalStoreAsync() methods, the screen flashes (almost like an activity reload, or like the app is doing something that I don't understand that's hiding the activity) while the methods are executing. I'd like that not to happen.
I'm very new to Android App Dev and even newer to Xamarin.
I'm using modified code that comes from the Azure Mobile Services tutorial on authentication etc.
Should I be somehow executing these methods using RunOnUiThread? If so, how do I await in conjunction with RunOnUiThread? Or should I be doing this in a completely different way?
I'm very lost. I've tried to search and find tutorials to follow, but I can't seem to find the answer. Here's the code so far:
protected override async void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.Activity_Splash);
// Create your application here
try{
CurrentPlatform.Init ();
// Create the Mobile Service Client instance, using the provided
// Mobile Service URL and key
client = new MobileServiceClient (applicationURL, applicationKey);
statusText = FindViewById<TextView> (Resource.Id.SplashStatusText);
ThreadPool.QueueUserWorkItem(x => Initialize());
}catch(Java.Net.MalformedURLException){
CreateAndShowDialog (new Exception ("There was an error creating the Mobile Service. Verify the URL"), "Error");
}catch(Exception e) {
CreateAndShowDialog (e, "Error");
}
}
private async void Initialize()
{
RunOnUiThread(() => statusText.Text = "Authenticating...");
await Authenticate();
RunOnUiThread (() => statusText.Text = "Syncing...");
await InitLocalStoreAsync();
MoveToMainActivity();
}
private async Task Authenticate()
{
try
{
user = await client.LoginAsync(this, MobileServiceAuthenticationProvider.Google);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
private async Task InitLocalStoreAsync()
{
// new code to initialize the SQLite store
string path = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), localDbFilename);
if (!File.Exists(path))
{
File.Create(path).Dispose();
}
var store = new MobileServiceSQLiteStore(path);
store.DefineTable<ToDoItem>();
// Uses the default conflict handler, which fails on conflict
// To use a different conflict handler, pass a parameter to InitializeAsync. For more details, see http://go.microsoft.com/fwlink/?LinkId=521416
await client.SyncContext.InitializeAsync(store);
}
How do I restructure this so that I don't get any screen flashes?
If you want to run an asynchronous method you have to use the Task Factory:
RunOnUiThread(() => statusText.Text = "Loading.");
Task.Run(() => AsyncWork()).ContinueWith(result => RunOnUiThread(() => statusText.Text = "Done!"));
The screen flashes i think it could be 2 things, the app crashed and is trying to recover the last activity or your are trying to update elements on the UI thread and doing processing/work too, so it might be "stutter".

Windows service (c#) not starting

Apologies for my English, I'm not a native speaker.
I'm trying to make a Windows service. If I try to build, install and run a VS template I don't get any errors.
I have ported my winform application to a service, made an installer, added some data sources, added a reference for the webservice, added some classes, but DIDN'T add any code to OnStart() and OnStop(). My code builds correctly and I can start and stop the service from the service manager.
However, if I add some code to the service class (which I don't call anywhere) and if I don't add code to OnStart() and to OnStop() then I can't start the service and the error is something like "The service doesn't respond the control functions". In the event log I can see the exception:
System.ArgumentOutOfRangeException
Stack:
in System.String.InternalSubStringWithChecks(Int32, Int32, Boolean)
in System.String.Substring(Int32, Int32)
in UpdaterFIAS.FIASMainClass.getNameFile(System.String, System.String, System.String)
in UpdaterFIAS.FIASMainClass..ctor()
in UpdaterFIAS.Updater..ctor()
in UpdaterFIAS.Program.Main()
And I can see here my function getNameFile() is throwing an Exception. However, this isn't called in my code because I have empty OnStart(). So, how can I find what went wrong if the event log doesn't write anything ( if it is in the OnStart() ) ? And I can't attach a debugger to it because it throws this exception.
edit: Forgot to say, my code works correctly when I use windows forms but here I don't call anything in OnStart, the project builds without errors but I have an exception when starting the service.
EDIT 2:
Program.cs code:
namespace UpdaterFIAS
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Updater()
};
ServiceBase.Run(ServicesToRun);
}
}
}
Updater.cs code:
namespace UpdaterFIAS
{
public partial class Updater : ServiceBase
{
public Updater()
{
InitializeComponent();
if (!System.Diagnostics.EventLog.SourceExists("MySource"))
{
System.Diagnostics.EventLog.CreateEventSource("MySource", "MyNewLog");
}
eventLog1.Source = "MySource";
eventLog1.Log = "MyNewLog";
}
FIASMainClass mainFIAS = new FIASMainClass();
protected override void OnStart(string[] args)
{
//timer1 = new System.Timers.Timer(5000);
//timer1.Elapsed += timer1_Elapsed;
//timer1.AutoReset = false;
//timer1.Enabled = true;
//ServiceStarterThread = new Thread(ServiceStarter);
//ServiceStarterThread.Start();
eventLog1.WriteEntry("In OnStart");
//mainFIAS.Start();
}
protected override void OnStop()
{
//if (updater != null && (updater.ThreadState != System.Threading.ThreadState.Aborted && updater.ThreadState != System.Threading.ThreadState.Stopped)) updater.Abort();
//if (log != null && (log.ThreadState != System.Threading.ThreadState.Aborted && log.ThreadState != System.Threading.ThreadState.Stopped)) log.Abort();
//log.Abort();
//timer1.Enabled = false;
//timer1.Dispose();
eventLog1.WriteEntry("In OnStop");
//mainFIAS.Stop();
}
}
}
EDIT 3:
FIASMainClass.cs code:
namespace UpdaterFIAS
{
class FIASMainClass
{
public FIASMainClass()
{ }
public void Start()
{
ServiceStarterThread = new Thread(ServiceStarter);
ServiceStarterThread.Start();
}
public void Stop()
{
if (updater != null && (updater.ThreadState != System.Threading.ThreadState.Aborted && updater.ThreadState != System.Threading.ThreadState.Stopped)) updater.Abort();
if (log != null && (log.ThreadState != System.Threading.ThreadState.Aborted && log.ThreadState != System.Threading.ThreadState.Stopped)) log.Abort();
}
private void ServiceStarter()
{
...
}
...
...
...
}
}
From you Stack Trace, the entry point is Program.Main. From there a new Updater is created and the getNameFiles is called. That would be the place to start.
As far as Debugging a windows service. You are right, this is indeed hard. There are two tricks I know. The first one is in the Main (or OnStart) to set a Thread.Sleep before you do anything. This way you have time to attach your debugger.
The other trick, is if your Visual Studio is on the same machine as your service, in the Main (or OnStart) add this line: Debugger.Launch(). This will tell the service to seek out Visual Studio for a debugging session. See here for more: Debugger.Launch() on windows service in Windows 8

Cannot evaluate expression because a native frame is on top of the call stack

I'm creating a simple window service and when I go to debug I get the error, "Cannot evaluate expression because a native frame is on top of the call stack.". Also, when I build the service in Release and run it just hangs.
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[] { new MyService1() };
ServiceBase.Run(ServicesToRun);
}
Thats all that is in the Program.cs file, where it normally gets hung on the ServiceBase.Run(ServicesToRun) line.
Everything I've been able to find only relates to the expression not being evaluated because the code is optimized or having to deal with asp.net and response.redirect.
Code for the Service.
public TruckRateClearService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
tmrProcess.Enabled = true;
}
protected override void OnCustomCommand(int command)
{
base.OnCustomCommand(command);
if (command == 129)
{
OnStart(null);
}
}
protected override void OnStop()
{
tmrProcess.Enabled = false;
}
private void tmrProcess_Tick(object sender, EventArgs e)
{
tmrProcess.Enabled = false;
try
{
eventLog.WriteEntry("Clearing Truck Rates Start" + DateTime.Now.ToString());
TruckRateClearingAgent.Process();
eventLog.WriteEntry("Clearing Truck Rates Finished" + DateTime.Now.ToString());
}
catch (Exception ex)
{
eventLog.WriteEntry(ex.ToString(), EventLogEntryType.Error);
}
tmrProcess.Enabled = true;
}
internal void Run()
{
tmrProcess_Tick(tmrProcess, null);
}
The Internal Void Run() was added just recent on the suggestion in the comments by Eren Ersönmez. His idea has been very helpful for helping debug my logic until I can figure the rest out.
I was able to get the into the Native call stack and it sits on one location, 76F17094 ret. Now I have no idea what this is but maybe someone else will.
Also, when I start the service and look into attaching it to VS I'm noticing two instances of it. One is the normal .exe and another is a .vshost.exe. When I start other services I only see the .exe file in the Attach to process part of the debugger. Could this be because one is on the v4 Framework ( .vshost .exe service ) and another on the v2 ( single .exe service ) Framework?
I believe I got it working. It seems that the problem lied with the timer I was using. The original timer I was using was a System.Windows.Forms timer. I switched it to System.Timers.Timers and everything started working again. Still cant attach VS to it but I can debug it still by using the Internal Run() method. Thanks for all the help n.n
Your main problem is that you're trying to directly run a windows service exe. Windows services can only be started via Service Control Manager (SCM). In order to be able to debug in VS, I'd recommend something like this:
static void Main()
{
if (Environment.UserInteractive)
{
new MyService1().Run();
Thread.Sleep(Timeout.Infinite);
}
else
{
ServiceBase.Run(new ServiceBase[] { new MyService1() });
}
}
You'd create a MyService1.Run method which spawns a new thread that runs the service loop. Also, you'd call the same Run method from within the MyService1.Onstart.
This scheme runs it as a service when being started by SCM, but treats it like a normal exe when being debugged in VS (or being run directly as an exe outside VS).
The problem
This notification means that the thread is currently executing unmanaged code, and therefore cannot be used to evaluate the expression.
In some situations, you could wait for the call to return to managed code before evaluating the expression. Unfortunately, in this situation, that won't happen until you shut down the service.
An Alternative
You might consider overriding the ServiceBase.OnCustomCommand method and putting a breakpoint there so you can evaluate your expression.
protected override void OnCustomCommand(int command)
{
//Debugger.Break() <- or just put a breakpoint in here.
}
You can invoke the custom command as follows:
c:\>sc control YourServiceName 129
The exception you're seeing means that unmanaged code is throwing an exception, so the .NET debugger can't show you the usual useful details.
What are you doing in MyService1() ? Can you post the code inside it?
Also are you trying to debug the service by just starting it from the environment. That might not work.
I usually write something like this:
static void Main(params string[] args)
{
if (args.Length > 0 && args[0] == "/console")
{
// Run whatever your service calls here
}
else
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[] { new MyService1() };
ServiceBase.Run(ServicesToRun);
}
}
Then in the project properties under the Debug tab enter /console as the command line arguments. You should be able to step into the application and debug it. You can only debug a service by installing it first: http://msdn.microsoft.com/en-us/library/7a50syb3(v=vs.80).aspx

Categories

Resources