Skip to content

Commit f21a5c7

Browse files
committed
Minor code cleanup
1 parent e8f3d21 commit f21a5c7

11 files changed

+49
-60
lines changed

README.md

+5-5
Original file line numberDiff line numberDiff line change
@@ -36,11 +36,11 @@ Simple and lightweight implementation of tile server basic features for .NET 5 /
3636
### Technologies
3737
There are two separate solutions and corresponding projects, sharing the same source code files:
3838

39-
| Property | .NET 5 | .NET 8 |
40-
| ------------------ |:---------:|:--------------:|
41-
| SDK | .NET 5.0 | .NET 8.0 |
42-
| MS Visual Studio | 2019 | 2022 (17.8.3) |
43-
| Status | Legacy | Active |
39+
| Property | .NET 5 | .NET 8 |
40+
| ------------------ |:---------:|:-----------:|
41+
| SDK | .NET 5.0 | .NET 8.0 |
42+
| MS Visual Studio | 2019 | 2022 |
43+
| Status | Legacy | Active |
4444

4545
Using
4646
* [Microsoft.Data.Sqlite](https://docs.microsoft.com/ru-ru/dotnet/standard/data/sqlite/) for working with SQLite database.

Src/TileMapService/Controllers/TmsController.cs

+14-12
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ namespace TileMapService.Controllers
1818
[Route("tms")]
1919
public class TmsController : ControllerBase
2020
{
21+
private const string Version = "1.0.0";
22+
2123
private readonly ITileSourceFabric tileSourceFabric;
2224

2325
public TmsController(ITileSourceFabric tileSourceFabric)
@@ -35,7 +37,7 @@ public IActionResult GetRootResource()
3537
return File(EC.XmlDocumentToUTF8ByteArray(xmlDoc), MediaTypeNames.Text.Xml);
3638
}
3739

38-
[HttpGet("1.0.0")]
40+
[HttpGet(Version)]
3941
public IActionResult GetTileMapService()
4042
{
4143
// TODO: services/tilemapservice.xml
@@ -45,20 +47,21 @@ public IActionResult GetTileMapService()
4547
return File(EC.XmlDocumentToUTF8ByteArray(xmlDoc), MediaTypeNames.Text.Xml);
4648
}
4749

48-
[HttpGet("1.0.0/{tileset}")]
50+
[HttpGet(Version + "/{tileset}")]
4951
public IActionResult GetTileMap(string tileset)
5052
{
5153
// TODO: services/basemap.xml
5254
var capabilities = this.GetCapabilities();
53-
var layer = capabilities.Layers?.SingleOrDefault(l => l.Identifier == tileset);
55+
var layer = capabilities.Layers.SingleOrDefault(l => l.Identifier == tileset);
5456
if (layer == null)
5557
{
5658
return NotFound(); // TODO: errors in XML format
5759
}
58-
59-
var xmlDoc = new Tms.CapabilitiesUtility(capabilities).GetTileMap(layer);
60-
61-
return File(EC.XmlDocumentToUTF8ByteArray(xmlDoc), MediaTypeNames.Text.Xml);
60+
else
61+
{
62+
var xmlDoc = new Tms.CapabilitiesUtility(capabilities).GetTileMap(layer);
63+
return File(EC.XmlDocumentToUTF8ByteArray(xmlDoc), MediaTypeNames.Text.Xml);
64+
}
6265
}
6366

6467
/// <summary>
@@ -70,7 +73,7 @@ public IActionResult GetTileMap(string tileset)
7073
/// <param name="z">Tile Z coordinate (zoom level).</param>
7174
/// <param name="extension">File extension.</param>
7275
/// <returns>Response with tile contents.</returns>
73-
[HttpGet("1.0.0/{tileset}/{z}/{x}/{y}.{extension}")]
76+
[HttpGet(Version + "/{tileset}/{z}/{x}/{y}.{extension}")]
7477
public async Task<IActionResult> GetTileAsync(string tileset, int x, int y, int z, string extension, CancellationToken cancellationToken)
7578
{
7679
// TODO: z can be a string, not integer number
@@ -108,19 +111,18 @@ public async Task<IActionResult> GetTileAsync(string tileset, int x, int y, int
108111

109112
private Tms.Capabilities GetCapabilities()
110113
{
111-
var layers = EC.SourcesToLayers(this.tileSourceFabric.Sources);
112114
return new Tms.Capabilities
113115
{
116+
BaseUrl = this.BaseUrl,
117+
Layers = EC.SourcesToLayers(this.tileSourceFabric.Sources),
114118
ServiceTitle = this.tileSourceFabric.ServiceProperties.Title,
115119
ServiceAbstract = this.tileSourceFabric.ServiceProperties.Abstract,
116-
BaseUrl = this.BaseUrl,
117-
Layers = layers.ToArray(),
118120
};
119121
}
120122

121123
private string BaseUrl => $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}";
122124

123-
private IActionResult ResponseWithNotFoundError(string message)
125+
private FileContentResult ResponseWithNotFoundError(string message)
124126
{
125127
var xmlDoc = new Tms.TileMapServerError(message).ToXml();
126128
Response.ContentType = MediaTypeNames.Text.XmlUtf8;

Src/TileMapService/Controllers/WmsController.cs

+3-3
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ public async Task<IActionResult> ProcessWmsRequestAsync(
119119
}
120120
}
121121

122-
private IActionResult ProcessGetCapabilitiesRequest(Wms.Version version)
122+
private FileContentResult ProcessGetCapabilitiesRequest(Wms.Version version)
123123
{
124124
var layers = EC.SourcesToLayers(this.tileSourceFabric.Sources)
125125
.Where(l => l.Srs == SrsCodes.EPSG3857) // TODO: sources with EPSG:4326 support
@@ -301,15 +301,15 @@ await WmsHelper.DrawLayerAsync( // TODO: ? pass required format to avoid convers
301301

302302
private static readonly char[] LayersSeparator = new[] { ',' };
303303

304-
private IActionResult ResponseWithExceptionReport(string exceptionCode, string message, string locator)
304+
private FileContentResult ResponseWithExceptionReport(string exceptionCode, string message, string locator)
305305
{
306306
var xmlDoc = new ExceptionReport(exceptionCode, message, locator).ToXml();
307307
Response.ContentType = MediaTypeNames.Application.Xml;
308308
Response.StatusCode = (int)HttpStatusCode.OK;
309309
return File(EC.XmlDocumentToUTF8ByteArray(xmlDoc), Response.ContentType);
310310
}
311311

312-
private IActionResult ResponseWithServiceExceptionReport(string? code, string message, string version)
312+
private FileContentResult ResponseWithServiceExceptionReport(string? code, string message, string version)
313313
{
314314
var xmlDoc = new ServiceExceptionReport(code, message, version).ToXml();
315315
Response.ContentType = MediaTypeNames.Text.XmlUtf8;

Src/TileMapService/Controllers/WmtsController.cs

+3-3
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,7 @@ public async Task<IActionResult> ProcessGetTileRestfulRequestAsync(
180180
return await this.GetTileAsync(layer, tileCol, tileRow, Int32.Parse(tileMatrix), EC.TileFormatToContentType(format), this.tileSourceFabric.ServiceProperties.JpegQuality, cancellationToken);
181181
}
182182

183-
private IActionResult ProcessGetCapabilitiesRequest()
183+
private FileContentResult ProcessGetCapabilitiesRequest()
184184
{
185185
var layers = EC.SourcesToLayers(this.tileSourceFabric.Sources)
186186
.Where(l => l.Format == ImageFormats.Png || l.Format == ImageFormats.Jpeg) // Only raster formats
@@ -230,7 +230,7 @@ private async Task<IActionResult> GetTileAsync(
230230

231231
private string BaseUrl => $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}";
232232

233-
private IActionResult ResponseWithBadRequestError(string exceptionCode, string message)
233+
private FileContentResult ResponseWithBadRequestError(string exceptionCode, string message)
234234
{
235235
var xmlDoc = new ExceptionReport(exceptionCode, message).ToXml();
236236
Response.ContentType = MediaTypeNames.Text.XmlUtf8;
@@ -239,7 +239,7 @@ private IActionResult ResponseWithBadRequestError(string exceptionCode, string m
239239
return File(EC.XmlDocumentToUTF8ByteArray(xmlDoc), Response.ContentType);
240240
}
241241

242-
private IActionResult ResponseWithNotFoundError(string exceptionCode, string message)
242+
private FileContentResult ResponseWithNotFoundError(string exceptionCode, string message)
243243
{
244244
var xmlDoc = new ExceptionReport(exceptionCode, message).ToXml();
245245
Response.ContentType = MediaTypeNames.Text.XmlUtf8;

Src/TileMapService/TileMapService.NET5.csproj

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
<ItemGroup>
1313
<PackageReference Include="BitMiracle.LibTiff.NET" Version="2.4.649" />
1414
<PackageReference Include="Microsoft.Data.Sqlite.Core" Version="7.0.13" />
15-
<PackageReference Include="Npgsql" Version="6.0.7" />
15+
<PackageReference Include="Npgsql" Version="6.0.13" />
1616
<PackageReference Include="SkiaSharp" Version="2.88.6" />
1717
<PackageReference Include="SkiaSharp.NativeAssets.Linux" Version="2.88.6" />
1818
<PackageReference Include="SQLitePCLRaw.bundle_green" Version="2.1.7" />

Src/TileMapService/TileSources/HttpTileSource.cs

+5-6
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ async Task ITileSource.InitAsync()
7676
}
7777

7878
// Default is tms=false for simple XYZ tile services
79-
var tms = this.configuration.Tms ?? (this.configuration.Type.ToLowerInvariant() == SourceConfiguration.TypeTms);
79+
var tms = this.configuration.Tms ?? (String.Compare(this.configuration.Type, SourceConfiguration.TypeTms, StringComparison.InvariantCultureIgnoreCase) == 0);
8080
var srs = String.IsNullOrWhiteSpace(this.configuration.Srs) ? Utils.SrsCodes.EPSG3857 : this.configuration.Srs.Trim().ToUpper();
8181

8282
// Re-create configuration
@@ -256,7 +256,7 @@ async Task ITileSource.InitAsync()
256256

257257
async Task<byte[]?> ITileSource.GetTileAsync(int x, int y, int z, CancellationToken cancellationToken)
258258
{
259-
if ((z < this.configuration.MinZoom) || (z > this.configuration.MaxZoom))
259+
if (z < this.configuration.MinZoom || z > this.configuration.MaxZoom)
260260
{
261261
return null;
262262
}
@@ -285,13 +285,12 @@ async Task ITileSource.InitAsync()
285285
{
286286
if (response.Content.Headers.ContentType != null && response.Content.Headers.ContentType.MediaType == MediaTypeNames.Application.OgcServiceExceptionXml)
287287
{
288-
var message = await response.Content.ReadAsStringAsync();
288+
var message = await response.Content.ReadAsStringAsync(cancellationToken);
289289
this.logger.LogWarning($"Error reading tile: '{message}'.");
290290
return null;
291291
}
292292

293293
// TODO: more checks of Content-Type, response size, etc.
294-
295294
var data = await response.Content.ReadAsByteArrayAsync(cancellationToken);
296295
this.cache?.AddTile(x, y, z, data);
297296

@@ -329,14 +328,14 @@ async Task ITileSource.InitAsync()
329328
if (response.Content.Headers.ContentType != null &&
330329
response.Content.Headers.ContentType.MediaType == MediaTypeNames.Application.OgcServiceExceptionXml)
331330
{
332-
var message = await response.Content.ReadAsStringAsync();
331+
var message = await response.Content.ReadAsStringAsync(cancellationToken);
333332
this.logger.LogWarning($"Error reading tile: '{message}'.");
334333
return null;
335334
}
336335

337336
// TODO: more checks of Content-Type, response size, etc.
338337

339-
var data = await response.Content.ReadAsByteArrayAsync();
338+
var data = await response.Content.ReadAsByteArrayAsync(cancellationToken);
340339

341340
return data;
342341
}

Src/TileMapService/Tms/Capabilities.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,6 @@ class Capabilities
1010

1111
public string? BaseUrl { get; set; }
1212

13-
public Models.Layer[]? Layers { get; set; }
13+
public Models.Layer[] Layers { get; set; } = Array.Empty<Models.Layer>();
1414
}
1515
}

Src/TileMapService/Tms/CapabilitiesUtility.cs

+5-10
Original file line numberDiff line numberDiff line change
@@ -23,12 +23,7 @@ public CapabilitiesUtility(Capabilities capabilities)
2323
{
2424
if (capabilities.BaseUrl == null)
2525
{
26-
throw new ArgumentNullException(nameof(capabilities), "capabilities.BaseUrl is null.");
27-
}
28-
29-
if (capabilities.Layers == null)
30-
{
31-
throw new ArgumentNullException(nameof(capabilities), "capabilities.Layers is null.");
26+
throw new ArgumentNullException("capabilities.BaseUrl", "BaseUrl is null.");
3227
}
3328

3429
this.serviceTitle = capabilities.ServiceTitle;
@@ -156,7 +151,7 @@ public XmlDocument GetTileMap(Models.Layer layer)
156151
double unitsWidth, pixelsWidth;
157152
switch (layer.Srs)
158153
{
159-
case Utils.SrsCodes.EPSG3857:
154+
case SrsCodes.EPSG3857:
160155
{
161156
// Assuming 1x1 tile grid at zoom level 0
162157
unitsWidth = 20037508.342789 * 2;
@@ -180,7 +175,7 @@ public XmlDocument GetTileMap(Models.Layer layer)
180175

181176
break;
182177
}
183-
case Utils.SrsCodes.EPSG4326:
178+
case SrsCodes.EPSG4326:
184179
{
185180
// Assuming 2x1 tile grid at zoom level 0
186181
unitsWidth = 360;
@@ -320,12 +315,12 @@ private static XmlAttribute CreateProfileAttribute(XmlDocument doc, string? srs)
320315

321316
switch (srs)
322317
{
323-
case Utils.SrsCodes.EPSG3857:
318+
case SrsCodes.EPSG3857:
324319
{
325320
profileAttribute.Value = Identifiers.ProfileGlobalMercator;
326321
break;
327322
}
328-
case Utils.SrsCodes.EPSG4326:
323+
case SrsCodes.EPSG4326:
329324
{
330325
profileAttribute.Value = Identifiers.ProfileGlobalGeodetic;
331326
break;

Src/TileMapService/Utils/EntitiesConverter.cs

+2-4
Original file line numberDiff line numberDiff line change
@@ -40,10 +40,8 @@ public static string ExtensionToMediaType(string extension) =>
4040
_ => extension,
4141
};
4242

43-
public static List<Layer> SourcesToLayers(IEnumerable<SourceConfiguration> sources) =>
44-
sources
45-
.Select(c => SourceConfigurationToLayer(c))
46-
.ToList();
43+
public static Layer[] SourcesToLayers(IEnumerable<SourceConfiguration> sources) =>
44+
sources.Select(SourceConfigurationToLayer).ToArray();
4745

4846
private static Layer SourceConfigurationToLayer(SourceConfiguration c) =>
4947
new()

Src/TileMapService/Utils/ResponseHelper.cs

+3-8
Original file line numberDiff line numberDiff line change
@@ -41,14 +41,9 @@ public static bool IsFormatInList(IList<string> mediaTypes, string mediaType)
4141
if (isFormatSupported)
4242
{
4343
var outputImage = ImageHelper.ConvertImageToFormat(imageContents, mediaType, quality);
44-
if (outputImage != null)
45-
{
46-
return new FileResponse { FileContents = outputImage, ContentType = mediaType };
47-
}
48-
else
49-
{
50-
return null;
51-
}
44+
return outputImage != null
45+
? new FileResponse { FileContents = outputImage, ContentType = mediaType }
46+
: null;
5247
}
5348
else
5449
{

Src/TileMapService/Utils/WebMercator.cs

+7-7
Original file line numberDiff line numberDiff line change
@@ -157,21 +157,21 @@ public static double TileCoordinateYAtZoom(double latitude, int zoomLevel) =>
157157

158158
[MethodImpl(MethodImplOptions.AggressiveInlining)]
159159
public static double LongitudeToPixelXAtZoom(double longitude, int zoomLevel) =>
160-
LongitudeToPixelX(longitude, (double)MapSize(zoomLevel, DefaultTileSize));
160+
LongitudeToPixelX(longitude, MapSize(zoomLevel, DefaultTileSize));
161161

162162
[MethodImpl(MethodImplOptions.AggressiveInlining)]
163163
public static double LatitudeToPixelYAtZoom(double latitude, int zoomLevel) =>
164-
LatitudeToPixelY(latitude, (double)MapSize(zoomLevel, DefaultTileSize));
164+
LatitudeToPixelY(latitude, MapSize(zoomLevel, DefaultTileSize));
165165

166166
[MethodImpl(MethodImplOptions.AggressiveInlining)]
167167
public static double LongitudeToPixelX(double longitude, double mapSize) =>
168-
((longitude + 180.0) / 360.0) * mapSize;
168+
((longitude + 180) / 360) * mapSize;
169169

170170
[MethodImpl(MethodImplOptions.AggressiveInlining)]
171171
public static double LatitudeToPixelY(double latitude, double mapSize)
172172
{
173173
var sinLatitude = Math.Sin(MathHelper.DegreesToRadians(latitude));
174-
return (0.5 - Math.Log((1.0 + sinLatitude) / (1.0 - sinLatitude)) / (4.0 * Math.PI)) * mapSize;
174+
return (0.5 - Math.Log((1 + sinLatitude) / (1 - sinLatitude)) / (4 * Math.PI)) * mapSize;
175175
}
176176

177177
[MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -180,16 +180,16 @@ public static double PixelXToLongitude(double pixelX, int zoomLevel)
180180
var mapSize = (double)MapSize(zoomLevel, DefaultTileSize);
181181
var x = (MathHelper.Clip(pixelX, 0.0, mapSize) / mapSize) - 0.5;
182182

183-
return 360.0 * x;
183+
return 360 * x;
184184
}
185185

186186
[MethodImpl(MethodImplOptions.AggressiveInlining)]
187187
public static double PixelYToLatitude(double pixelY, int zoomLevel)
188188
{
189189
var mapSize = (double)MapSize(zoomLevel, DefaultTileSize);
190-
var y = 0.5 - (MathHelper.Clip(pixelY, 0.0, mapSize) / mapSize);
190+
var y = 0.5 - (MathHelper.Clip(pixelY, 0, mapSize) / mapSize);
191191

192-
return 90.0 - 360.0 * Math.Atan(Math.Exp(-y * 2.0 * Math.PI)) / Math.PI;
192+
return 90 - 360 * Math.Atan(Math.Exp(-y * 2 * Math.PI)) / Math.PI;
193193
}
194194
}
195195
}

0 commit comments

Comments
 (0)