Scripts for installing, starting, stopping and uninstalling a windows service

July 21st, 2017

These 5 files has served me for 10 years or more for updating a windows service in a small project I have.

The code is crude but serves its purpose. It is not hard to make the code nicer.

The thing here is that I have 1 service in 2 instances, one for production and one for QA on the same machine. Hence they need different names.

The bat file I normally run is StopUninstallInstallStartService.bat because it does the whole turn around. Between every step it pauses and allows me to check the output and between Uninstall and Install also swap the binaries.

I have a similar single file solution here.

InstallService.bat

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@echo off
rem This bat file installs a service and sets its name.
if dummy==dummy%1 (
goto help
)
rem *** Install the service.
sc create %1 binPath= %CD%\MyService.exe DisplayName= "MyService [%1]" start= delayed-auto
sc failure %1 reset= 0 actions= restart/30/restart/30/restart/3000
rem C:\Windows\Microsoft.NET\Framework\v4.0.30319\installutil.exe MyService.exe
goto end
: help
echo Parameter is missing.
echo Syntax: InstallService [Servicename]
:end

StartService.bat

1
2
3
4
5
6
7
8
9
10
11
12
@echo off
rem This bat file starts a service by its name.
if dummy==dummy%1 (
goto help
)
rem *** Start the service.
sc start %1
goto end
: help
echo Parameter is missing.
echo Syntax: StartService [Servicename]
:end

StopService.bat

1
2
3
4
5
6
7
8
9
10
11
12
@echo off
rem This bat file stops a service by its name.
if dummy==dummy%1 (
goto help
)
rem *** Stop the service.
sc stop %1
goto end
: help
echo Parameter is missing.
echo Syntax: StopService [Servicename]
:end

UninstallService.bat

1
2
3
4
5
6
7
8
9
10
11
12
13
@echo off
rem This file uninstalls a service by its name.
if dummy==dummy%1 (
goto help
)
rem *** Uninstall the service.
rem sc delete %1
C:\Windows\Microsoft.NET\Framework\v4.0.30319\installutil.exe /uninstall MyService.exe
goto end
: help
echo Parameter is missing.
echo Syntax: UninstallService [Servicename]
:end

StopUninstallInstallStartService.bat

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@echo off
rem This file stops, uninstalls, installs and starts a service; with a pause in between for manual intervention.
if dummy==dummy%1 (
goto help
)
echo *** Stop the service
call StopService %1
pause
echo *** Uninstall the service.
call DeleteService %1
pause
echo *** Install the service.
call InstallService %1
pause
echo *** Start the service.
call StartService %1
pause
goto end
:help
echo Parameter is missing.
echo Syntax: StopUninstallInstallStartService [Servicename]
:end

Stop, uninstall, install and start a windows service

July 19th, 2017

I have one bat file that does all this for me.
It also has a pause inserted so I can visually check that everything looks ok.
The pause between uninstall and install is important as that is where I exchange the DLL when updating.
Yes, the code is ugly. But it has served a project for 10+ years with the only update with new dotnet versions.

I have  a similar solution here. It uses several files but can also name the service.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
rem *** Stop the service.

net stop "My Service Name"

pause

rem *** Uninstall the service.

C:\Windows\Microsoft.NET\Framework\v4.0.30319\installutil.exe /uninstall MyService.exe

pause

rem *** Install the service.

C:\Windows\Microsoft.NET\Framework\v4.0.30319\installutil.exe MyService.exe

pause

rem *** Start the service.

net start "My Service Name"

pause

Start IIS express through command prompt

July 7th, 2017

I seldom use F5 (start the application in debugging mode in Visual studio) but instead run it normally and connect the debugger only when I need to.
Connecting the debugger takes a measurable amount of time so with a faster turnaround I can keep focused better.

I also leave IIS running all the time. It does shadow copying so there is no need to restart anything.

I have recently switched from IIS to IIS express while developing and hence need to have it running all the time. That I do through the command prompt with

1
"c:\Program Files\IIS Express\iisexpress.exe" /path:C:\PathToMyWeb /port:32767

where path is the path to the site (where the web.config resides) and the port is what you see in the web project properties or in the web browers’s address bar the first time you hit F5.

It has the nice side effect that I can see all the http requests I do in the command window, a light weight current log of sorts.

Prioritising is about removing stuff

June 17th, 2017

The question is not “Can you do x before month’s end?”.

The question is “Can you remove something that is less important than x?”

In an earlier project I had all my tasks on a wall so when someone wanted a task done they had to physically remove a note and instantly knew that another task would not be done (until something else was done or removed).

To put even more stress on the person, let’s call him Andersson, wanting to allot some of my time the notes/tasks had different owners. This meant that Andersson got a physical feeling that his/her work was more important than someone else’s.

“Do you think I can remove Svenssons note?”
“I don’t know. Ask him.”

This meant I didn’t have to switch task and search out Svensson and present someone else’s task and then come back to Andersson with a result.
Andersson understood his/her action had impact on two other people. Andersson’s problem was still in his/her hands.
My time spared. Svensson’s time spared.
Andersson didn’t have to wait for a decision from someone else.
All win.

Code reviewing comments

June 2nd, 2017

I am presently using TFS’s code reviewing tool and IMHO it lacks visualisation of which comments are important and which are not.

So I came up with the idea of prefixing my comments.

PRAISE: Good refactoring, I like how you remove the negation.

FIX: A null check is missing.

SUGGESTION: Split line.

CHECK: Is it the right enum used here?

EXPLAIN: Is this comparison really correct? I guess so but how does it work?

If there are many FIX but only one or a few are critical I prefix the critical once with RED, like RED FIX.
This gives the oppurtunity to “while you already are in the file, do these things too”.

When code reviewing do not forget to give appraisal too

Pseudo random

April 28th, 2017

I have started developing a lib for creating pseudo randomised data. (yes, I know all randomised data on a computer is pseudo randomised, but in my case I want to control the seeding)

The lib, basically, is the ordinary dotnet random class with constructor with some customised constructors to make it easier to add a known seed. It also contains methods for randomising strings with a prefix, a certain length, int, long, decimal, guid, enum and other stuff that is often used.

The seeding is taken from the test method’s name.
This will give the same values for every test run of that method.

Create a webapi

February 12th, 2017

Prerequisite

See Compile Aspnet core 1.1 outside Docker container but run within

Create a controller

Create a file TodoController.cs file in the same folder as HomeController.cs file. In a real application we should probably put it in a folder “api” or similar.

Fill it with the text below (which is a refinement of https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-web-api ):

[Update:There is now a

1
dotnet new -t webapi

or similar so you don’t have to copypaste the code below. I plan to write about it as soon as I can.]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication.Controllers
{
    // Setting the Route attribute is important.
    // Otherwise we don't get the restish behaviour we're looking for.
    // I cannot say exactly why this is so.
    [Route("api/[controller]")]
    public class TodoController : Controller
    {
        private static List _data =
        new List{
            new Item{
                Id = 1,
                Name = "One"
            },
            new Item{
                Id = 2,
                Name = "Two"
            },
        };
        [HttpGet]
        public IEnumerable<item> GetAll()
        {
            return _data;
        }
        [HttpGet("{id}", Name = "GetTodo")]
        public string Get(int id)
        {
            return _data.Single(d => d.Id == id).Name;
        }
        [HttpPut("{id}")]
        public IActionResult Put(int id, [FromBody] string name)
        {
            GetItem(id).Name = name;
            return new NoContentResult();
        }
        [HttpPost]
        public IActionResult Post(string name)
        {
            var item = new Item { Id = _data.Count() + 1, Name = name };
            _data.Add(item);
            return CreatedAtRoute("GetTodo", new { id = item.Id }, item);
        }
        private Item GetItem(int id)
        {
            return _data.Single(d => d.Id == id);
        }
    }
    public class Item
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}
</item>

Compile:

1
dotnet build

And start the web server with the application:

1
dotnet bin/Debug/netcoreapp1.1/MyWs.dll

Call the controller

Start another terminal.

First check what we have.

1
curl localhost:5000/api/Todo

Then check one item.

1
curl localhost:5000/api/Todo/2

Create a new.

1
2
curl --data "Name=Three" localhost:5000/api/Todo/
curl localhost:5000/api/Todo/3

Update an existing according to Stack overflow.

1
2
3
4
5
curl -H "Content-Type: application/json" \
-X PUT \
--data '"Tva"' \
localhost:5000/api/todo/2
curl localhost:5000/api/Todo/2

Image processing in dotnet core

February 6th, 2017

There is no native image processing lib for dotnet core but someone at Microsoft has been kind enough to list 4 alternatives here.

Overload capslock keyboard key in windows

January 24th, 2017

We all have this centrally keyboard key that is seldom used. I am thinking of caps lock.

I wanted to use it as an alternative key, not as ctrl or anything; but as something totally different that does not invade existing short cuts.

Rewiring the capslock is harder than it looks at first glance.
I didn’t find a Good solution but at least one that works; for now.

Autohotkey

Autohotkey aka AHK is for writing macros for keyboard, mouse(?) and joystick. The language is awful but don’t let that scare you away.

I have mapped CapsLock to be used with j, k, l and ; to navigate.
Capslock by itself is Esc.

Source code

Regular header stuff in the file:

1
2
3
4
#NoEnv ; Recommended for performance and compatibility with future AutoHotkey releases.
; #Warn ; Enable warnings to assist with detecting common errors.
SendMode Input ; Recommended for new scripts due to its superior speed and reliability.
SetWorkingDir %A_ScriptDir% ; Ensures a consistent starting directory.

Make Capslock not work as capslock but also make it work as Esc:
(I believe some magic is involved.)

1
2
3
SetCapsLockState AlwaysOff
!CapsLock::CapsLock
CapsLock::Send {Esc}

Map the personal stuff. In my case navigation:

1
2
3
4
CapsLock &amp; j::Send {Left}
CapsLock &amp; k::Send {Right}
CapsLock &amp; `;::Send {Down}
CapsLock &amp; l::Send {Up}

Unfortunately I don’t remember the sources I puzzled together my solution form.

Compile Aspnet core 1.1 outside Docker container but run within

January 14th, 2017

Prerequisite

OSX

Docker

Dotnet core 1.1

A folder named (e.g.) /Users/yourname/Docker/Dandelion
and a folder named (e.g.) /Users/yourname/Docker/Dandelion/MyWeb

Create the web

In MyWeb run

1
2
3
4
dotnet new -t web
dotnet restore
dotnet build
dotnet publish

Now we have a web site compiled and ready to run with [dotnet run].
You can run the app and then [curl localhost] to find out if it is runnable; but if you got no error message earlier all should be ok.

Create an image

Go to the Dandelion folder.

Create a file Dockerfile and paste into it:

1
2
3
FROM microsoft/dotnet
EXPOSE 80
ENV "ASPNETCORE_URLS=http://+:80"

Then, to create the image run

1
docker build -t yourname/dandelion .

Note that the name must be all small caps.

If you want to check that the image is created just execute [docker images] which should show the new image at the top of the list.

Start the container

Go to the Dandelion folder. (you are probably already standing there)

Execute

1
2
3
4
5
docker run -p 80:80 \
-ti --rm \
-v /Users/yourname/Documents/Docker/Dandelion/MyWeb/bin/Debug/netcoreapp1.1/publish:/MyWeb \
yourname/dandelion \
/bin/bash -c 'cd /MyWeb; dotnet MyWeb.dll'

and your web should start.

Verify result

Either open another console and execute

1
curl localhost

or go to localhost in your web browser.