├── EasyService4Net.Example
├── App.config
├── ServiceInternalClasses.cs
├── Program.cs
├── Properties
│ └── AssemblyInfo.cs
├── app.manifest
└── EasyService4Net.Example.csproj
├── EasyService4Net
├── ServiceInternals
│ ├── InternalService.cs
│ └── ProjectInstaller.cs
├── RegistryManipulator.cs
├── Properties
│ └── AssemblyInfo.cs
├── EasyService4Net.csproj
├── WindowsServiceManager.cs
└── EasyService.cs
├── LICENSE
├── EasyService4Net.sln
├── .gitattributes
└── .gitignore
/EasyService4Net.Example/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/EasyService4Net.Example/ServiceInternalClasses.cs:
--------------------------------------------------------------------------------
1 | using EasyService4Net.ServiceInternals;
2 |
3 | namespace EasyService4Net.Example
4 | {
5 | public class EasyServiceInstaller : ProjectInstaller { }
6 | public class EasyServiceService : InternalService { }
7 | }
8 |
--------------------------------------------------------------------------------
/EasyService4Net.Example/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 |
4 | namespace EasyService4Net.Example
5 | {
6 | class Program
7 | {
8 | static void Main(string[] args)
9 | {
10 | var easyService = new EasyService();
11 |
12 | easyService.OnServiceStarted += () =>
13 | {
14 | Console.WriteLine("Hello World!");
15 | File.WriteAllText("C:\\exampleFile.txt", "Hello World!");
16 | };
17 |
18 | easyService.Run(args);
19 | }
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/EasyService4Net/ServiceInternals/InternalService.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.ServiceProcess;
5 | using System.Text;
6 | using System.Threading.Tasks;
7 |
8 | namespace EasyService4Net.ServiceInternals
9 | {
10 | public class InternalService : ServiceBase
11 | {
12 | internal static event Action OsStarted;
13 | internal static event Action OsStopped;
14 |
15 | protected override void OnStart(string[] args)
16 | {
17 | OsStarted.Invoke();
18 | }
19 |
20 | protected override void OnStop()
21 | {
22 | OsStopped.Invoke();
23 | }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2015 TheCodeCleaner
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
23 |
--------------------------------------------------------------------------------
/EasyService4Net/RegistryManipulator.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.Win32;
2 |
3 | namespace EasyService4Net
4 | {
5 | internal class RegistryManipulator
6 | {
7 | private readonly string _serviceRegistryPath;
8 | private const string Imagepath = "ImagePath";
9 | private const string MinusService = " -service";
10 |
11 | public RegistryManipulator(string serviceName)
12 | {
13 | _serviceRegistryPath = @"SYSTEM\CurrentControlSet\services\" + serviceName;
14 | }
15 |
16 | internal void RemoveMinusServiceFromRegistry()
17 | {
18 | var key = Registry.LocalMachine.OpenSubKey(_serviceRegistryPath, true);
19 | var path = key.GetValue(Imagepath).ToString().Replace(MinusService, "");
20 | key.SetValue(Imagepath, path);
21 | key.Close();
22 | }
23 |
24 | internal void AddMinusServiceToRegistry()
25 | {
26 | var key = Registry.LocalMachine.OpenSubKey(_serviceRegistryPath, true);
27 | var path = key.GetValue(Imagepath) + MinusService;
28 | key.SetValue(Imagepath, path);
29 | key.Close();
30 | }
31 |
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/EasyService4Net/ServiceInternals/ProjectInstaller.cs:
--------------------------------------------------------------------------------
1 | using System.ComponentModel;
2 | using System.Configuration.Install;
3 | using System.ServiceProcess;
4 |
5 | namespace EasyService4Net.ServiceInternals
6 | {
7 | [RunInstaller(true)]
8 | public class ProjectInstaller : Installer
9 | {
10 | private static string _serviceDisplayName;
11 | private static string _serviceName;
12 |
13 | public static void InitInstaller(string serviceDisplayName, string serviceName)
14 | {
15 | _serviceDisplayName = serviceDisplayName;
16 | _serviceName = serviceName;
17 | }
18 |
19 | public ProjectInstaller()
20 | {
21 | var serviceProcessInstaller = new ServiceProcessInstaller
22 | {
23 | Account = ServiceAccount.LocalSystem,
24 | Password = null,
25 | Username = null
26 | };
27 |
28 | var serviceInstaller = new ServiceInstaller
29 | {
30 | DisplayName = _serviceDisplayName,
31 | ServiceName = _serviceName,
32 | StartType = ServiceStartMode.Automatic
33 | };
34 |
35 | Installers.Add(serviceProcessInstaller);
36 | Installers.Add(serviceInstaller);
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/EasyService4Net/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("EasyService4Net")]
9 | [assembly: AssemblyDescription("Make Windows Service Easily")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("EasyService4Net")]
13 | [assembly: AssemblyCopyright("Copyright Code Cleaner© 2015")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("c9ffd595-d558-4ece-966d-ccd420142b45")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.*")]
36 |
--------------------------------------------------------------------------------
/EasyService4Net.Example/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("EasyService4Net.Example")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("EasyService4Net.Example")]
13 | [assembly: AssemblyCopyright("Copyright © 2015")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("7ef9d3ab-eae2-496b-b444-1fcdbfff719d")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/EasyService4Net.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 2013
4 | VisualStudioVersion = 12.0.30501.0
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyService4Net", "EasyService4Net\EasyService4Net.csproj", "{F638D0F4-4505-4CA6-992D-A76683F5BC5A}"
7 | EndProject
8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyService4Net.Example", "EasyService4Net.Example\EasyService4Net.Example.csproj", "{DA4B7970-44D3-4F2F-9132-922C1BB2FE27}"
9 | EndProject
10 | Global
11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
12 | Debug|Any CPU = Debug|Any CPU
13 | Release|Any CPU = Release|Any CPU
14 | EndGlobalSection
15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
16 | {F638D0F4-4505-4CA6-992D-A76683F5BC5A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
17 | {F638D0F4-4505-4CA6-992D-A76683F5BC5A}.Debug|Any CPU.Build.0 = Debug|Any CPU
18 | {F638D0F4-4505-4CA6-992D-A76683F5BC5A}.Release|Any CPU.ActiveCfg = Release|Any CPU
19 | {F638D0F4-4505-4CA6-992D-A76683F5BC5A}.Release|Any CPU.Build.0 = Release|Any CPU
20 | {DA4B7970-44D3-4F2F-9132-922C1BB2FE27}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
21 | {DA4B7970-44D3-4F2F-9132-922C1BB2FE27}.Debug|Any CPU.Build.0 = Debug|Any CPU
22 | {DA4B7970-44D3-4F2F-9132-922C1BB2FE27}.Release|Any CPU.ActiveCfg = Release|Any CPU
23 | {DA4B7970-44D3-4F2F-9132-922C1BB2FE27}.Release|Any CPU.Build.0 = Release|Any CPU
24 | EndGlobalSection
25 | GlobalSection(SolutionProperties) = preSolution
26 | HideSolutionNode = FALSE
27 | EndGlobalSection
28 | EndGlobal
29 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | ###############################################################################
2 | # Set default behavior to automatically normalize line endings.
3 | ###############################################################################
4 | * text=auto
5 |
6 | ###############################################################################
7 | # Set default behavior for command prompt diff.
8 | #
9 | # This is need for earlier builds of msysgit that does not have it on by
10 | # default for csharp files.
11 | # Note: This is only used by command line
12 | ###############################################################################
13 | #*.cs diff=csharp
14 |
15 | ###############################################################################
16 | # Set the merge driver for project and solution files
17 | #
18 | # Merging from the command prompt will add diff markers to the files if there
19 | # are conflicts (Merging from VS is not affected by the settings below, in VS
20 | # the diff markers are never inserted). Diff markers may cause the following
21 | # file extensions to fail to load in VS. An alternative would be to treat
22 | # these files as binary and thus will always conflict and require user
23 | # intervention with every merge. To do so, just uncomment the entries below
24 | ###############################################################################
25 | #*.sln merge=binary
26 | #*.csproj merge=binary
27 | #*.vbproj merge=binary
28 | #*.vcxproj merge=binary
29 | #*.vcproj merge=binary
30 | #*.dbproj merge=binary
31 | #*.fsproj merge=binary
32 | #*.lsproj merge=binary
33 | #*.wixproj merge=binary
34 | #*.modelproj merge=binary
35 | #*.sqlproj merge=binary
36 | #*.wwaproj merge=binary
37 |
38 | ###############################################################################
39 | # behavior for image files
40 | #
41 | # image files are treated as binary by default.
42 | ###############################################################################
43 | #*.jpg binary
44 | #*.png binary
45 | #*.gif binary
46 |
47 | ###############################################################################
48 | # diff behavior for common document formats
49 | #
50 | # Convert binary document formats to text before diffing them. This feature
51 | # is only available from the command line. Turn it on by uncommenting the
52 | # entries below.
53 | ###############################################################################
54 | #*.doc diff=astextplain
55 | #*.DOC diff=astextplain
56 | #*.docx diff=astextplain
57 | #*.DOCX diff=astextplain
58 | #*.dot diff=astextplain
59 | #*.DOT diff=astextplain
60 | #*.pdf diff=astextplain
61 | #*.PDF diff=astextplain
62 | #*.rtf diff=astextplain
63 | #*.RTF diff=astextplain
64 |
--------------------------------------------------------------------------------
/EasyService4Net.Example/app.manifest:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
57 |
58 |
59 |
--------------------------------------------------------------------------------
/EasyService4Net/EasyService4Net.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {F638D0F4-4505-4CA6-992D-A76683F5BC5A}
8 | Library
9 | Properties
10 | EasyService4Net
11 | EasyService4Net
12 | v4.5
13 | 512
14 |
15 |
16 | true
17 | full
18 | false
19 | bin\Debug\
20 | DEBUG;TRACE
21 | prompt
22 | 4
23 |
24 |
25 | pdbonly
26 | true
27 | bin\Release\
28 | TRACE
29 | prompt
30 | 4
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 | Component
49 |
50 |
51 | Component
52 |
53 |
54 |
55 |
56 |
63 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 |
4 | # User-specific files
5 | *.suo
6 | *.user
7 | *.sln.docstates
8 |
9 | # Build results
10 |
11 | [Dd]ebug/
12 | [Rr]elease/
13 | x64/
14 | build/
15 | [Bb]in/
16 | [Oo]bj/
17 |
18 | # Enable "build/" folder in the NuGet Packages folder since NuGet packages use it for MSBuild targets
19 | !packages/*/build/
20 |
21 | # MSTest test Results
22 | [Tt]est[Rr]esult*/
23 | [Bb]uild[Ll]og.*
24 |
25 | *_i.c
26 | *_p.c
27 | *.ilk
28 | *.meta
29 | *.obj
30 | *.pch
31 | *.pdb
32 | *.pgc
33 | *.pgd
34 | *.rsp
35 | *.sbr
36 | *.tlb
37 | *.tli
38 | *.tlh
39 | *.tmp
40 | *.tmp_proj
41 | *.log
42 | *.vspscc
43 | *.vssscc
44 | .builds
45 | *.pidb
46 | *.log
47 | *.scc
48 |
49 | # Visual C++ cache files
50 | ipch/
51 | *.aps
52 | *.ncb
53 | *.opensdf
54 | *.sdf
55 | *.cachefile
56 |
57 | # Visual Studio profiler
58 | *.psess
59 | *.vsp
60 | *.vspx
61 |
62 | # Guidance Automation Toolkit
63 | *.gpState
64 |
65 | # ReSharper is a .NET coding add-in
66 | _ReSharper*/
67 | *.[Rr]e[Ss]harper
68 |
69 | # TeamCity is a build add-in
70 | _TeamCity*
71 |
72 | # DotCover is a Code Coverage Tool
73 | *.dotCover
74 |
75 | # NCrunch
76 | *.ncrunch*
77 | .*crunch*.local.xml
78 |
79 | # Installshield output folder
80 | [Ee]xpress/
81 |
82 | # DocProject is a documentation generator add-in
83 | DocProject/buildhelp/
84 | DocProject/Help/*.HxT
85 | DocProject/Help/*.HxC
86 | DocProject/Help/*.hhc
87 | DocProject/Help/*.hhk
88 | DocProject/Help/*.hhp
89 | DocProject/Help/Html2
90 | DocProject/Help/html
91 |
92 | # Click-Once directory
93 | publish/
94 |
95 | # Publish Web Output
96 | *.Publish.xml
97 |
98 | # NuGet Packages Directory
99 | ## TODO: If you have NuGet Package Restore enabled, uncomment the next line
100 | #packages/
101 |
102 | # Windows Azure Build Output
103 | csx
104 | *.build.csdef
105 |
106 | # Windows Store app package directory
107 | AppPackages/
108 |
109 | # Others
110 | sql/
111 | *.Cache
112 | ClientBin/
113 | [Ss]tyle[Cc]op.*
114 | ~$*
115 | *~
116 | *.dbmdl
117 | *.[Pp]ublish.xml
118 | *.pfx
119 | *.publishsettings
120 |
121 | # RIA/Silverlight projects
122 | Generated_Code/
123 |
124 | # Backup & report files from converting an old project file to a newer
125 | # Visual Studio version. Backup files are not needed, because we have git ;-)
126 | _UpgradeReport_Files/
127 | Backup*/
128 | UpgradeLog*.XML
129 | UpgradeLog*.htm
130 |
131 | # SQL Server files
132 | App_Data/*.mdf
133 | App_Data/*.ldf
134 |
135 |
136 | #LightSwitch generated files
137 | GeneratedArtifacts/
138 | _Pvt_Extensions/
139 | ModelManifest.xml
140 |
141 | # =========================
142 | # Windows detritus
143 | # =========================
144 |
145 | # Windows image file caches
146 | Thumbs.db
147 | ehthumbs.db
148 |
149 | # Folder config file
150 | Desktop.ini
151 |
152 | # Recycle Bin used on file shares
153 | $RECYCLE.BIN/
154 |
155 | # Mac desktop service store files
156 | .DS_Store
157 |
--------------------------------------------------------------------------------
/EasyService4Net.Example/EasyService4Net.Example.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {DA4B7970-44D3-4F2F-9132-922C1BB2FE27}
8 | Exe
9 | Properties
10 | EasyService4Net.Example
11 | EasyService4Net.Example
12 | v4.5
13 | 512
14 |
15 |
16 | AnyCPU
17 | true
18 | full
19 | false
20 | bin\Debug\
21 | DEBUG;TRACE
22 | prompt
23 | 4
24 |
25 |
26 | AnyCPU
27 | pdbonly
28 | true
29 | bin\Release\
30 | TRACE
31 | prompt
32 | 4
33 |
34 |
35 | app.manifest
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 | Component
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 | {F638D0F4-4505-4CA6-992D-A76683F5BC5A}
62 | EasyService4Net
63 |
64 |
65 |
66 |
73 |
--------------------------------------------------------------------------------
/EasyService4Net/WindowsServiceManager.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections;
3 | using System.Configuration.Install;
4 | using System.Reflection;
5 | using System.ServiceProcess;
6 |
7 | namespace EasyService4Net
8 | {
9 | internal class WindowsServiceManager
10 | {
11 | #region Fields
12 |
13 | private readonly string _serviceDisplayName;
14 |
15 | #endregion
16 |
17 | #region C'tor
18 |
19 | public WindowsServiceManager(string serviceDisplayName)
20 | {
21 | _serviceDisplayName = serviceDisplayName;
22 | }
23 |
24 | #endregion
25 |
26 | #region Internal
27 |
28 | internal bool IsInstalled()
29 | {
30 | using (var controller = new ServiceController(_serviceDisplayName))
31 | {
32 | try
33 | {
34 | var status = controller.Status;
35 | }
36 | catch (Exception)
37 | {
38 | return false;
39 | }
40 | return true;
41 | }
42 | }
43 |
44 | internal void Install()
45 | {
46 | if (IsInstalled()) return;
47 | using (var installer = GetInstaller())
48 | {
49 | IDictionary state = new Hashtable();
50 | try
51 | {
52 | installer.Install(state);
53 | installer.Commit(state);
54 | }
55 | catch
56 | {
57 | try
58 | {
59 | installer.Rollback(state);
60 | }
61 | catch { }
62 | throw;
63 | }
64 | }
65 | }
66 |
67 | internal void UnInstall()
68 | {
69 | if (!IsInstalled()) return;
70 | using (var installer = GetInstaller())
71 | {
72 | IDictionary state = new Hashtable();
73 | installer.Uninstall(state);
74 | }
75 | }
76 |
77 | internal void Start()
78 | {
79 | if (!IsInstalled()) return;
80 | using (var controller = new ServiceController(_serviceDisplayName))
81 | {
82 | if (controller.Status == ServiceControllerStatus.Running) return;
83 | controller.Start();
84 |
85 | controller.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(10));
86 | }
87 | }
88 |
89 | internal void Stop()
90 | {
91 | if (!IsInstalled()) return;
92 | using (var controller = new ServiceController(_serviceDisplayName))
93 | {
94 | if (controller.Status == ServiceControllerStatus.Stopped) return;
95 | controller.Stop();
96 | controller.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(10));
97 | }
98 | }
99 |
100 | #endregion
101 |
102 | #region Private
103 |
104 | private static AssemblyInstaller GetInstaller()
105 | {
106 | var serviceExeName = Assembly.GetEntryAssembly().ManifestModule.Name;
107 | return new AssemblyInstaller(serviceExeName, null) { UseNewContext = true };
108 | }
109 |
110 | #endregion
111 | }
112 | }
113 |
--------------------------------------------------------------------------------
/EasyService4Net/EasyService.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Reflection;
3 | using System.ServiceProcess;
4 | using EasyService4Net.ServiceInternals;
5 |
6 | namespace EasyService4Net
7 | {
8 | public class EasyService
9 | {
10 | #region Events
11 |
12 | public event Action OnServiceStarted;
13 | public event Action OnServiceStopped;
14 |
15 | #endregion
16 |
17 | #region Fields
18 |
19 | private readonly string _serviceDisplayName;
20 | private readonly WindowsServiceManager _serviceManager;
21 | private readonly RegistryManipulator _registryManipulator;
22 |
23 | #endregion
24 |
25 | #region C'tor
26 |
27 | ///
28 | ///
29 | ///
30 | /// null for using the assembly name.
31 | /// null for using the assembly name.
32 | public EasyService(string serviceDisplayName = null, string serviceName = null)
33 | {
34 | var assemblyName = Assembly.GetEntryAssembly().GetName().Name;
35 | _serviceDisplayName = serviceDisplayName ?? assemblyName;
36 | serviceName = serviceName ?? assemblyName;
37 |
38 | _serviceManager = new WindowsServiceManager(_serviceDisplayName);
39 | _registryManipulator = new RegistryManipulator(serviceName);
40 |
41 | InternalService.OsStarted += Start;
42 | InternalService.OsStopped += Stop;
43 | ProjectInstaller.InitInstaller(_serviceDisplayName,serviceName);
44 | }
45 |
46 | #endregion
47 |
48 | #region Public
49 |
50 | public void Run(string[] args)
51 | {
52 | if (args.Length == 0)
53 | {
54 | RunConsole();
55 | return;
56 | }
57 |
58 | switch (args[0])
59 | {
60 | case "-service":
61 | RunService();
62 | break;
63 | case "-install":
64 | InstallService();
65 | break;
66 | case "-uninstall":
67 | UnInstallService();
68 | break;
69 | default:
70 | throw new Exception(args[0] + " is not a valid command!");
71 | }
72 | }
73 |
74 | #endregion
75 |
76 | #region Private
77 |
78 | private void RunConsole()
79 | {
80 | Start();
81 | Console.WriteLine("Press any key to exit...");
82 | Console.ReadLine();
83 | Stop();
84 | }
85 |
86 | private static void RunService()
87 | {
88 | ServiceBase[] servicesToRun = { new InternalService() };
89 | ServiceBase.Run(servicesToRun);
90 | }
91 |
92 | private void InstallService()
93 | {
94 | _serviceManager.Install();
95 | _registryManipulator.AddMinusServiceToRegistry();
96 | _serviceManager.Start();
97 | }
98 |
99 | private void UnInstallService()
100 | {
101 | if (!_serviceManager.IsInstalled())
102 | return;
103 |
104 | _serviceManager.Stop();
105 | _registryManipulator.RemoveMinusServiceFromRegistry();
106 | _serviceManager.UnInstall();
107 | }
108 |
109 | private void Stop()
110 | {
111 | if (OnServiceStopped != null)
112 | OnServiceStopped.Invoke();
113 | }
114 |
115 | private void Start()
116 | {
117 | Console.WriteLine("Service {0} started ", _serviceDisplayName);
118 | if (OnServiceStarted != null)
119 | OnServiceStarted.Invoke();
120 | }
121 |
122 | #endregion
123 | }
124 | }
125 |
--------------------------------------------------------------------------------