Intro to Windows Services in C# - How to create, install, and use a service using Topshelf

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
services in Windows are really powerful tools for automation but they're often overlooked these small applications run constantly in the background and can be used for a number of tasks from the simple to complex in this video we're gonna look at how to create service how to run it and debug it and how to install it now if you're new to this channel my name is Tim Corey and it's my goal to make learning c-sharp easier whether you're new to c-sharp or have used it for years you should be able to find something here they'll benefit you we're on the biggest ways you can see improvement in your c-sharp skills is through practice make sure that whatever you learn you practice that's why I have an ongoing series on Thursdays called the weekly challenge I encourage you to participate each week to make you sure your skills stay sharp okay let's get started let's start from a blank project today if you want the file source code there's a link in the description that will take you to a blog post where you can download this code for this video we're gonna create a console application so file new project let's start a console application let me create this and call it the simple heartbeat service okay because really the idea here is not about what code I put in here but instead on how to create the service itself now I will go over a few different ways that these can be used to kind of get you jump-started in using this in the real world but for this we're just gonna create a simple heartbeat service that will say yes I'm alive yes I'm alive over and over now before we get started I do want to make sure I clarify what a service is because there's a few different things that are called services but in this case we're talking about is a Windows service so if you go to your if you hit the Windows key and just type service this is what you get a list of services and these are things that run in the background on your computer notice that there's some that are running and some that are not so here's the list of ones I have running there's a lot of them and that's not let's see a bad thing something kind of freaked out I see all the things were in the background it's only a problem if they're really heavy and take up a lot of resources but a laugh service it just kind of sits in a background and do things occasionally and that's where I'm create today something that's does something occasionally it's not heavy it's not a slow computer down significantly in any way so but for example I just pull a few here hyper-v so hyper-v is a virtual machine management system that runs in Windows and I have that installed and it's running so I can run virtual machines if I want to there's a whole bunch more in here my sequel on port 80 is running or my single 80 I'm not sure it's port 80 but there's a whole bunch in here sequels here remote desktop is here and so forth so that's the services list we're gonna add our own called simple heartbeat service so just to make sure let's come down here and look for s I and there's s H and then SM so there's no simple heartbeat service listed here so just kind of keep that in mind because eventually we're gonna put a service there so we have a command or a a console application now you may have thought that we'd do this instead let me just kind of point this out there's a new product type if you search for service you'll probably find well WCF services tell you something totally different but then there's Windows service right here we could have used that project type the problem with this prototype is it's very hard to debug and so instead of doing that we're using a console application which is going to do the same exact thing as that service product type only we can also run it as a console application and the benefit there is we can run it locally and debug it or we can install it as a service and we will have to attach to that service nor debug it then and then redeploy it every time and that's kind of a problem with the the built-in service type project is that in order to debug it you have to install it get to run your machine and then attach the debugger to that running application to debug it then I find that when I'm initially Korean application that debugging process is a lot back and forth and so if I make one fix and think that the whole fix and then I deployed again and it's not the whole thing I do it again and again and again that's a long process this makes it shorter by using as a console application now I could do this manually and just create the whole thing manual in and stahl it with a command line all the rest but I'm going to make my life a little easier and use a tool and the tool is open-source it's been around for a long time and it will be around for a long time and that is top shelf so right click on references go imagine to get packages or a search for top shelf this person right here three point four five million downloads so it is very popular it has been used a lot obviously but it also has a lot of integrations for example squirrel updater so we talked about the squirrel desktop installer application before well this will allow you to do updates using squirrel to your service we're just gonna use just top shelf for today and we'll hit install alright and we're done now the first thing I do is I actually want to create my service coat now service codes a little bit different than a console application a console application has a start and and it kind just flows linearly so you start the beginning of this curly brace and I tell you at the end you're done and that's not really what a service does it continues to run in the background forever potentially and so we have to create something to do that it's a really simple little kind of like a template or formula you do so it's create class and this class is going to be the class where it's actually doing the service works right call this the heart beat let's call her P I make it public and in here we have to a few things first of all we'd have a start method and a stop method both public and that start we get called when we're starting our service and a stop we get called when we stop our service so let's set that up but first want to do you guys set up what this is going to do in this case really simple stuff I'm going to have a timer run that's going to run every second and when it when the timer elapses I'm going to write to a file just the date and time simple okay so private read-only timer I hit control dot to a user exhibit but there's two different kinds of timers so we have system dot threading and system dot timers these two are similar in nature and in fact they will work the same way if you have a simple application but if you get into a multi-threaded situation what you really want he's not the threading one but the timers one the timers one has actually thread safe so let's use the system timers and we'll call this on our score timer and now we'll do create a constructor ctor and we'll say that the timer equals new timer and we'll give it a 1 second interval so it counts in milliseconds so one thousand is one second I also want to set the auto reset to true and what that does is says okay when you've elapsed your time I want you to start over so so go one second and then do it again and again and again and I want to create a event for this so when the time has elapsed now let's hit tab to create that event I'll close this out now it does create the name is underscore time or underscore relapse sound like that let's just call it timer elapsed like so and there we go so now we have the the timer elapsed event I might like even create make it a little better so just call it timer elapsed like so and now it looks a little more like a normal method now events typically do have the lower case because they are attached to a type like timer but I think it's little cleaner that's where I do it okay the throw new not implement exception since I created that automatically what this does it creates a new not implemented exception inside my code because it's saying I create as code for you but I don't want you calling this thinking it's it's all done so if you ever actually call this it's gonna throw an exception which what you want until you put real code in here but we're ready to put real code in here we can get rid of the exception now in here I have a couple different things I can do but I am going to use the file append all lines method so it's create some just one line but I'll create an array equals new string array and I have one line in here which is date/time dot now dot two string like so and so even though this is not in quotes this is one string add to the string array and I can use this string array now to say file which I to control dot and add the using system to i/o so file dot append all lines we have to get up half which I'm gonna hard code in a real-world situation you probably won't put this into a config file but see temp will put in the demos folder we're at Korea file here called heartbeat dot txt so we're going to pend all lines which we only have one line that's okay I do this because if I ever want a second line it's just easier to add it to that array than it is to do the farm append all text which I have to add the new line at the end and make sure I do that every time and just ignore that I want to do it this way it's easier so what this will do is it'll pend the string date/time dot now to the end of the text file now if a text file does not exist this append all lines will create it now the path does have to exist so make sure that path is valid for your application if you run as yourself so all it gonna do every time we hit one second is gonna run this event method which creates that one line and writes it to the heartbeat text file at the end so let's see the date time every time increase by one second essentially so that's the the timer and that's the constructor at start that set the timer up but it hasn't started the timer yet and that's where we get into our public void start which just says timer dot start we're the same thing for public void stop timer dot stop so now we have our constructor which sets up a timer then we have a start method which starts a timer and a stop method which stops the timer so the service is started then that tires gonna keep ticking one second one second one second and keep range that text file when service is stopped the timer stops it doesn't write the text file anymore so that's our basically our complete service now for you you might why do you something different here talk about that a minute about what she could do in here to me do swing difference with your service the price structure will ypres much the same usually use a timer the timer allows you to dial in how much does this service run so in my case it runs every second but the reality is for a lot of services they could run every minute or every 10 minutes or every hour even so next we have to do is we actually to wire this up to be called you have this class but we're actually calling anywhere yet and that's where top shelf comes in so what I do is Russ start by saying var exit code equals host factory do control dot there to bring in top shelf so using top shelf right here so factory dot run this is where it's actually I run our service and we'll say that it it's gonna say X and let our arrow function or equals greater than which or you want to call it and apart and I call it the am before you go in here and put code and this sets up the service missus top shelf specific code they do have great documentation on the website and I'll link to that in the description but it really found their pattern pretty much me that's it's it's pretty basic because all do you want this to do is wire stuff up so X dot service and the service is going to be heartbeat that's a service we're on call and using that will say asks for service and they arrow function again I can't use X because I'm already inside of this one which uses X so s for service s dot construct using it will say heartbeat arrow function new heartbeat that called a constructor for the the heartbeat service and and when started we just say I can use the same heartbeat not capital H lowercase H and we'll say that arrow function heartbeat dot start what this is doing is just saying okay when you want to start call the start method on the heartbeat class it'll do the same thing again but instead when started it's me when stopped and we're I call the stop method so call start when started call stop when stopped and the constructor to use is the empty constructor so that sets the service up we're not quite done yet but you want to say well how do you want this service to run now a service let us bring my services back over and let's open up a service doesn't matter which one notice here these there's a startup type we'll get to that in a minute but is also who would you login ass local system account or a specific account and as other accounts as well you can use so there's different options services can run under and what those different options do is they give you different permission levels now go into all the things services can do as far as which permission levels do what I'll just do a simplest one which is run as you have your options here a network service a local system a local service we're gonna choose local system and that should give us all permissions we need now the last thing I want to do for this service is I want to setup the basic information okay let's bring the services back in we have our name nose sensor space service well that's the the friendly name for this because this service is actually called sensor service no space we can read that and that's got this description here as well which is a whole long description that tells you what this service does we want the same thing for our service so let's set up X dot set service name and this is the nospace name okay this is the machine friendly name okay so no spaces so I'll say heartbeat service now I can set the display name this is what we tell the users the name is notice I'm using a space in there and now we can set the description the description is something much larger that describes what we do so this is the sample heartbeat service used in a YouTube demo let's make sure you get these semicolon at the end so now we have all of this setup but notice I'm capturing the output of fact host factory run notice that says top shelf exit code and I'm grabbing it as exit code this will continue to run as long as the service is running but once it stops it's then grab as exit code and so I want to capture that and convert it into an int so int exit code value equals we need to cast to an int this value convert dot change type and this is the exit code exit code dot get type code so this does is exit code is a new it's gonna convert it over to an integer which we then capturing our exit code value and now when we say environment dot exit code equals exit code value that's the integer and the reason why I use exit code needs an integer and so they have mapped all the different type of exits to any new make it easy but then we have to map it back to an int in order to return that to the environment exit code so yes that's a lot of saying exit code and it might be a little confusing looking at these two lines but essentially all that's doing is converting it from a Noom to an int and passing it out and if you have to you can copy and paste these lines and they'll work every time as long as you make sure these names are consistent and if you want to change something like you call this something else I think that the I think top shall call it something else a char or something like that well you just name pre name as HR and then rename these two things as well to be a char and you're good to go so if it's a little confusing I understand but the reality is you just need to know how to convert from a new back to an int okay guess what we're done we've got our service ready to go now let's test this out by running it as just a console application so I hit start here and notice and it says okay success name display name description service and it says it's now running press ctrl C to exit and if I bring over my demos folder notice I have in C temp 10 I was a heartbeat file there was nothing for let's open that up with notepad plus plus and notepad plus plus has a fun feature under the View menu it says my during they will do is refresh this every time the file changes and notice it keeps incrementing the value as we keep writing to this text file every second so it's working their way we intended it to now let's go ahead and hit control C here and those it stops for 82 seconds was the last time he wrote to that file let's close that down turn off modern first and we're going to close this down and now we're going to do is we're going to install this service so back over here just remember that there is no service called heartbeat we call it heartbeat service so g2h oh there's no heartbeat service so I think it's gonna call something else before but anyways simple heartbeat service that's what I was thinking about where it's going to call it heartbeat service so that's the difference but Group Policy client to host guardian client service so there's no heartbeat in the middle let's go ahead and change that if we right click here and say open folder and file explorer that's gonna open up our our project file into the bin-debug there is the heartbeat service exe what I'm gonna do I'm gonna grab everything here out me the PDB file by gonna grab it anyways it's fine for what I need to do and I come over to my folder here no demos I'll create a new folder for heartbeat service and in here paste that exe now this is not the squirrel-like deployment leave like and so yes you'd want to do a more actual deployment but this is the simplest way of doing it ok this is really simple I'm gonna show you a simple way you can go on and figure out how to do the the further deployment of squirrel or I can show you in a later video but for this video you guys put us on a thumb drive and put into a folder you want to keep and the key here is this folder you can't delete it later but this is where the service is actually got run from so I've chosen this location right here for a simple heartbeat service Exe I copy that path I'm gonna open up a command prompt and let's just say run goodness actually I'm gonna do it from my run as menu and a screen flashed there from history that did the the administrative command prompt so administrative command prompt gives me all the access I need to install this it's gonna say CD and paste in that path to change directory to date location now it's called simple heartbeat service exe so to install this why you do is say simple heartbeat service dot exe install and the last can I'm going to do is say start so that'll do is uninstall this service and gonna start it too so let's run that and it says you're good to go the heartbeat services start it was installed and in fact if we come back over here and we open this back up with notepad and we've turned back on the monitoring you'll notice that the date and times are updating automatically and that's because the service is running now I just move it out of the way I could close this because it's already done notices back at the command prompt you don't have to keep this window open but I'm going to is because the fact I need get back here to make some other commands but to show you that it's installed let's refresh this list and now heartbeat service is listed here the description is correct this is a sample heartbeat service using a YouTube demo and it's his heartbeat space service and it's currently running now I could stop this and now it's stopped and if you look over here in fact it's no longer refreshing so that's that's a service in a nutshell it it's very easy to install and actually it's also very easy to uninstall that's another key feature here that's the reason I kept this open so if I want to uninstall this instead of saying simple heartbeat service install I just want to say uninstall it's saying it's already successful for removing from the system it's still wrapping up a couple things now it's completed and we're done so now to come back over here and refresh the heartbeat service is no longer there really simple to do so what we learned the Lord's really easy to install a service it's really easy creative service and it's really easy to do things with a service now obviously writing to a text file not the best use of a service especially since you probably blow it up at some point because it's just going to get too big but there are other things we can do and let's talk through some of the other things we could do one of the things you could do is you have a folder cleanup routine so for example I used my my downloads folder a lot I keep a lot of junk in there I just forget to clean it up because I download something and I just need to get cleaned out we're gonna do some of that file if I really want it otherwise it just kind of sits there and so you can actually have a service run every probably every hour even and just delete everything in the Downloads folder there's wipe it all out and maybe you only delete things that are older this certain time that way you're not gonna delete a currently downloading thing but you could delete everything that's old out maybe even once a day if you wanted to but do it automatically not something you have to think about a way to run that process so a little service another one is I have a ton of pictures I take pictures all the time and if I could have some little tool that just organized those pictures into maybe a folder by month by year so a year folder than a month folder and maybe even add a folder and they would just sort them into the right spots well I could do that using a tool where I has dump all my photos into one file or one folder and then this tool would say oh there's new folder or new files here I might take every picture file not anything else just the picture files and sort them based upon the date they were created if you get if you're you know working for a company or you're working with some system where you're getting have CSV file you could have that CSV file automatically processed just create a little folder on your desktop or somewhere that the the service watches and you dump a CSV file in there it opens it up it reads it through it parses it out and it puts it into a database and it's all just automatic there's no thought about this running process so then the next thing you do is have that folder be in your onedrive and share that out with clients or other people and they could put the csv files in there and then when onedrive downloads of csv files it processes them so i'm the kind of reverse of it it could watch a database and every time it checks and they it's gonna check once a minute or so if there's new records in a table then it could process those records for example it could email customers and then move them out of this table or you know if an idea is a helpdesk so a new person submits it helped us request it goes in the database and then this system watches that and as soon as it sees a new record the email is that person back and says your help ticket has been submitted we've got it we've got assigned and here's the information here's the you have the ID or whatever it is they've assigned to it so the lot of things you could do an automatic basis their service week great for so there's a lot of power here's a lot of stuff you could do just be careful because the other side of it is since there is so much power here there's also so much possibility that you could do something harmful for example don't leave this service running forever because it will blow that text file up and leave gigabytes in size in no time at all a sudden your claw your computer up you have no space and this file is too big to even open a notepad so don't do that one but there's a lot of things you can do there positive with this program let me know what you think of that you might want to do in your application just leave in the comments below male spark somebody else's creativity with what they want do as well all right also if you have any questions or thoughts about this leave in the comments below I'll try to get to them as soon as possible thanks for watching I hope you have a great day and as always I am Tim quarry [Music] you [Music]
Info
Channel: IAmTimCorey
Views: 113,902
Rating: undefined out of 5
Keywords: .net, C#, Visual Studio, code, programming, tutorial, training, how to, tim corey, C# training, C# tutorial, windows service, c# service, create a windows service in c#, create a windows service c# visual studio 2017, create a windows service in visual studio 2017, create a windows service to run an exe, c# topshelf, topshelf, c# topshelf service
Id: y64L-3HKuP0
Channel Id: undefined
Length: 31min 20sec (1880 seconds)
Published: Mon Dec 03 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.