How to create a Simple Windows Service in C#

Your Ad Here

We all know what a Windows Service is - a long running executable that's designed to work without user interaction. They can be configured to start when the system boots and they can be run without any users logged into the system. This tutorial is going to provide step-by-step instructions on how to build a Windows Service using C# and .NET.

The first thing you're going to want to do is create a new Console Application in Visual Studio. I like to start building services as console applications so they can easily be tested and debugged before converting them to services.

New Console Application Dialog

In order to build services, we depend on some .NET objects location in the System.ServiceProcess and System.Configuration.Install assemblies. Go ahead and add those references to your project.

Visual Studio Project References

When you created the project, Visual Studio should have created a file called Program.cs, which looks something like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyWindowsService
{
class Program
{
static void Main(string[] args)
{
}
}
}

The only thing we need to do in order to make this class into a service is make Program extend System.ServiceProcess.ServiceBase.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceProcess;
namespace MyWindowsService
{
class Program : ServiceBase
{
static void Main(string[] args)
{
}
}
}

By extending ServiceBase, we're given a bunch of service related functions we can override. At a minimum, every service should override OnStart and OnStop. These are where, as the names imply, your custom logic should go when the service is started and stopped.

class Program : ServiceBase
{
static void Main(string[] args)
{
}
protected override void OnStart(string[] args)
{
base.OnStart(args);
//TODO: place your start code here
}
protected override void OnStop()
{
base.OnStop();
//TODO: clean up any variables and stop any threads
}
}

There are several other functions beyond start and stop like pause, continue, and shutdown, but they're not needed for a basic service. For all available functions, check out the ServiceBase member list on MSDN.

Now we need to add some information about our service - like a name. Let's add a constructor to Program and put it there.

class Program : ServiceBase
{
static void Main(string[] args)
{
}
public Program()
{
this.ServiceName = "My Service";
}
protected override void OnStart(string[] args)
{
base.OnStart(args);
//TODO: place your start code here
}
protected override void OnStop()
{
base.OnStop();
//TODO: clean up any variables and stop any threads
}
}

The constructor is where you'd also set lots of other information about your service (if the default settings wouldn't work). These can include things like which events it can handle, what operation it can do (pause, stop, etc.), and what event log it should log information to (application, system, etc.). For us, however, the default settings will work just fine.

We're very close to having a finished service. All that left is to tell Windows what service to run when your application it executed. Just like normal applications, execution begins in the Main function. This is where we'll create an instance of our service and tell it to run.

class Program : ServiceBase
{
static void Main(string[] args)
{
    ServiceBase.Run(new Program());
}
public Program()
{
this.ServiceName = "My Service";
}
protected override void OnStart(string[] args)
{
base.OnStart(args);
//TODO: place your start code here
}
protected override void OnStop()
{
base.OnStop();
//TODO: clean up any variables and stop any threads
}
}

That's it! The service implementation is complete. We can't install it yet though, because we haven't implemented an installer. To do that we need to add another class to our project called MyWindowsServiceInstaller.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyWindowsService
{
class MyWindowsServiceInstaller
{
}
}

When Visual Studio creates a class for you, it doesn't automatically make it public. It's very important that this class be made public. When you install a service, the installer will look through your assembly for public classes with a specific attribute. If it's not public, it won't find it.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyWindowsService
{
public class MyWindowsServiceInstaller
{
}
}

This class needs to extend System.Configuration.Install.Installer and be given a RunInstaller attribute. This is the attribute that the service installer looks for when installing your service.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration.Install;
using System.ComponentModel;
namespace MyWindowsService
{
[RunInstaller(true)]
public class MyWindowsServiceInstaller : Installer
{
}
}

Now we need to configure how we want our service installed. We'll do this in the constructor for the class we just created.

[RunInstaller(true)]
public class MyWindowsServiceInstaller : Installer
{
public MyWindowsServiceInstaller()
{
var processInstaller = new ServiceProcessInstaller();
var serviceInstaller = new ServiceInstaller();
//set the privileges
    processInstaller.Account = ServiceAccount.LocalSystem;
    serviceInstaller.DisplayName = "My Service";
    serviceInstaller.StartType = ServiceStartMode.Manual;
//must be the same as what was set in Program's constructor
    serviceInstaller.ServiceName = "My Service";
this.Installers.Add(processInstaller);
this.Installers.Add(serviceInstaller);
}
}

This is pretty much the bare minimum when it comes to service options. We have to create a ServiceProcessInstaller and a ServiceInstaller. These two classes are responsible for installing the service. The ServiceProcessInstaller installs information common to all services, and the ServiceInstaller installs information for this specific service.

The Account property sets which privileges you'd like the service to run under. The default is User, but then we'd have to specify a username and a password to determine the account. I chose LocalSystem, which gives the service a lot (probably too much) access to the local computer.

Services are identified by name, so you have to ensure serviceInstaller.ServiceName is exactly the same as what you set in the constructor of Program. The rest of the options are pretty obvious. All that's left is to add our two installers to the Installers collection.

We're done! All that's left to do now is install the service.

Installing The Service

Services are installed using a tool from Microsoft called installutil.exe. This tool is free and is probably already on your computer. I doubt it's in your system path, so you might want to do a quick search for it and add it to your environment variables before continuing.

All you have to do to install your service is open a command prompt, cd to your Release directory, and type:

installutil MyWindowsService.exe

installutil output

Your service is now installed and ready to go. If you bring up your services manager, you should see one labeled "My Service". Of course, if you start it, nothing will happen since we didn't actually put any code in the OnStart function.

Windows Service List

If you want to uninstall the service, you can do so with the same utility but with the "-u" flag.

installutil -u MyWindowsService.exe

There's a lot of power that we haven't even touched in Windows Services, but this tutorial should hopefully give you a starting point on which you can expand and build some much more complex solutions. All of the example code has been attached as a Visual Studio 2008 solution.

Source:http://www.switchonthecode.com

Subscribe
Posted in Labels: , kick it on DotNetKicks.com | 4 comments

How To Configure And Use Visual Studio Macros

Your Ad Here

Microsoft Visual Studio has pretty much every operation you'd ever need right at your fingertips through the built in keystrokes. However, there are times when you'd like the text editor to do something that isn't built in. This is where macros come in. Macros can be wired up to keystrokes and can do pretty much unlimited modifications to your text - as long as you're willing to program it. In this tutorial, I'm going to demonstrate how to import an existing macro and configure a keystroke for it.

I'm not going to show you how to write macros in this tutorial. For almost anything you need, someone has already probably written it anyway. It's just a Google search away. At some point in the future, however, I'll go into the details on how to write a custom macro.

The macro I'm going to use in this tutorial is one I found especially useful a while ago that reverses the statements on either side of an assignment operator. So this:

myVariable = myOtherVariable;

Turns into this:

myOtherVariable = myVariable;

This macro is hosted on CodeProject and was written by someone named John C.

All of Visual Studio's macros can be found using the Macro Explorer, which can be accessed through the Tools menu.

VS Macros Menu

If you've never added a macro to Visual Studio, the explorer should look something like this:

VS Macro Explorer

Macros are placed into projects and grouped together in modules. Visual Studio has already created and added the MyMacros project with one module called Module1. As you can see, however, there are no macros in that module. This is where we're going to add the macro I linked to above. The first thing you'll want to do is right-mouse click on Module1 and add a new macro.

New Macro Menu

As soon as you hit that menu item, the Macro IDE will display. This is where you'd program your macro, but in our case, this is where we past John C's macro.

The Macro IDE

Visual Studio went ahead and put a blank macro in the module for you, but all we have to do is simply replace all of the text with John's macro.

Macro IDE with content

It's not quite ready to use yet. John named his module JohnUtils, but ours is named Module1. Before this macro can be used, we need to change the name of the module in John's code to Module1.

Public Module JohnUtils

Needs to change to:

Public Module Module1

That's it. Now when you save and close the Macro IDE, the new macro will be visible in the macro explorer.

New Macro Explorer Contents

Theoretically, this macro is ready to run. If you select some lines of code, right-mouse click on the macro and select "run", it will execute on the lines you've selected. However, I don't want to have to use the mouse to run my macros. I want to hook them up to keystrokes. Fortunately, Visual Studio has a nice little keyboard editor where you can do just that. The first thing we need to do is bring up the keyboard editor, which is located under the Tools/Options menu.

VS Keboard Editor

That list of commands contains every command available to Visual Studio - which is a lot. It also contains all of your macros. You'll want to filter the list by simply typing "macro" in the text box above the commands.

Keyboard Editor Filtered

As soon as you find the macro you want to hook up to a keystroke, simply click the shortcut keys text box and enter your keystroke. It can sometimes be difficult to find a keystroke not already used by Visual Studio, but from what I've learned, control+0 is not used anywhere. There's nothing wrong with using an existing keystroke, but it will replace whatever the original command was, so choose wisely. Once your keystroke is entered, just click the "Assign" button and everything is done. Now whenever you hit that keystroke, the selected macro will run.

Keyboard Editor Shortcut Keys Closeup

There's still a lot to cover when it comes to macros, but this tutorial should give you a good introduction on how to import and use an existing macro. Look forward to more in-depth tutorials in the future on how to write your own Visual Studio macros. As always, questions and comments are always welcome.

Source:http://www.switchonthecode.com

Subscribe
Posted in Labels: , kick it on DotNetKicks.com | 15 comments

How to make custom code snippet in Visual Studio

Your Ad Here

A cool feature that Visual Studio has is the concept of a "code snippet." You know those chunks of code that you need to type over and over again throughout your code? Perhaps your logging calls, or even more mundane than that, the generic code for try-catch blocks. Well, the folks behind Visual Studio came up with an idea to help keep that concept to a minimum - code snippets. Essentially, it is like having that repetitive code always on your clipboard, ready to "paste" into your code - except it is way more powerful than just copying and pasting code.

If you have used Visual Studio for a while, you have probably run across some of the standard code snippets - you may even be using them intentionally all the time. Today we are going to look at first how to use snippets in your code (really easy to do), and then we are going to take a look at how you can write your own code snippets. It is in writing your own code snippets that you really start to see the power of the code snippet system, and hopefully after today's tutorial you can go off and streamline your own work flow by writing a couple snippets for yourself.

So first, lets take a look at adding existing snippets to code. There are a number of ways to do this in Visual Studio, the most common of which is to use regular intellisense. For instance, below we are about to add a for loop snippet:

Intellisense Dropdown

Visual Studio Context Menu

You can also get to a menu of just snippets by using the right click menu and choosing the option "Insert Snippet". And, of course, if the mouse is too much work for you, there is a keyboard shortcut that will bring up this menu directly - ctrl-k + ctrl-x. Below, you can see the menu in action as we choose again to insert the for loop snippet.

Intellisense For Snippets

You might be wondering "why would I want to use a for loop snippet?" - cause after all, a for loop it really isn't that complex to write. Well, what it does is give you the full for loop framework with only a couple keystrokes. This is what inserting the for loop snippet will give you:

Example Snippet Insert

If your not convinced that saved you that many keystrokes, theres another handy feature. See how the first "i" is highlighted and the second two are surrounded by dotted lines? That means that those variables are supposed to be the same - which mean that if you edit the first "i" right after you insert the code snippet, the other "i"s change to the new name automatically. That 'linkage' isn't kept around forever, as soon as you go and edit something other than the snippet, those dotted lines go away and any changes that you make later on don't automatically get propagated. But pretty cool, eh?

Another handy feature of snippets, is that for many of them you not only have the ability to "insert" them, you also have the ability to surround other code with them. For instance, if you had highlighted some code, done a right click, you can pick "Surround With.." from that right click menu (it is right below "Insert Snippet" in the right click menu pictured above). Then, only the code snippets that can do a "surround" operation will appear, and you can pick one and add it. And surround does exactly what you might expect - for instance, in the case of the for loop, it will surround the code you had highlighted with the for loop structure pictured above. The keyboard shortcut for this "Surround With" action is ctrl-k + ctrl-s.

Ok, enough on using code snippets - lets try and write one! For this tutorial, we are going to create a really simple snippet for performance timing. It will work as both an "insert" and "surround" code snippet, and this will be the code that it produces:

Our Snippet Example

All it does is surround a block of code with a line at the start that captures the start time, and a line at the end that prints out the difference between the start time and the current time. There are two blocks that are set as editable - first, the name of the startTime variable (which will also change the startTime reference at the end of the snippet), and the "My function" part of the string, so that you can put a more descriptive name of exactly what you are timing.

So how do we do this? Well, all a code snippet is is an xml file - and a relatively simple one at that. Here is the basic outline of a code snippet xml file:

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
</Header>
<Snippet>
</Snippet>
</CodeSnippet>
</CodeSnippets>

Pretty standard initial xml declaration stuff. There is a CodeSnippets block that can contain one or more CodeSnippet blocks. Each CodeSnippet block has a Header block (for stuff like title and author) and a Snippet block (for the actual snippet code). Below is an example Header block:

<Header>
<Title>Simple Performance Timing</Title>
<Shortcut>Timing</Shortcut>
<Description>
    Code snippet for surrounding a section of code with
    some performance timing.
</Description>
<Author>Switch On The Code</Author>
<SnippetTypes>
<SnippetType>SurroundsWith</SnippetType>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>

Nothing crazy here - we give the snippet a title, a shortcut (which is what shows up in all the intellisense menus), a description and an author. With the SnippetTypes block, you declare what type(s) this snippet supports - in this case, it can do both "SurroundsWith" and "Expansion" (i.e., insertion). So onto the actual definition of the snippet:

<Snippet>
<Declarations>
<Literal>
<ID>startTime</ID>
<ToolTip>Beginning Time Variable</ToolTip>
<Default>startTime</Default>
</Literal>
<Literal>
<ID>message</ID>
<ToolTip>Replace This With Your Description</ToolTip>
<Default>My function</Default>
</Literal>
<Literal Editable="false">
<ID>DiagnosticsDebug</ID>
<Function>
        SimpleTypeName(global::System.Diagnostics.Debug)
</Function>
</Literal>
</Declarations>
<Code Language="CSharp">
<![CDATA[
   long $startTime$ = Environment.TickCount;
   $selected$ $end$
   $DiagnosticsDebug$.WriteLine(String.Format(
       "$message$ took {0} ticks.", Environment.TickCount - $startTime$));
   ]]>
</Code>
</Snippet>

There are two main sections here, Declarations and Code. It is in the declarations that we can declare the special variables that appear in multiple places in the code (like startTime), or variables that just need to be edited when the snippet appears (like the "My function" string). As you can see, the first literal that we declare is startTime - we give it a name to refer to it as in the snippet (in this case "startTime"), a tool tip that will appear for the user describing what the variable is, and a default value. We can then use this literal down inside the code snippet itself - refering to it as $startTime$.

The next literal is just as simple - it is the placeholder for the "My function" string, and we call it message. You can see it down in the code in the output string refered to as $message$. The third literal is kind of weird. It is not editable by the user (declared by the Editable="false" attribute), and it has a Function tag. What this allows us to do is have the snippet figure out automatically if it should output the code using the full reference System.Diagnostics.Debug or just the shorthand Debug. If already have a using System.Diagnostics; statement in your code, then there is no need for the full declaration, and the snippet realizes this. The work is actually done in that SimpleTypeName function in the Function tag. You can read more about this and the other available functions for use in snippets in the MSDN docs.

And that brings us down to the actual code inside the Code tag. Most of this is the actual code that will appear after insertion, and we already explained what $startTime$ and $message$. There are two other oddities here - $selected$ and $end$. They are both reserved identifiers in code snippets - $selected represents whatever the user had highlighted when they decided to do a "Surround With" snippet, and $end$ signifies where the caret should go after the user finishes inserting the snippet.

And that is about it for defining a code snippet. There are, of course, a number of other optional attributes/tags that we did not hit on with this simple snippet, but the MSDN docs do a pretty good job of explaining them. Below is the entire timing code snippet as a single block:

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>Simple Performance Timing</Title>
<Shortcut>Timing</Shortcut>
<Description>
        Code snippet for surrounding a section of code
        with some performance timing.
</Description>
<Author>Switch On The Code</Author>
<SnippetTypes>
<SnippetType>SurroundsWith</SnippetType>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>startTime</ID>
<ToolTip>Beginning Time Variable</ToolTip>
<Default>startTime</Default>
<Type>long</Type>
</Literal>
<Literal>
<ID>message</ID>
<ToolTip>Replace This With Your Description</ToolTip>
<Default>My function</Default>
</Literal>
<Literal Editable="false">
<ID>DiagnosticsDebug</ID>
<Function>
            SimpleTypeName(global::System.Diagnostics.Debug)
</Function>
</Literal>
</Declarations>
<Code Language="CSharp">
<![CDATA[
       long $startTime$ = Environment.TickCount;
       $selected$ $end$
       $DiagnosticsDebug$.WriteLine(String.Format(
           "$message$ took {0} ticks.", Environment.TickCount - $startTime$));
       ]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>

But wait! You might be wondering how you actually add a code snippet for Visual Studio to use after you have created it. You will want to go up to the Tools menu and choose Code Snippets Manager:

Visual Studio Tools Menu

Once you click on that, you get the Code Snippets Manager dialog:

Visual Studio Code Snippet Manager

And from here it is pretty self explanatory - you can import snippet files (using the aptly named "Import" button), or you can add a folder's worth (in which case, as you add and remove snippets from that folder, they will appear/disappear from the available snippets).

I hope you've enjoyed this introduction to Visual Studio snippets. There are a number of resources out there for finding code snippets that other people have written, such as Got Code Snippets. If you have any questions about writing your own snippets, or cool uses for them, please leave a comment.

Source:http://www.switchonthecode.com

Subscribe
Posted in Labels: , kick it on DotNetKicks.com | 3 comments

ASP.NET, HTML, JavaScript Snippet Support (VS 2010 and .NET 4.0 Series)

Your Ad Here

ASP.NET, HTML, JavaScript Snippet Support (VS 2010 and .NET 4.0 Series)

This is the sixth in a series of blog posts I’m doing on the upcoming VS 2010 and .NET 4 release.

Today’s post covers another useful improvement in VS 2010 – HTML/ASP.NET/JavaScript snippet support. Snippets allow you to be more productive within source view by allowing you to create chunks of code and markup that you can quickly apply and use in your application with a minimum of character typing.

Visual Studio has supported the concept of “snippets” for VB and C# in previous releases – but not for HTML, ASP.NET markup and JavaScript. With VS 2010 we now support snippets for these content types as well.

Using ASP.NET Snippets

Let’s walkthrough how we can use snippets to quickly implement a common security scenario. Specifically, we’ll implement the functionality necessary to display either a “[ Login ]” link or a “[ Welcome UserName ]” message at the the top right of a site depending on whether or not the user is logged in:

step1

The above functionality is automatically added for you when you create a project using the new ASP.NET Project Starter Template in VS 2010. For the purpose of this walkthrough, though, we’ll assume we are starting with a blank master page and will build it entirely from scratch.

We’ll start by adding a standard

element to a master page, and then position our cursor within it:

step2

We are going to use the built-in control to help implement our scenario. The control is a templated control (first introduced with ASP.NET 2.0) that allows us to easily switch between “Anonymous” and “LoggedIn” templates that automatically display depending on whether the user is authenticated. Rather than type the markup manually, we’ll instead use the new snippet support in VS 2010.

Typing in “

step3

We’ll select the built-in “loginview” code snippet from the above list and hit the “tab” key to complete it:

Want to read full article, Go to Scott Blog

Happy Reading



Subscribe
Posted in Labels: , kick it on DotNetKicks.com | 7 comments

C# Sharp Programming Basics Adding Sound - Part One

Your Ad Here

Subscribe
Posted in Labels: , kick it on DotNetKicks.com | 0 comments

Making a simple Calculator in C#(C sharp)

Your Ad Here

Subscribe
Posted in Labels: , kick it on DotNetKicks.com | 42 comments

C# Tutorial: Writing If Statements and Boolean Tests

Your Ad Here

Subscribe
Posted in Labels: , kick it on DotNetKicks.com | 0 comments

An Introduction to Test Driven Development in C#

Your Ad Here

Subscribe
Posted in Labels: , kick it on DotNetKicks.com | 0 comments

Inheriting from Forms in Visual Studio using C#

Your Ad Here

Subscribe
Posted in Labels: , kick it on DotNetKicks.com | 0 comments

What is new .NET RIA CTP2009 July?

Your Ad Here

Here is a list of what is new in the July 2009 Preview:


1. A new and improved model for handling operations on the client – you can more easily specify callback/event for an operation, track its status and cancel it.

2. Improved class library support
3. Extensibility points in generated code
4. Cleaner user model and better extensibility support for Application services
5. Better DomainDatasource capability for handling paging and updates.
6. Cleaner shared code support


7. First wave of ADO.NET Data Services alignment (add a DomainService to DataService for writing app logic / expose DomainService as DataService).
8. Bug fixes and initial performance improvement on the server

Subscribe
Posted in Labels: kick it on DotNetKicks.com | 0 comments

How to use C# Events

Your Ad Here

Subscribe
Posted in Labels: , kick it on DotNetKicks.com | 0 comments

How to use Visual Inheritance in VS2010 .

Your Ad Here

How to use Visual Inheritance in VS2010?

First of all i would like to explain a bit about the inheritance, Inheritance is one of the most important property of Object Oriented Programming language ,by which we reuse the code and extend the existing functionality where there is a relation of "IS A" exists in two classes . For example

Lets take an example in C#

public class base
{
public base(){

System.out.println("base class Constructor");
}
public void print ()
{
System.out.println("Base Class");
}
}
public class derived :base
{
public derived()
{

base.base();
System.out.println("derived class");

}
public void printEx(){

System.out.println("Printinng extended functionality");

}

}

This is how we use inheritance in C# but we are lacking this feature in Windows Forms applications where we want to reuse the existing windows forms to extend the functionality.This feature is available now in VS2010 where we can use our existing Win Form as base form to inherit from , thats called
visual inheritance.


Steps to use Visual inheritance in VS2010

1: Create a Windows Form project in VS2010
2: By default one Win Form will be added with name Form1.cs or vb. whatever language you use for creating Win Apps
3: Design this form
4: Build the project so that DLL is build for this project
5: Now add one more Win Form to project and select Inherited Form as given below in figure.


Note : if you dont compile your Form1.cs than you will not be able to add Form1.cs as base form to inherit from.
6: Now you will see that your Form2.cs will have all the controls of your base Form1.cs on your Form2.cs

Now question arises, how to access the controls of base class ie Form1.cs.

1: Best practices say that you should provide public getter and setter on the base class.
or
2: You can change the access modifier of base class(Form1.cs) control to Public or Protected as per your design .

Now build the application and run it .

Happy Coding.

Subscribe
Posted in Labels: , kick it on DotNetKicks.com | 3 comments