I have created a BackgroundTask to run a WebService, however if i run my solution with debugger attached, everything works fine, slowly, but fine. But when i hit start in the appmanager (webinterface) it always says "failed to start package [MYPACKAGEID]". So what am i missing?
Here is the complete project: https://github.com/naice/HomeAutomation.git
public sealed class StartupTask : IBackgroundTask
{
internal static BackgroundTaskDeferral Deferral = null;
public async void Run(IBackgroundTaskInstance taskInstance)
{
//
// TODO: Insert code to perform background work
//
// If you start any asynchronous methods here, prevent the task
// from closing prematurely by using BackgroundTaskDeferral as
// described in http://aka.ms/backgroundtaskdeferral
//
Deferral = taskInstance.GetDeferral();
await ThreadPool.RunAsync(async workItem => {
RestWebServer restWebServer = new RestWebServer(80);
try
{
// initialize webserver
restWebServer.RegisterController<Controller.Home.Home>();
restWebServer.RegisterController<Controller.PhilipsHUE.Main>();
await restWebServer.StartServerAsync();
}
catch (Exception ex)
{
Log.e(ex);
restWebServer.StopServer();
Deferral.Complete();
}
}, WorkItemPriority.High);
}
}
The point is that there is no problem with the code or even the manifest, it seems that it's just not meant to run while the device is in "headed" mode, you need to set it as a satrtup headless app and then restart the device.
Edit: All these problems are gone with the latest version 10.0.14279.1000 and now the GUI finally works as it should.
I have been struggling with this to and have had great success with this method that might help someone. All is done in Power Shell
Put the device into headless mode, in some way I don´t think this is mandatory but I have not succeeded without it.
Edit: This is not the case any more, it works as it should now.
https://ms-iot.github.io/content/en-US/win10/HeadlessMode.htm
Start the app in headless mode and add it to the startup app list
To see what apps are in the startup list type
IotStartup startup
To add a headless app type in command
IotStartup add headless [Task1]
To add a headless app type in command
IotStartup startup headless [Task1]
To find the app name you can use the command
IotStartup list
To see that your app are in startup list type
IotStartup startup
Then reboot your device!
I have also had some problems related to removing apps from startup and then try to debug them via Visual Studio and in some cases the only solution were to flash the SD card with a new image.
For a complete list of available commands
https://ms-iot.github.io/content/en-US/win10/tools/CommandLineUtils.htm
Related
Even though there are similar questions, I couldn't find any that solves mine. I have a simple program that runs as a service and I want to start it programatically. It's as simple as this:
private static void StartService()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new MyService()
};
ServiceBase.Run(ServicesToRun);
}
As expected, I can't just start my service without installing it. Windows gives me the following error message:
Cannot start service from command line or debugger. A windows service must first be installed using installutil.exe and then started with service explorer, Windows services administrative tool or NET start.
So far so good. So I went there and did just as the docs says:
installutil <my_project>.exe
The installation was successful and I can even start my service from Service Manager or net start. The only problem is: when I debug my application (via F5), Windows keeps showing me the exact same message: Cannot start service (...).
I've found a solution here that uses this:
public void onDebug()
{
OnStart(null);
}
Which allows me to run and debug my application normally, but I actually need it to run as a service and Windows refuses to start that way. Is there anything I'm missing?
It is not in your power to just start a Service like a normal programm. The Service must be registered with and started by the Service manager. That is one of the (many) rules of Windows services. And you have to repeat that for every new build.
As this and other Service related rules (no interactive sessions) can make developing them a Pain, a common approach is to develop them using a console application. I could not find my ideal example, but I found something like it:
https://alastaircrabtree.com/how-to-run-a-dotnet-windows-service-as-a-console-app/
Of course a better longterm plan might be to stop using Services alltogether and switch over to the Windows Task Scheduler. It depends heavily on what exactly you need this code to be able to do in practice.
I am working on a windows iot core application running on a rasberry pi3
i tried to create/fetch the device key from the azure iot hub using the methods below
public MainPage()
{
systemName = "RaspIot";
this.InitializeComponent();
/* Register for the unloaded event so we can clean up upon exit */
Unloaded += MainPage_Unloaded;
registryManager = RegistryManager.CreateFromConnectionString(connectionString);
AddDeviceAsync().Wait();
}
private static async Task AddDeviceAsync()
{
Device device;
try
{
device = await registryManager.AddDeviceAsync(new Device(systemName));
}
catch (DeviceAlreadyExistsException)
{
device = await registryManager.GetDeviceAsync(systemName);
}
deviceKey = device.Authentication.SymmetricKey.PrimaryKey;
}
If the device with name "RaspIot" is already registered an exception is thrown.
This is working fine in a .net45 console application. but in the UWP application for the PI3 the exception is thrown (pops up in while debugging) but not captured by the catch). what should i do differently?
I can reproduce your issue. And when running the UWP app using your code, the UI hangs and is not responsive. So it is not a best practice in UWP app.
In the UWP app, you can directly use AddDeviceAsync() without Wait(). It will execute normal and can catch the exception.
But in the console app, the app will exit without getting the task completion if you remove Wait() operator. So they are different.
For calling asynchronous APIs in UWP you can reference this document.
Update:
And it is not recommended register a device in the MainPage function since it will always be executed every time the app is started.
I have a Window Service , that is running on my machine . I have separate console application in the same solution that is performing some functionality. In order to access the functions of the console application , I have add the *.exe file of the console application as a reference to the Window Service project.
public void OnTimer(object sender, System.Timers.ElapsedEventArgs args)
{
// TODO: Insert monitoring activities here.
EventLog.WriteEntry("Monitoring the System", EventLogEntryType.Information);
string[] arr = new string[] { };
ConsoleApplication.Program.Main(null);
}
The Console application works perfectly file if I directly run through Visual Studio. However , If I call the Main() method from the Window Service I am getting a null pointer exception.
public static void Main(string[] args)
{
try
{
//CODE BREAKS HERE ON READING FROM CONFIG FILE
string genesis_sel= ConfigurationSettings.AppSettings["genesis_sel"].ToString();
}
catch (Exception ex)
{
//Exception code
}
}
Below is a snapshot of the Console application Project running in Visual Studio.
I am not sure what's causing the code to break while accessing the main method from a Window service.
Any suggestions?
Update: Added snapshot of the config file. I don't believe it's a rad access issue from the configuration file as it is reading correctly when I run the console application alone. There is an initialization issue when I access it through the window Service.
UPDATE Replaced the main method with a single event log , but still getting the same exception.
When you call the method it is running as part of your service, so it uses Environment and settings from your service. That means that you should have correct data in AppSettings of your service project. To bring more clarity: In this case function Main is part of your service and not a separate application root.
Otherwise you can run your console as separate process, but in that case you are loosing part of Control functions.
I would suggest, to separate common logic in a separate project/dll and call functions from it, it will be more clean and not so confusing
Presently, I am attempting to profile a Windows service that I am working on using the new "Performance and Diagnostics" feature in Visual Studio 2013 (see http://blogs.msdn.com/b/visualstudioalm/archive/2013/07/12/performance-and-diagnostics-hub-in-visual-studio-2013.aspx). When I attempt to profile the service, I get this error message:
Cannot start service from the command line or a debugger. A Windows Service must first be intalled (using installutil.exe) and then started with the ServerExplorer, Windows Services Administrative Tool or the NET START command.
Normally when debugging the service, it works fine because I have the following code in Program.cs:
private static MySvc _serviceInstance;
private static readonly List<ServiceBase> _servicesToRun =
new List<ServiceBase>();
static void Main(string[] args)
{
_servicesToRun.Add(_serviceInstance);
if (Environment.UserInteractive)
{
_servicesToRun.ToArray().LoadServices();
}
else
{
ServiceBase.Run(_servicesToRun.ToArray());
}
}
static Program()
{
_serviceInstance = new MySvc();
}
Also, if I attempt to attach to a running app, in the dialog that appears it doesn't display any executing processes, and when I put the name of the service in there, it does not find it. Does anyone have any suggestions? TIA.
UPDATE: This is what I get when I attempt to attach to a process. Why doesn't the "Performance and Diagnostics" see any processes running on my computer? Why would it only connect to Windows Store apps instead of all exes? Please see this image:
The way I resolved the problem was the copy all the source code and make minor modifications to get everything to run in a Console application, then chose Debug->Performance and Diagnostics and ran the Console application using "Change Target" -> "Launch and executable file (.exe)"
I'm building a Windows Service that uses FileSystemWatcher, and runs in the background.
I don't want to keep on uninstalling and installing the service every time I want to debug, so would like to do most of my development in a normal program before moving it into a service. But I'm quite new to this, and when I run it, it just runs through the block and exits.
What would be a good way to keep the program running?
http://einaregilsson.com/run-windows-service-as-a-console-program/
I've used this before to debug my service as a Console application based on whether its running in an interactive user environment.
public partial class DemoService : ServiceBase
{
static void Main(string[] args)
{
DemoService service = new DemoService();
if (Environment.UserInteractive)
{
service.OnStart(args);
Console.WriteLine("Press any key to stop program");
Console.Read();
service.OnStop();
}
else
{
ServiceBase.Run(service);
}
}
while (true)
{
// Execute your program's functionality here.
}
I wrote a 7 part series a while ago titled: Building a Windows Service. It covers all the intricacies of building services, making them friendly to debug, and self-installing.
The basic feature set I was looking for was as follows:
Building a service that can also be used from the console
Proper event logging of service startup/shutdown and other activities
Allowing multiple instances by using command-line arguments
Self installation of service and event log
Proper event logging of service exceptions and errors
Controlling of start-up, shutdown and restart options
Handling custom service commands, power, and session events
Customizing service security and access control
The final result was a Visual Studio project template that creates a working service, complete with all of the above, in a single step. It's been a great time saver for me.
see Building a Windows Service – Part 7: Finishing touches for a link to the project template and install instructions.
Here’s documentation from MSDN # http://msdn.microsoft.com/en-us/library/7a50syb3(v=vs.80).aspx?ppud=4 . I have tried it before and it works under .NET Framework 3.x. I could not find my descriptive notes on it, at the moment.
Use the pragma #If DEBUG for debugging purposes like console outputs. Another is using the Debug object.
If you have any trouble with this, say so. I may be able to find my notes or make a Windows Service app myself, just to see if the steps on MSDN still work.