# AGENTS.md — IHBoxWebsite

## Overview

This is the **IHBox MES Web Application** — an ASP.NET 4.8 **Web Site project** (not a Web Application
project) that hosts a Backbone.js SPA for the Dexteel Manufacturing Execution System. The server side
provides ASP.NET ASPX templates, WCF services, and API endpoints. The client side is a Backbone.js SPA
with RequireJS AMD modules. See `app/AGENTS.md` for SPA-specific conventions.

---

## Build & Deploy

This is an **ASP.NET Web Site** (not a compiled Web Application). There is no `.sln` or `.csproj`.

- **No manual compile step** — code in `App_Code/` is compiled by ASP.NET at runtime on first request.
- **Deployed via IIS** — copy files to the IIS virtual directory (typically `/IHBox`).
- **Publish** via MSBuild using `website.publishproj`:
  ```bash
  msbuild website.publishproj /p:Configuration=Release /p:DeployOnBuild=true
  ```
- **Version bumping** — update `version.txt` using the helper scripts:
  ```bash
  Tools\bumpVersion.bat         # increments patch version
  Tools\bumpversion.ps1         # PowerShell alternative
  ```
  Version is read from `package.json` at runtime by `App_Code/WebAppVersion.cs` and used as a
  cache-buster on all script and CSS references (`?v=4.2.0.7`).

---

## Tests

**There are no automated tests** for this project. Integration testing is done manually against a live
SQL Server instance (`SRD-MESDEV` for dev, `SRD-MES` for production).

---

## Project Structure

```
IHBoxWebsite/
├── App_Code/               # Server-side C# (auto-compiled by ASP.NET at runtime)
│   ├── DAL.cs              # Static data access layer (raw ADO.NET, stored procs)
│   ├── WebApp.cs           # Central helper: menus, security, user, session
│   ├── DMT.cs / IDMT.cs    # WCF service implementation and interface
│   ├── LogService.cs       # WCF service for client-side logging
│   ├── Response.cs         # Simple Response DTO {Success, Message, Data}
│   ├── Mail.cs             # Email sending via Gmail SMTP
│   ├── SystemConfiguration/ # System setup classes
│   └── DotPrograms/        # Custom scripting/compilation engine
├── App_LocalResources/     # Global .resx localization files (EN, ES, FR, PT)
├── app/                    # Backbone.js SPA — see app/AGENTS.md
├── assets/                 # Static assets: CSS, JS libraries, fonts, images
│   ├── ag-grid/            # AG Grid Enterprise
│   ├── bootstrap/          # Bootstrap 2.x
│   ├── libs/jam/           # Core JS libs (backbone, jquery, underscore, handlebars)
│   └── libs/js/            # 52+ additional JS libraries
├── Bin/                    # Pre-compiled DLLs (do not edit; rebuild deps if needed)
├── landing/                # Pre-login pages (login, signup, email templates)
├── mobile/                 # Mobile trending page
├── Tools/                  # Version bump scripts
├── AppSettings.config      # External appSettings (referenced from Web.config)
├── connectionStrings.config # External connection strings (referenced from Web.config)
├── Global.asax             # ASP.NET application lifecycle
├── index.aspx / .cs        # SPA host page (main entry point)
├── heartbeat.aspx / .cs    # Health check endpoint — returns {"status":"OK"}
├── site_base.master / .cs  # Master page (minimal HTML shell)
├── Web.config              # Main ASP.NET configuration
├── packages.config         # NuGet packages
└── version.txt             # Current version string (e.g., 4.2.0.7)
```

---

## C# Code Style

### Naming Conventions

| Element | Convention | Example |
|---|---|---|
| Classes | PascalCase | `DAL`, `WebApp`, `LogService` |
| Public methods | PascalCase | `GetMenuData`, `SendEmail` |
| Private methods | camelCase | `saveKey`, `hashPassword` |
| Static fields | camelCase | `connectionString`, `logger` |
| Instance fields | `this.camelCase` | `this.logger`, `this.jsSerializer` |
| Local variables | camelCase | `menuData`, `outputDirPath` |

### Using Directives

All usings are explicit (no global usings — this is .NET 4.8). Order: System → Microsoft → third-party →
project namespaces. Example:

```csharp
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Configuration;
using log4net;
using Helpers.Log;
```

### Types

- No nullable reference types (pre-C# 8, .NET 4.8).
- Use `int.TryParse()` / `float.Parse()` with guards rather than bare casts.
- `Helpers.Common.Response<T>` is the standard return type for cross-boundary WCF results.
- `Response.cs` (`{Success, Message, Data}`) is the simpler DTO for ASPX endpoint returns.

---

## Server-Side Data Access

All database access goes through **stored procedures** — never write inline SQL.

### Direct ADO.NET (standard pattern in `DAL.cs`)
```csharp
using (var con = new SqlConnection(connectionString))
using (var cmd = new SqlCommand("Schema.ProcedureName", con))
{
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@Param", value);
    var da = new SqlDataAdapter(cmd);
    var ds = new DataSet();
    da.Fill(ds);
    // Convert ds.Tables[0] to Dictionary or JSON
}
```

### Secured Calls (for security-sensitive operations)
```csharp
// Uses encrypted SA credentials via the Security project
Security.DALSecurity.CallSecuredProcedure("Schema.ProcedureName", parameters, connectionString);
```

### Connection Strings
- `APP` — `PublicUser` account (read-only for most screens)
- `SYSTEM` — `IHBoxSystemUser` account (write operations)
- Accessed via `ConfigurationManager.ConnectionStrings["APP"].ConnectionString`
- Defined in `connectionStrings.config`; **never hardcode server names in committed code**

---

## Logging (Server-Side)

Uses **log4net** configured in `Web.config` with two rolling file appenders:
- `..\..\Logs\IHBoxSystemDebug.log` — all levels
- `..\..\Logs\IHBoxSystemExceptions.log` — errors only

```csharp
// Initialize (top of class)
ILog logger = Logger.GetLogger(MethodBase.GetCurrentMethod().DeclaringType.Name);

// Usage
logger.Info("Processing request for user: " + userName);
logger.Error("Error in GetMenuData.", ex);
logger.Debug(ex.Message);
```

WCF service methods use `TransactionLogger` for structured begin/end logging:
```csharp
tranLog = new TransactionLogger(this.logger, MethodBase.GetCurrentMethod().Name);
tranLog.LogBegin();
// ... work ...
tranLog.LogEnd(response);
// In catch:
response = new SqlResponse(ex).ToResponse();
tranLog.LogEnd(ex);
```

---

## Error Handling (Server-Side)

- ASPX code-behind: catch all exceptions, return `{ Success: false, Message: ex.Message }` JSON.
- WCF methods: use `TransactionLogger.LogEnd(ex)` and return a `Response` DTO — never let exceptions
  bubble out of WCF service methods.
- **Avoid catch-and-swallow** (silent `catch (Exception ex) { }`) even though it exists in legacy code.
  Always log with `logger.Error(...)` before swallowing.

---

## Configuration

- `Web.config` — master config; references external files for `appSettings` and `connectionStrings`
- `AppSettings.config` — license folders, email credentials, update paths, encrypted passwords
- `connectionStrings.config` — SQL Server connection strings (do not commit production credentials)
- `app/app-config.js` — client-side config: `root`, `foldersRoot`, database names, custom modules list
- Authentication mode: **Windows Authentication** — `<authentication mode="Windows" />`

---

## Referenced Projects & DLLs

Built from source (referenced in `website.publishproj`):
- `Helpers2/Helpers.Common` — `Response<T>`, `TransactionLogger`, null-safe utilities
- `Helpers2/Helpers.Database` — `HelperDatabase.ExecuteProcedure()`
- `Helpers2/Helpers.ThirdParty` — third-party integrations
- `Tools/Security` — `DALSecurity.CallSecuredProcedure()`, encryption/decryption

Pre-compiled DLLs in `Bin/` (NuGet + external):
- `log4net.dll`, `Newtonsoft.Json.dll`, `EPPlus.dll` (Excel), `Ionic.Zip.dll` (ZIP)
- `DotNetSiemensPLCToolBoxLibrary.dll` (PLC comm), `IHDMTApi.dll` (DMT API)
- `Microsoft.AnalysisServices.*.dll` (SSAS)

---

## WCF Services

- `Log.svc` / `LogService.cs` — receives client-side JS log messages and writes to log4net
- `DMT` / `DMT.cs` — script compilation and upload service
- Service contracts defined in `IDMT.cs` as WCF `[ServiceContract]` / `[OperationContract]` interfaces
- Configured in `Web.config` under `<system.serviceModel>`
