Sending toast notification from Windows service throws HRESULT: 0x80070005 (E_ACCESSDENIED) - c#

The line of code that throws the error is:
new ToastContentBuilder()
.AddText("Title of notification")
.AddText("Body of notification")
.Show();
The program is a Windows service made in C#, installed using a Wix installer. ToastContentBuilder comes from the Microsoft.Toolkit.Uwp.Notifications namespace. In Product.wxs, I have set the ServiceInstall tag as such:
<SeviceInstall Id="ServiceInstaller"
Type="ownProcess"
Vital="yes"
Name="MyProcessName"
DisplayName="My Process Name"
Description="My process description."
Start="auto"
Account="LocalSystem"
ErrorControl="normal"
Arguments=""
Interactive="yes" />
In the Services viewer in Windows, I have checked the properties of the process, and it is logged on as a Local System account, and the "Allow service to interact with desktop" box is checked.
I am aware of a similar question, but that question is unanswered and is seemingly not a service installed using Wix, so it is of little use.
I would appreciate any leads. I am not very familiar with Wix so something in Product.wxs may be at fault.

I've never tried to send a toast message from a windows service. I have sent toast messages from tray apps and scheduled tasks running as the user.
To have click events in the toast you have to create an app with a shortcut in the start menu like this:
<Shortcut Id="sc1" Name="Some App" Directory="ProgramMenuFolder" Description="Some App">
<!--AUMID-->
<ShortcutProperty Key="System.AppUserModel.ID" Value="WindowsNotifications.SomeApp" />
<!--COM CLSID, specifying which CLSID to activate when toast clicked-->
<ShortcutProperty Key="System.AppUserModel.ToastActivatorCLSID" Value="guid-used-in-code" />
</Shortcut>
In your code you have to implement
[ClassInterface(ClassInterfaceType.None)]
[ComSourceInterfaces(typeof(INotificationActivationCallback))]
[Guid("guid-used-in-code"), ComVisible(true)]
and
protected override void OnStartup(StartupEventArgs e)
{
// Register AUMID, COM server, and activator
DesktopNotificationManagerCompat.RegisterAumidAndComServer<MyNotificationActivator>("WindowsNotifications.SomeApp");
DesktopNotificationManagerCompat.RegisterActivator<MyNotificationActivator>();

Related

How to launch a full-trust process as elevated from UWP app?

I am trying to launch a full-trust process program from my UWP app. I am using the PackageManager in my full-trust process to locate UWP packages to launch files or links, so I need to run it as an admin.
When I try running the full-trust process, it opens and works properly on my machine (I am running an admin account). However, when I look up the process in the Task Manager, it does not run elevated.
I'm just worried that it may not work on any other machine (non-admin) out there. Here's my code I'm using in Package.appxmanifest, courtesy of Stefan Wick (https://stefanwick.com/2018/10/07/app-elevation-samples-part-3/):
<desktop:Extension Category="windows.fullTrustProcess" Executable="Assets\NitishTest.exe">
<desktop:FullTrustProcess>
<desktop:ParameterGroup GroupId="Parameters" Parameters="parameters" />
</desktop:FullTrustProcess>
</desktop:Extension>
<uap3:Extension Category="windows.appExecutionAlias"
Executable="Assets\NitishTest.exe"
EntryPoint="Windows.FullTrustApplication">
<uap3:AppExecutionAlias>
<desktop:ExecutionAlias Alias="NitishTest.exe" />
</uap3:AppExecutionAlias>
</uap3:Extension>
I am not using a Windows Application Packaging Project, however. Could this be the reason why it's not working properly elevated?

UWP app fails to start on login using the StartupTask APIs

NOTE: I've already looked at this related question, this is not a duplicate
I'm working on a UWP app which also uses the Desktop Bridge (the app package contains the UWP app and a WinForms component), and I'm trying to add the auto startup feature, so far without success.
Here's what I did:
Some research. Looked at this question mentioned before, this blog post from MS and at the official docs as well.
Followed the docs by editing the Package.appxmanifest file to add the uap5 namespace, and then the uap5:Extension node as instructed, setting my app .exe file in the Executable property, and Windows.FullTrustApplication in the EntryPoint property.
Bonus: just in case, I also tried to replace the uap5 namespace with desktop, as some code samples used that one instead. Same result, the app doesn't start at all.
Included the APIs to get the startup task and request it to be setup.
Deployed the app, proceeded to use those APIs, got the confirm window and tapped "allow".
Opened the Task Managed and double checked that the app name was there under the "Startup" tab, with the "Enabled" label correctly shown next to it.
Logged out and back in
At this point nothing happens, except from the mouse pointer showing the loading ring for half a second after logging in. Opened the Windows event viewer and found an error, which was indicating the failed auto startup for the app. Tried again a few times and sure enough, every time the app didn't start and another identical error popped up in the event viewer. This is the error info:
Application name: <my app>.exe, versione: 1.0.0.0, timestamp: 0x5a68410c
Module: KERNELBASE.dll, versione: 10.0.17134.407, timestamp: 0x99042cc0
Exception code: 0xe0434352
Offset: 0x000000000003a388
Process ID: 0x1c4c
Path: C:\Users\<my username>\Documents\GitHub\<my app>\<my app>.Package\bin\x64\Debug\AppX\<my app>.exe
Module path: C:\Windows\System32\KERNELBASE.dll
[...]
I'm not sure what I'm doing wrong here, I've followed the docs step by step and I do see the app listed in the Task Manager, but it just fails to start this way.
Any help would be appreciated, thanks in advance! 😄
EDIT: it seems the problem is related to the Desktop Bridge functionality. I have a UWP app and a packaging project, and I've added the startup task to both the .appxmanifest files (with different Ids). I do this as I use the packaging project to create the x86/x64 builds, and the UWP project directly for the ARM/ARM64 builds.
If I only deploy the UWP app (standalone, without the package) and enable the startup task, the app runs fine. But, if I deploy the packaging project and enable that startup task, the startup fails. I do see the startup task in the Task Manager in both cases. As mentioned earlier, when the startup task fails for the packaging project, I see those errors in the event viewer.
EDIT #2: did some more tests with the Desktop Bridge app. It seems that after it fails to start, the Windows event logger gets two more errors listed there for each attempt. One is the error in the "Application Error" category mentioned earlier, and another one is an error in the "AppModel-Runtime" category, with the following info:
Failed with 0x490 modifying AppModel Runtime status for package for user (current status = 0x0, desired status = 0x20).
EDIT #3: as requested, here's the .appxmanifest file for the packaging project. Note that as mentioned earlier, I tried adding the startup task both using the desktop namespace as well as the newer uap5 namespace. Again, in both cases I can retrieve the task and prompt the user to enable it, and I do see it listed in the Task Manager, but the application still fails to start with the usual error.
When setting up a StartupTask extension in your appxmanifest it is important to understand that the declaration is different for Win32 components vs UWP components. This is documented here:
https://learn.microsoft.com/en-us/uwp/api/Windows.ApplicationModel.StartupTask
UWP Components:
<Package xmlns:uap5="http://schemas.microsoft.com/appx/manifest/uap/windows10/5" ...>
...
<Applications>
<Application ...>
...
<Extensions>
<uap5:Extension Category="windows.startupTask">
<uap5:StartupTask
TaskId="MyStartupId"
Enabled="false"
DisplayName="Test startup" />
</uap5:Extension>
</Extensions>
</Application>
</Applications>
Win32 Components:
<Package xmlns:uap5="http://schemas.microsoft.com/appx/manifest/uap/windows10/5"...>
...
<Applications>
<Application ...>
...
<Extensions>
<uap5:Extension
Category="windows.startupTask"
Executable="MyDesktopBridgeApp.exe"
EntryPoint="Windows.FullTrustApplication">
<uap5:StartupTask
TaskId="MyStartupId"
Enabled="false"
DisplayName="My Desktop Bridge App" />
</uap5:Extension>
</Extensions>
</Application>
</Applications>

Register Windows Service by Wix Tool Set script

I have Wix setup project which configure windows service to auto-start on install and system reboot. Before auto-start feature, everything was fine. My procedure of deployment was to install service, register it via "InstallUtil.exe" utility and then start service manual. I want to automate all these activities, but I am facing a problem when i try to install service on a system on which service is not configured with "InstallUtil.exe" utility. The error message I am getting is given as:
Service "(ServiceName) could not be configured. This could be problem
with the package or your permissions. Verify that you have sufficient
privileges to configure system services.
Service configuration code is:
<ServiceInstall Id="ServiceInstaller" Type="ownProcess" Vital="yes" Name="$(var.ServiceName)" DisplayName="$(var.ServiceName)" Description="Description"
Start="auto" Account="LocalSystem" ErrorControl="normal" Interactive="no"/>
<ServiceConfig Id="ServiceConfigAtStartUp" ServiceName="$(var.ServiceName)" DelayedAutoStart="yes" OnInstall="yes" OnReinstall ="yes" />
<ServiceControl Id="StartService" Name="$(var.ServiceName)" Start="install" Stop="both" Remove="uninstall" Wait="yes" />
Thank you Edgar Jul. This problem has been solved. I wrote a small console project in C# which registers Windows service if not already registered. This is very easy in C#. I call this executable (ServiceRegister.exe) as a custom action after all the installation files are copied, as can be be seen in the following Wix script.
<CustomAction Id="RegisterService"
Directory="INSTALLFOLDER"
ExeCommand=""[INSTALLFOLDER]ServiceRegister.exe" /Register"
Execute="deferred"
Return="ignore"
Impersonate="no" />
<InstallExecuteSequence>
<Custom Action='RegisterService' After='InstallFiles' />
</InstallExecuteSequence>

Msi setup showing File in use message on uninstallation

I have developed an msi setup using WIX which consists of a desktop application as well as a windows service and both are running on C# .Net 3.5 framework. My windows service starts only when any user logs into the system which triggers the desktop application to start. The windows service is made to run as Local System. The msi setup is getting installed successfully at Win-8, Win-7 and Windows-XP but showing "File In Use" message while doing uninstallation even the service is not removed from the SCM. I have given the below codes at the OnStop() method of the service and inside the WIX page respectively.
onStop() method:
Process[] workers = Process.GetProcessesByName("filename");
workers[0].WaitForExit(1000);
workers[0].Kill();
workers[0].Dispose();
workers[0].Close();
Product.wxs inside WIX:
<ServiceInstall Id="ServiceInstaller" Name="Servicename"
DisplayName="service display name" Description="service description"
Start="auto" Account="LocalSystem" ErrorControl="normal"
Type="ownProcess"></ServiceInstall>
<ServiceControl Id="ServiceInstallerControl" Name="Servicename"
Start="install" Stop="both" Remove="uninstall" Wait="yes" />
The service is not removed from the SCM at all and the below popup message is displaying at the time of uninstallation process.
I have worked around with the WIX to solve the problem but unable to do so.
Any kind of help in this regard will be highly appreciated.
I'd recommend you to create custom action that handles the uninstall.You can create a batch file with the uninstall details , and then simply execute the batch file from the custom action( as a process).Its good practice to create installation and uninstall batch files with your service.

Can't get NServiceBus running under custom service account?

I've created a bare-bones NServiceBus endpoint (which doesn't do anything for now), and when I install it (using NServiceBus.Host.exe /install /displayName:"MyEndpoint"), it gets installed as a service
that runs under Local Service, and it works perfectly.
Now, when I change the Run as account for this Windows Service to my own local service account (lets call it "svcTestAccount" for now, it has Logon as a service permission), the service starts and then unexpectedly stops halfway during its initialization.
I can't tell why, since no exceptions get logged to log4net, the process just terminates.
I've seen this behaviour before in a previous project when the endpoint couldn't access the queue it needed, but this time I have configured the 5 queues that my endpoint to give "Everyone" "Full Control", so it shouldn't be that, right?
What's strange is that, when I run it (using the NServiceBus.Host.exe on production profile), it happily runs in all the following situations:
From within Visual Studio 2012, running as local admin.
As a windows service, running under Local Service
As a windows service, running under Network Service
As a windows service, running under svcTestAccount, if svcTestAccount is a member of the local Administrators group.
From a command prompt running under svcTestAccount (i.e. "runas /user:svcTestAccount cmd" to open the command prompt, then NServiceBus.Host.exe to run my endpoint)
The only thing that doesn't work is getting it to run as a Windows Service under svcTestAccount (and not being a member of the local Administrators group).
Can anybody tell me what's going on?
For completeness sake, my endpoint only consists of:
public class EndpointConfig : IConfigureThisEndpoint, AsA_Publisher, IWantCustomInitialization
{
public void Init()
{
Configure.With()
.DefaultBuilder()
.Log4Net();
}
}
And my web.config:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<configuration>
<configSections>
<section name="UnicastBusConfig" type="NServiceBus.Config.UnicastBusConfig, NServiceBus.Core" />
</configSections>
<UnicastBusConfig>
<MessageEndpointMappings>
</MessageEndpointMappings>
</UnicastBusConfig>
</configuration>
I'm using NServiceBus 4.3.0 on Windows Server 2012.
To run NServiceBus host as a different account (not Local System) you need to execute the installer with /username and /password, eg:
NServiceBus.Host.exe /install /displayName:"MyEndpoint" /username:"mydomain\username" /password:"mysecretpassword"
See http://docs.particular.net/NServiceBus/the-nservicebus-host#installation for more info.

Categories

Resources