How to prevent multiple instances of Windows 10 XAML applications? - xaml

I'm working on a Windows 10 app. One of the new features of Windows 10 apps is the ability of multiple instances (windows) of the same app. I want to disable this. Has anyone found documentation regarding this scenario?

You can override method OnLaunch in App.xaml.cs :
protected async override void OnLaunched(LaunchActivatedEventArgs e)
{
if (e.PreviousExecutionState != ApplicationExecutionState.Running) //Check if is there any instance of the App is already running
{
base.OnLaunched(e);
}
}

Check out this Instancing property in manifest file.
Instancing

Related

Service not calling OnShutdown() when windows shuts down

I have .net core console application, which is hosted as windows service.
I want to catch an event if the user logs off/shutdown the computer.
I have found ways to catch this event in .net framework (here & here).
But I cant figure out how to achieve this in .net core.
To create service I am using "ServiceBase" class. Sample code is as given below:
public class MyService : ServiceBase
{
readonly string LogPath = "D:\\TestAppService.txt";
#region Constructors
public MyService()
{
this.CanShutdown = true;
}
#endregion
#region Protected Functions
protected override void OnStart(string[] args)
{
//your code here
// call the base class so it has a chance
// to perform any work it needs to
base.OnStart(args);
}
protected override void OnStop()
{
//your code here
// Call the base class
base.OnStop();
}
protected override void OnShutdown()
{
using (StreamWriter sw = File.AppendText(LogPath))
{
sw.WriteLine("shutdown == true");
}
//your code here
base.OnShutdown();
}
#endregion
}
The OnStop and OnStart methods are being called.
but when I shutdown the computer my OnShutdown method is not called.
According to aspisof.net, you should be able to use the SessionEnding API. This is because it is listed as being exposed in the windows Compatibility Pack - available on NuGet here.
This article on learn.microsoft.com shows how you can include it in a .NET Core application.
tl;dr
Add the NuGet package
Target Windows only
One thing to note: this was originally designed to be a temporary fix for porting Windows specific .NET code over to .NET Core.
The more accepted way to implement Windows only features is to move as much code to .NET Standard libraries as possible, and to use conditional compilation directives to include platform specific code when building for that platform.
By design dotnet core is not "friendly" with platform specific stuff
(like listening to log off event seems to me).
The solution I use in one of Windows-hosted services is described here.
When application domain is forced to close by operating system on shutdown - there is a room for using AppDomain event handlers.

Android Accessibility Service stopped working after a day or two on Oreo

Background:
I have a class which extends from AccessibilityService. Whenever a window is changed following function is called which gives me the application name of the foreground application.
#Override
public void onAccessibilityEvent(AccessibilityEvent event) {
}
Following is the configuration I set:
#Override
protected void onServiceConnected() {
super.onServiceConnected();
//Configure these here for compatibility with API 13 and below.
AccessibilityServiceInfo config = new AccessibilityServiceInfo();
config.eventTypes = AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED;
config.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC;
if (Build.VERSION.SDK_INT >= 16) { //Just in case this helps
config.flags = AccessibilityServiceInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS;
}
setServiceInfo(config);
}
AccessibilityService.xml
<?xml version="1.0" encoding="utf-8"?>
<accessibility-service
xmlns:android="http://schemas.android.com/apk/res/android"
android:description="#string/accessibility_explanation"
android:accessibilityEventTypes="typeWindowStateChanged|typeAllMask"
android:accessibilityFeedbackType="feedbackSpoken|feedbackHaptic|feedbackAudible|feedbackVisual|feedbackGeneric|feedbackAllMask"
android:notificationTimeout="100" android:canRetrieveWindowContent="true" />
The Problem:
It works fine for some time, but after a day or two it suddenly stops working. It doesn't call the onAccessibilityEvent(AccessibilityEvent event) function. Although the accessibility service of this application is enabled but still it doesn't show the application name when window is changed.
May be it doesn't work if the application comes back from sleep mode? I had to reinstall the application on top of my debug build and then again it started working but for how long.
Question: How can I make sure it always return me the application name when window is changed?
Just restart your app. This is because Accessibility Service is managed by the Android OS, so if any thing causes your service to crash, it will be killed and rescheduled to be started at some time in the fture that you can not control. So it is possible that your service has been killed.

Single process C#.Net windows service is showing multiple thread in CPU resource monitor?

I have developed a C#.Net windows service which is a single process.In this I'm using 2 third party Dlls one for ZIP(Ionic) and another for Excel(EPPlus).
The .EXE job is to:
Read SDF file
Write the SDF file data to SQL Server table
Generate Excel
Create ZIP
While monitoring this particular EXE in resource monitor it is showing 10 threads are running.
Note: I have not used any threading in this application.
Is OS making it 10 threads? If yes, how and why??
Related: Why does this simple .NET console app have so many threads?
I'll use a simple console application in Visual Studio 2010 that adds a reference to an assembly that spawns a thread similar to what a 3rd party library could do.
A Windows Service may have different debugging techniques, and may have various additional threads running created by the system.
Simple Console
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
ClassLibrary1.Class1.StartThread();
while (true)
{
System.Threading.Thread.Sleep(1000);
System.Diagnostics.Trace.TraceInformation("test2");
}
}
}
}
Simple API in separate class library assembly, added as a reference to the Console project
using System.Threading.Tasks;
namespace ClassLibrary1
{
public class Class1
{
public static void StartThread()
{
var t = new Task(() => {
while(true)
{
System.Threading.Thread.Sleep(1000);
System.Diagnostics.Trace.TraceInformation("test1");
}
});
t.Start();
}
}
}
Start Debugging (F5)
From the Menu Debug, Select 'Break All'
From the Menu Debug, Select Windows then Threads
The following image shows :
Main Thread, this is the console application
ClassLibrary1.Class1.StartThread.AnonymousMethod_0, this is the thread started by the referenced assembly. If Ionic or a 3Rd party API started a thread, you may see something related to its namespace.

How to share fluent configuration in a Castle Windsor IOC container

I am trying to create an IOC container in Castle Windsor that's configuration is shared across assemblies.
(What follows is an example of how this works in Unity. What I want to do is to make it work the same way using Castle Windsor)
I have the following project configuration...
TestCompany.Services.Host
(Web project hosting a number of .svc files)
PrintService.svc
Web.Config
Unity.Config
TestCompany.Services.PrintService
IPrintService.cs
PrintService.cs
The actual implementation of my "PrintService" is not implemented inside my Services.Host but in the TestCompany.Services.PrintService assembly.
As part of my shared project code (not shown) I have a container helper which is responsible for loading the unity configuration...
public static IUnityContainer GetContainer()
{
// Checks for existance of container (_container == null) ommitted.
var section = ConfigurationManager.GetSection("unity") as UnityConfigurationSection;
section.Configure(_container, name);
...
...
}
This method loads the unity configuration section from the Unity.Config and uses it to configure the container.
The advantage of this method is that one Unity.Config loaded inside (I presume) the AppDomain can service a number of assemblies. Simply calling GetContainer() from any of the assemblies consumed by my service host will return a container populated with the same type resolution's etc.
I really want to use the fluent configuration in Castle Windsor but I dont see how without this "shared" configuration file that can be acheived. PrintService and any future services will all need to resolve the same dependencies and I dont want to have to repeat my fluent configuration between these services.
Ideally I need some sort of container configured in the service host app that can "flow" into all of the assemblies that it makes use of.
Thanks.
I think I may not be understanding your question but I think I understand your scenario and here is how I do something similar, if it helps at all...
My Philosophy:
Each part of the application should be in charge of registering what
it knows about and nothing more, so there is no need for a single
central configuration file and things that are shared between
components are registered in one place and their interfaces are
available everywhere via a common library.
So let's take an example...
First of all, let us just say (for the purposes of my example) that IPrintService is something that you want to register an implementation of once and use throughout the application and that we have some other component that needs to be implemented by some external module from the main application. We, therefore, create an assembly called Common like so:
Common
public interface IPrintService
{
void Print();
}
public interface IMyService
{
void DoSomething();
}
Now let us think about the main part of the application (maybe it is an ASP .NET application, maybe justa console application, does not really matter). Here we construct the container and ask it to find all the possible components. We can do that like so:
Main Application
// Could be the Global.asax code behind but for simplicity this is
// just a console application
class Program
{
private static readonly IWindsorContainer Mycontainer
= BootstrapContainer();
// Allow access to the raw container - this is probably a bad idea but
// in the rare case that you need it you can get it from here
public static IWindsorContainer Container { get { return Mycontainer; } }
private static IWindsorContainer BootstrapContainer()
{
// Here we will just install every IWindsorInstaller found in any
// assembly in the same folder as the application (so no need for
// references or anything).
var c = new WindsorContainer();
string folder = Path.GetDirectoryName(
Assembly.GetExecutingAssembly().Location);
c.Install(FromAssembly.InDirectory(new AssemblyFilter(folder)));
return c;
}
}
// Here is the print service implementation
public class MyPrintService : IPrintService
{
public void Print()
{
// Print!
}
}
// This is the installer for the main module - here we are saying exactly
// what is implementing the interface
public class MainApplicationInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container,
IConfigurationStore store)
{
container
.Register(Component
.For<IPrintService>()
.ImplementedBy<MyPrintService>());
}
}
So now we have a common library with our shared inetrfaces and a main application that will register an implementation for our shared interface and also load up any other modules in the system.
The only thing, therefore, left to do is to consume that print service and use it. We can do this anywhere that is using the container so let's create a third assembly that references only Common (we will call it test module.
Test Module
// This installer installs just the things inside this module since that
// is all it knows about but those things can use things that are
// registered in the container by anybody.
public class TestModuleInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container,
IConfigurationStore store)
{
container
.Register(Component
.For<IMyService>()
.ImplementedBy<MyServiceThatDoesSomething>());
}
}
public class MyServiceThatDoesSomething : IMyService
{
private readonly IPrintService _printService;
public MyServiceThatDoesSomething(IPrintService printService)
{
_printService = printService;
}
public void DoSomething()
{
// Use the print service!
_printService.Print();
}
}
Finally compile everything and copy the test module to the same folder as the main application and then from the main you can do this:
Container.Resolve<IMyService>().DoSomething();
And then the magic happens! Well, some code runs and you find that the print service is called by the class from the module even though it knows nothing about it.
Anyway, maybe that helps a little bit, maybe not, good luck!

Managing Configuration Changes in WCF

What is the preferable way to manage configuration file changes in WCF webservices? I know usually in desktop applications people use a FileSystemWatcher to watch for changes in App.config, but how exactly does one go about configuring one in WCF? I tried using something like the following code:
public class Service : IService
{
private static readonly FileSystemWatcher ConfigurationWatcher = new FileSystemWatcher(PathToRootDirectory);
private void ReloadConfiguration(object sender, FileSystemEventArgs e)
{
ConfigurationManager.RefreshSection("appSettings");
ConfigurationManager.RefreshSection("connectionStrings");
}
// IService implementation goes here.
static Service()
{
ConfigurationWatcher.Filter = "web.config";
ConfigurationWatcher.NotifyFilter = NotifyFilter.LastWrite;
ConfigurationWatcher.Change += ReloadConfiguration;
}
}
However, that didn't seem to work since ConfigurationWatcher seemed to being initialized upon every call to the service... How does one go about accomplishing this?
This happens automatically for a service hosted in IIS.
Any change to the web.config or any assembly in the bin folder will cause the current AppDomain to shut down and a new AppDomain to be started for subsequent requests - just like with ASP.NET.