TheTechIdea OilGas - Developer guide User guide →

Tutorials

Four guided builds. Every step below is code from tests/TheTechIdea.OilGas.Tests/TutorialTests.cs, and each tutorial is a test that runs its steps in order, so the tutorials cannot drift from the libraries.

1. Your first well view

From files to a checked, drawn and exported view in five steps.

Load the well. A mapping profile says which tables and columns hold what; the built-in csv profile reads a folder of CSV files, and a database is read the same way through a profile for its schema.

// 1. Load a well: a CSV folder through the built-in "csv" mapping profile (databases work the same way).
var provider = new MappedWellDataProvider(new CsvTabularSource(folder), MappingProfile.Load("csv"));
var loaded = await provider.LoadWellAsync("CSV-1");
WellModel model = loaded.Model;                         // canonical model; loaded.Warnings lists what could not be mapped

Build the view. The converter creates the depth track, the completion schematic and the tally; ExtraTracks adds the log, pressure and core tracks the model has data for.

// 2. Build the view: depth track, schematic, tally, plus log / pressure / core tracks from the model.
var document = WellModelConverter.ToWellboreView(model, new WellModelConversionOptions { ExtraTracks = WellLogTracks.FromModel }, out var conversionWarnings);

Check it before anyone relies on it. Messages carry stable codes, listed under Validation codes.

// 3. Check it before showing it: errors, warnings and information with stable codes.
foreach (var issue in WellboreValidator.Validate(document))
    Console.WriteLine($"{issue.Severity} {issue.Code}: {issue.Message}");

Show it. WellboreView draws on any SkiaSharp canvas; the README shows the few lines that connect it to a WinForms, WPF, MAUI or Avalonia control (redraw on Invalidated, forward mouse, wheel, keys and touch).

// 4. Show it: the view draws on any SkiaSharp canvas; a UI host forwards input and redraws on Invalidated.
var view = new WellboreView { Document = document, Width = 1200, Height = 900 };
view.ZoomToRange(9800, 10400);
using (var surface = SKSurface.Create(new SKImageInfo(1200, 900)))
    view.Draw(surface.Canvas);                          // in a UI: skControl.PaintSurface += (s, e) => view.Draw(e.Surface.Canvas);

Export exactly what the user sees - paged PDF with header block and legend, or SVG and PNG.

// 5. Export what the user sees: PDF (paged), SVG or PNG.
using var pdf = new MemoryStream();
int pages = WellboreExport.ToPdf(document, pdf, new WellborePrintOptions { Title = "CSV-1 completion" });

2. Writing a custom track

A track is a class with a stable type key. It draws in its plot area through the view's depth mapper (so it follows zoom, TVD and compressed modes automatically), and it can add a readout, validation messages, legend entries and its own saved data.

/// <summary>Tutorial track: drilling bit runs as labelled depth intervals.</summary>
[WellTrackType("tutorial.bit-runs")]
public sealed class BitRunTrack : WellTrack
{
    /// <summary>One bit run.</summary>
    public sealed class BitRun
    {
        /// <summary>Depth the run started (document unit).</summary>
        public float Top { get; set; }
        /// <summary>Depth the run ended.</summary>
        public float Bottom { get; set; }
        /// <summary>Bit, for example 12-1/4in PDC.</summary>
        public string Bit { get; set; } = string.Empty;
    }

    public BitRunTrack() { Name = "Bit runs"; WidthRatio = 0.8f; }
    public override string TypeKey => "tutorial.bit-runs";              // written to documents; keep it stable
    public override string? Subtitle => "bit per run";
    public List<BitRun> Runs { get; } = new List<BitRun>();

    // drawing: the plot area, depths through the view's mapper, colours from the theme
    public override void DrawContent(SKCanvas canvas, WellTrackContext context)
    {
        var p = context.Layout.PlotBounds;
        using var fill = new SKPaint { Color = new SKColor(255, 224, 178) };
        using var edge = new SKPaint { IsAntialias = true, Style = SKPaintStyle.Stroke, Color = context.Theme.Frame };
        using var text = new SKPaint { IsAntialias = true, Color = context.Theme.Text };
        using var font = new SKFont { Size = 10f };
        foreach (var run in Runs)
        {
            var box = new SKRect(p.Left + 2f, context.Mapper.ToY(run.Top), p.Right - 2f, context.Mapper.ToY(run.Bottom));
            canvas.DrawRect(box, fill); canvas.DrawRect(box, edge);
            canvas.DrawText(run.Bit, box.MidX, box.MidY, SKTextAlign.Center, font, text);
        }
    }

    // cursor readout at a depth
    public override string? ReadoutAt(WellTrackContext context, float depth) =>
        Runs.FirstOrDefault(r => depth >= r.Top && depth <= r.Bottom) is BitRun r ? $"{r.Bit} ({r.Top:0}-{r.Bottom:0})" : null;

    // checks shown with every other validation message (use your own code prefix)
    public override IEnumerable<WellboreIssue> Validate(WellboreDocument document)
    {
        var ordered = Runs.OrderBy(r => r.Top).ToList();
        for (var i = 1; i < ordered.Count; i++)
            if (ordered[i].Top < ordered[i - 1].Bottom)
                yield return new WellboreIssue(WellboreIssueSeverity.Warning, "BR001", $"{Name}: runs '{ordered[i - 1].Bit}' and '{ordered[i].Bit}' overlap.", Id);
    }

    // legend and printed legend
    public override IEnumerable<LegendEntry> LegendEntries()
    {
        yield return new LegendEntry { Group = "Drilling", Label = "Bit run", Color = new SKColor(255, 224, 178) };
    }

    // persistence: the track's own data inside the document JSON
    public override JsonObject? SavePayload()
    {
        var runs = new JsonArray();
        foreach (var r in Runs) runs.Add(new JsonObject { ["top"] = r.Top, ["bottom"] = r.Bottom, ["bit"] = r.Bit });
        return new JsonObject { ["runs"] = runs };
    }

    public override void LoadPayload(JsonObject? payload)
    {
        Runs.Clear();
        if (payload?["runs"] is JsonArray runs)
            foreach (var o in runs.OfType<JsonObject>())
                Runs.Add(new BitRun { Top = o["top"]!.GetValue<float>(), Bottom = o["bottom"]!.GetValue<float>(), Bit = o["bit"]?.GetValue<string>() ?? "" });
    }
}

Use it like any built-in track:

// 2. Put it in a view next to the built-in tracks and draw it.
var document = new WellboreDocument(); document.Axis.Unit = DepthUnit.Meters; document.Axis.Top = 0; document.Axis.Bottom = 3000;
var bits = new BitRunTrack();
bits.Runs.Add(new BitRunTrack.BitRun { Top = 0, Bottom = 800, Bit = "17-1/2in" });
bits.Runs.Add(new BitRunTrack.BitRun { Top = 800, Bottom = 2400, Bit = "12-1/4in PDC" });
document.Tracks.Add(new DepthTrack()); document.Tracks.Add(bits);
var view = new WellboreView { Document = document, Width = 500, Height = 900 };
using (var surface = SKSurface.Create(new SKImageInfo(500, 900))) view.Draw(surface.Canvas);

Saving and reloading recreates it from its type key:

// 3. Save and reload: the type key recreates the track, SavePayload / LoadPayload carry its runs.
var json = document.ToJson();
var reloaded = WellboreDocument.FromJson(json);
var again = reloaded.FindTrack<BitRunTrack>()!;         // the same type again, with its two runs

Its readout and checks join the built-in ones:

// 4. Readout and validation work like the built-in tracks.
var context = view.LastContexts.Single(c => c.Track is BitRunTrack);
var readout = context.Track.ReadoutAt(context, 1200);               // "12-1/4in PDC (800-2400)"
bits.Runs.Add(new BitRunTrack.BitRun { Top = 2300, Bottom = 3000, Bit = "8-1/2in" });
var issues = WellboreValidator.Validate(document);                  // includes BR001: the last two runs overlap

To let users drag items in your track, add the three editing hooks described under Extending.

3. A company environment

One company file with your units, names and code lists; country or asset files extend it with only what differs.

// 1. A company base with its resources (lexicon and labels), and a country file that extends it.
File.WriteAllText(Path.Combine(root, "company.environment.json"), @"{
  ""name"": ""Acme"", ""units"": { ""pressureUnit"": ""bar"" },
  ""resources"": { ""lexiconFiles"": [ ""acme.lexicon.json"" ], ""labelFiles"": [ ""acme.labels.json"" ] } }");
File.WriteAllText(Path.Combine(root, "acme.lexicon.json"), @"{ ""units"": [ { ""id"": ""BURGAN"", ""name"": ""Burgan Formation"", ""aliases"": [ ""BURGAN FM"" ] } ] }");
File.WriteAllText(Path.Combine(root, "acme.labels.json"), @"{ ""culture"": ""en"", ""labels"": { ""track.depth"": ""Measured depth"" } }");
File.WriteAllText(Path.Combine(root, "kw", "kw.environment.json"), @"{
  ""extends"": ""../company.environment.json"", ""name"": ""Acme Kuwait"",
  ""units"": { ""depthUnit"": ""m"" }, ""cement"": { ""goodBondIndex"": 0.75 } }");

Load and check the files. wellbore-config validate does the same from the command line, with exit codes for CI.

// 2. Load and check it: problems are reported, never thrown; every value knows where it came from.
var services = WellboreServices.Load(Path.Combine(root, "kw", "kw.environment.json"));
foreach (var w in services.Warnings) Console.WriteLine(w);                       // coded file problems are in services.Issues
var fromFile = services.Environment.SourceOf("units.pressureUnit");               // ...\company.environment.json
var errors = services.Environment.Validate();                                     // wellbore-config validate does the same in CI

Apply the environment: per request in a server, or for the whole application.

// 3. Apply it: for one request (a server) with a scope, or for the whole application with Global.
using (WellboreServices.Scope(services))
{
    var depthTitle = new DepthTrack().Name;                                       // "Measured depth" (company label)
    var pressure = DisplayUnits.FormatPressure(1000);                             // "68.9 bar" (company unit)
    var unit = WellboreServices.Current.Lexicon.Resolve("Top Burgan FM")?.Id;     // "BURGAN" (company lexicon)
    Assert.Equal(("Measured depth", "68.9 bar", "BURGAN"), (depthTitle, pressure, unit));
}
// desktop application: WellboreServices.Global = services;

4. A live feed

A live view needs a source of new rows, a feed that appends them to the document, and a view in follow mode.

/// <summary>A stand-in for a rig feed: five new gamma-ray samples every poll (a WITSML / ETP client implements the same interface).</summary>
public sealed class SimulatedMwdSource : IGrowingLogSource
{
    private double _depth = 1000;
    public Task<GrowingLogRows> FetchAfterAsync(double? lastIndex, CancellationToken cancellationToken = default)
    {
        var rows = new GrowingLogRows { IndexUnit = "m", Mnemonics = { "GR" } };
        for (var i = 0; i < 5; i++) { _depth += 0.5; rows.Rows.Add((_depth, new double?[] { 60 + 10 * Math.Sin(_depth) })); }
        return Task.FromResult(rows);
    }
}
// 2. A view with the curve the feed fills, a LiveLogFeed on its document, and follow mode.
var document = new WellboreDocument(); document.Axis.Unit = DepthUnit.Meters; document.Axis.Top = 990; document.Axis.Bottom = 1010;
var gr = new WellLogTrack { Name = "Gamma Ray" }; gr.Curves.Add(new WellLogCurve { Mnemonic = "GR", MinimumValue = 0, MaximumValue = 150 });
document.Tracks.Add(new DepthTrack()); document.Tracks.Add(gr);
var feed = new LiveLogFeed(document);
var view = new WellboreView { Document = document, Live = feed, FollowLatest = true, Clock = () => now, Width = 500, Height = 800 };
// 3. Poll on your schedule (a timer or background service); each poll appends only new rows.
var source = new SimulatedMwdSource();
for (var poll = 0; poll < 3; poll++)
{
    int added = await feed.PollAsync(source, now);
    view.Draw(SKSurface.Create(new SKImageInfo(500, 800)).Canvas);                // a UI host just redraws
}

The badge tells users how old the data is:

// 4. Watch the data age: the badge reads LIVE, then STALE after live.staleAfterSeconds without new rows.
var live = view.LastLiveBadge;                                                    // "LIVE · 0s"
view.Clock = () => now.AddMinutes(10);
using (var surface = SKSurface.Create(new SKImageInfo(500, 800))) view.Draw(surface.Canvas);
var stale = view.LastLiveBadge;                                                   // "STALE · 10m"