# Windows Service Validation in ShopfloorConnect Installer

**Date**: 2025-10-10
**Feature**: Automated Windows Service Registration Verification

---

## Overview

The ShopfloorConnect installer now includes comprehensive validation to ensure the Windows service `SFCMTCService` is properly registered during installation.

---

## What Service Gets Installed?

### Service Details

| Property | Value |
|----------|-------|
| **Service Name** | `SFCMTCService` |
| **Display Name** | Shop Floor Connect MTC Service |
| **Description** | Machine Tool Client Service for Teamcenter integration |
| **Executable** | `C:\ShopFloorConnect\FIT-MI_Server\Tomcat 5.0\bin\SFCMTCService.exe` |
| **Startup Type** | Delayed Automatic |
| **Account** | Local System (default) |
| **Dependencies** | None |

### Service Architecture

The service is based on **Apache Tomcat 5.0** wrapped as a Windows service:
- Uses `tomcat8_64.exe` service wrapper (renamed to `SFCMTCService.exe`)
- Hosts the MTC web application (`wut.war`)
- Communicates with Teamcenter PLM server (10.233.113.141)
- Listens on local ports:
  - HTTP: 8090
  - HTTPS: 8493
  - Shutdown: 8006

---

## How Service Registration Works

### Installation Chain

```
ShopfloorConnect.iss
    │
    └─► Step 2: install.bat
            │
            ├─► Sets TCFITDIR environment variable
            │
            └─► Calls: Java + Apache Ant + ant_install.xml
                    │
                    ├─► Extracts mi_server.jar
                    ├─► Copies Tomcat files to FIT-MI_Server/
                    ├─► Renames tomcat8_64.exe → SFCMTCService.exe
                    ├─► Creates setenv.bat with paths
                    │
                    └─► Executes: SFC_MTC_Tomcat_service.bat install SFCMTCService delayed
                            │
                            └─► Registers Windows Service using Tomcat wrapper
                                ✓ Service: SFCMTCService
                                ✓ Startup: Delayed Automatic
                                ✓ Status: Stopped (installed but not started)
```

### Key Files Involved

| File | Purpose |
|------|---------|
| `install.bat` | Detects TCFITDIR, calls Ant build |
| `ant_install.xml` | Apache Ant build script (588 lines) |
| `mi_server.jar` | Contains Tomcat server and web app |
| `tomcat8_64.exe` | Apache Tomcat service wrapper |
| `SFC_MTC_Tomcat_service.bat` | Service registration script |
| `mi_server.ini` | MTC configuration (created by Ant) |

---

## Validation Checks in Installer

The installer performs **three validation checks** after running `install.bat`:

### Check 1: FIT-MI_Server Folder Exists
```pascal
if not DirExists('C:\ShopFloorConnect\FIT-MI_Server') then
begin
  MsgBox('Installation Error: FIT-MI_Server folder not created!');
  Exit;
end;
```

**What it validates**:
- The Ant build script successfully extracted and copied files
- The folder structure was created

**Typical failure reasons**:
- TCFITDIR not set before running install.bat
- Java runtime not found
- Disk write permissions issue

---

### Check 2: Windows Service Registered
```pascal
// Query the service using sc.exe
if not Exec('cmd.exe', '/c sc query SFCMTCService', '', SW_HIDE, ewWaitUntilTerminated, ResultCode) then
begin
  MsgBox('Warning: Unable to query Windows service!');
  Exit;
end;

// Check if service exists
if ResultCode <> 0 then
begin
  MsgBox('Service Registration Failed!');
  Exit;
end;
```

**What it validates**:
- Windows service `SFCMTCService` is registered in Service Control Manager
- Service is queryable via `sc.exe`

**Typical failure reasons**:
- SFC_MTC_Tomcat_service.bat failed to execute
- Insufficient admin privileges
- Service wrapper executable missing
- Service name conflict (service already exists with different config)

**Return Codes**:
- `0` = Service exists and is queryable ✓
- `1060` = Service does not exist (ERROR_SERVICE_DOES_NOT_EXIST)
- `5` = Access denied (not admin)

---

### Check 3: Configuration File Created
```pascal
if not FileExists('C:\ShopFloorConnect\FIT-MI_Server\webapps\wut\WEB-INF\conf\mi_server.ini') then
begin
  MsgBox('Configuration Error: mi_server.ini not found!');
  Exit;
end;
```

**What it validates**:
- The Ant script completed successfully
- Configuration file was created from template
- Web application structure is intact

**Typical failure reasons**:
- Ant build interrupted or failed
- Template file missing in mi_server.jar
- Web app deployment failed

---

## Service Commands

### Query Service Status
```cmd
sc query SFCMTCService
```

**Sample Output (Stopped)**:
```
SERVICE_NAME: SFCMTCService
TYPE               : 10  WIN32_OWN_PROCESS
STATE              : 1  STOPPED
WIN32_EXIT_CODE    : 1077  (0x435)
SERVICE_EXIT_CODE  : 0  (0x0)
CHECKPOINT         : 0x0
WAIT_HINT          : 0x0
```

**Sample Output (Running)**:
```
SERVICE_NAME: SFCMTCService
TYPE               : 10  WIN32_OWN_PROCESS
STATE              : 4  RUNNING
WIN32_EXIT_CODE    : 0  (0x0)
SERVICE_EXIT_CODE  : 0  (0x0)
CHECKPOINT         : 0x0
WAIT_HINT          : 0x0
```

### Start Service
```cmd
sc start SFCMTCService
```

or

```cmd
net start SFCMTCService
```

### Stop Service
```cmd
sc stop SFCMTCService
```

or

```cmd
net stop SFCMTCService
```

### Delete Service (Uninstall)
```cmd
sc delete SFCMTCService
```

or

```cmd
cd C:\ShopFloorConnect\FIT-MI_Server\Tomcat 5.0\bin
SFC_MTC_Tomcat_service.bat remove
```

### View Service Configuration
```cmd
sc qc SFCMTCService
```

---

## Manual Service Registration

If the installer fails to register the service, you can do it manually:

### Method 1: Using Batch File (Recommended)
```cmd
cd C:\ShopFloorConnect\FIT-MI_Server\Tomcat 5.0\bin
SFC_MTC_Tomcat_service.bat install SFCMTCService delayed
```

### Method 2: Using Service Wrapper Directly
```cmd
cd C:\ShopFloorConnect\FIT-MI_Server\Tomcat 5.0\bin
SFCMTCService.exe //IS//SFCMTCService --DisplayName="Shop Floor Connect MTC Service" --Startup=delayed
```

### Verify Registration
```cmd
sc query SFCMTCService
```

Should return service information (not error 1060).

---

## Troubleshooting Service Issues

### Service Shows "Error 1060" (Not Found)
**Cause**: Service was not registered

**Solutions**:
1. Check installer error messages for clues
2. Manually register using batch file (see above)
3. Verify service executable exists:
   ```cmd
   dir "C:\ShopFloorConnect\FIT-MI_Server\Tomcat 5.0\bin\SFCMTCService.exe"
   ```

### Service Won't Start (Error 1053)
**Cause**: Service failed to start within timeout period

**Solutions**:
1. Check TCFITDIR environment variable is set:
   ```cmd
   echo %TCFITDIR%
   ```
   Should output: `C:\ShopFloorConnect`

2. Verify Java runtime exists:
   ```cmd
   "C:\ShopFloorConnect\Java\j2sdk\jre\bin\java.exe" -version
   ```

3. Check Windows Event Viewer:
   - Windows Logs → Application
   - Look for errors from "SFCMTCService" or "Apache Tomcat"

4. Check service logs:
   ```
   C:\ShopFloorConnect\FIT-MI_Server\Tomcat 5.0\logs\
   ```

### Service Installed but Not Visible in Services GUI
**Cause**: Services console needs refresh

**Solution**:
1. Close Services console (services.msc)
2. Reopen it
3. Or use `sc query SFCMTCService` from command line

### Service Starts but Immediately Stops
**Cause**: Configuration error or port conflict

**Solutions**:
1. Check if ports are already in use:
   ```cmd
   netstat -ano | findstr ":8090"
   netstat -ano | findstr ":8493"
   ```

2. Verify `mi_server.ini` configuration:
   ```cmd
   notepad "C:\ShopFloorConnect\FIT-MI_Server\webapps\wut\WEB-INF\conf\mi_server.ini"
   ```

3. Check Tomcat configuration:
   ```cmd
   notepad "C:\ShopFloorConnect\FIT-MI_Server\Tomcat 5.0\conf\server.xml"
   ```

---

## Service Startup Process

When the service starts:

1. **Windows Service Manager** launches `SFCMTCService.exe`
2. **Service Wrapper** reads configuration from registry
3. **Wrapper** sets environment variables from `setenv.bat`:
   - `TCFITDIR=C:\ShopFloorConnect`
   - `JAVA_HOME=C:\ShopFloorConnect\Java\j2sdk`
4. **Wrapper** launches Java process with Tomcat
5. **Tomcat** starts and deploys `wut.war` web application
6. **MTC Application** reads `mi_server.ini` configuration
7. **MTC** connects to Teamcenter server at 10.233.113.141
8. **Service** reports "Running" status to Service Control Manager

**Total startup time**: ~30-60 seconds (delayed start adds additional delay)

---

## Registry Locations

Service configuration is stored in Windows Registry:

### Service Definition
```
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SFCMTCService
```

### Service Parameters
```
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SFCMTCService\Parameters
```

**Key Values**:
- `ImagePath`: Path to SFCMTCService.exe
- `DisplayName`: "Shop Floor Connect MTC Service"
- `Start`: 2 (Automatic - Delayed)
- `Type`: 16 (SERVICE_WIN32_OWN_PROCESS)

---

## Comparison: Before vs After Validation

### Before (Original Installer)
```
install.bat runs → [unknown if successful] → Show "Installation Complete!"
```

❌ No validation
❌ Silent failures
❌ No service verification
❌ User discovers issues later when trying to start service

### After (Improved Installer)
```
install.bat runs → Validate folder → Validate service → Validate config → Success
                         ↓               ↓               ↓
                    Show error     Show error      Show error
```

✓ Comprehensive validation
✓ Early error detection
✓ Specific error messages
✓ Remediation guidance
✓ Only shows success when truly successful

---

## Related Files

| File | Purpose |
|------|---------|
| `ShopfloorConnect.iss` | Main installer script with validation |
| `IMPROVEMENTS.md` | Full list of installer improvements |
| `README.md` | User documentation with troubleshooting |
| `SERVICE_VALIDATION.md` | This file |

---

**Last Updated**: 2025-10-10
**Version**: 1.1 (with service validation)
