Skip to content

Commit e288cfb

Browse files
oguncemusta
andauthored
Feature/sonarcloud issues (#15)
* Resolving sonarcloud issues, updated packages. * app engine yaml file removed. * code smell fixed. * configuration builder improved * code smells removed * dependencies updated Co-authored-by: Cem Usta <[email protected]>
1 parent 870e37d commit e288cfb

File tree

16 files changed

+103
-151
lines changed

16 files changed

+103
-151
lines changed

ImageServer.Core/Controllers/ImageController.cs

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -30,19 +30,7 @@ public async Task<IActionResult> ImageAsync(string id, string slug, int w, int h
3030
{
3131
Response.Headers.Add("Cache-Control", $"public, max-age={TimeSpan.FromDays(1).TotalSeconds}");
3232
Response.Headers.Add("Access-Control-Allow-Origin", "*");
33-
return await ImageResult(id, slug, w, h, quality, options);
34-
}
3533

36-
[HttpGet("/i/{slug}/{*filepath}")]
37-
public async Task<IActionResult> ImageFromFilePathAsync(string filepath, string slug)
38-
{
39-
Response.Headers.Add("Cache-Control", $"public, max-age={TimeSpan.FromDays(1).TotalSeconds}");
40-
Response.Headers.Add("Access-Control-Allow-Origin", "*");
41-
return await ImageResult(filepath, slug);
42-
}
43-
44-
private async Task<IActionResult> ImageResult(string id, string slug, int w = 0, int h = 0, int quality = 100, string options = "")
45-
{
4634
if (string.IsNullOrWhiteSpace(id))
4735
{
4836
_logger.LogError("Id is null");
@@ -55,6 +43,19 @@ private async Task<IActionResult> ImageResult(string id, string slug, int w = 0,
5543
return new StatusCodeResult((int)HttpStatusCode.BadRequest);
5644
}
5745

46+
return await ImageResult(id, slug, w, h, quality, options);
47+
}
48+
49+
[HttpGet("/i/{slug}/{*filepath}")]
50+
public async Task<IActionResult> ImageFromFilePathAsync(string filepath, string slug)
51+
{
52+
Response.Headers.Add("Cache-Control", $"public, max-age={TimeSpan.FromDays(1).TotalSeconds}");
53+
Response.Headers.Add("Access-Control-Allow-Origin", "*");
54+
return await ImageResult(filepath, slug);
55+
}
56+
57+
private async Task<IActionResult> ImageResult(string id, string slug, int w = 0, int h = 0, int quality = 100, string options = "")
58+
{
5859
byte[] bytes;
5960
try
6061
{

ImageServer.Core/ImageServer.Core.csproj

Lines changed: 2 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -39,11 +39,6 @@
3939
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
4040
</Content>
4141
</ItemGroup>
42-
<ItemGroup>
43-
<None Update="flex.yaml">
44-
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
45-
</None>
46-
</ItemGroup>
4742
<PropertyGroup Condition="'$(Configuration)' == 'Debug'">
4843
<TypeScriptTarget>ES6</TypeScriptTarget>
4944
<TypeScriptJSXEmit>None</TypeScriptJSXEmit>
@@ -60,13 +55,7 @@
6055
<TypeScriptSourceRoot />
6156
</PropertyGroup>
6257
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' " />
63-
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
64-
<IntermediateOutputPath>obj\Debug</IntermediateOutputPath>
65-
<DebugSymbols>false</DebugSymbols>
66-
<DebugType></DebugType>
67-
<OutputPath>bin\Debug</OutputPath>
68-
<DefineConstants></DefineConstants>
69-
<NoWarn></NoWarn>
70-
<NoStdLib>false</NoStdLib>
58+
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
59+
<PlatformTarget>AnyCPU</PlatformTarget>
7160
</PropertyGroup>
7261
</Project>

ImageServer.Core/Program.cs

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
namespace ImageServer.Core
88
{
9-
public class Program
9+
public static class Program
1010
{
1111
public static void Main(string[] args)
1212
{
@@ -15,19 +15,17 @@ public static void Main(string[] args)
1515

1616
public static IHostBuilder CreateHostBuilder(string[] args)
1717
{
18-
var config = new ConfigurationBuilder()
19-
.SetBasePath(Directory.GetCurrentDirectory())
20-
//.AddJsonFile("hosting.json", true)
21-
.Build();
22-
2318
var hostBuilder = Host.CreateDefaultBuilder(args)
19+
.ConfigureAppConfiguration((hostingContext, config) =>
20+
{
21+
config.SetBasePath(Path.Combine(Directory.GetCurrentDirectory(),"conf"));
22+
config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
23+
})
2424
.ConfigureWebHostDefaults(webBuilder =>
2525
{
2626
webBuilder.UseNLog();
27-
webBuilder.UseConfiguration(config);
2827
webBuilder.UseKestrel();
2928
webBuilder.UseContentRoot(Directory.GetCurrentDirectory());
30-
webBuilder.UseIISIntegration();
3129
webBuilder.UseStartup<Startup>();
3230
});
3331

ImageServer.Core/Route/OptionsRouteConstraint.cs

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
using System.Text.RegularExpressions;
22
using Microsoft.AspNetCore.Http;
33
using Microsoft.AspNetCore.Routing;
4+
using System.Collections.Generic;
45

56
namespace ImageServer.Core.Route
67
{
@@ -21,18 +22,16 @@ public bool Match(HttpContext httpContext, IRouter route, string routeKey, Route
2122

2223
bool StringHasUniqueChars(string key)
2324
{
24-
var charTable = string.Empty;
25+
var charTable = new List<char>();
2526

2627
foreach (var character in key)
2728
{
28-
if (charTable.IndexOf(character) == -1)
29-
{
30-
charTable += character;
31-
}
32-
else
29+
if (charTable.Contains(character))
3330
{
3431
return false;
3532
}
33+
34+
charTable.Add(character);
3635
}
3736
return true;
3837
}

ImageServer.Core/Services/Exceptions.cs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,23 @@
22

33
namespace ImageServer.Core.Services
44
{
5+
[Serializable]
56
public class SlugNotFoundException : Exception
67
{
78
public SlugNotFoundException(string message) : base(message)
89
{
910
}
1011
}
1112

13+
[Serializable]
1214
public class GridFsObjectIdException : Exception
1315
{
1416
public GridFsObjectIdException(string message) : base(message)
1517
{
1618
}
1719
}
1820

21+
[Serializable]
1922
public class RedirectToFallbackException : Exception
2023
{
2124
public readonly string FallbackImage;

ImageServer.Core/Services/FileAccess/GoogleStorageBucketAccess.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,8 @@ public async Task<byte[]> GetFileAsync(HostConfig host, string file)
3535
{
3636
throw new FileNotFoundException(ex.Message, file);
3737
}
38-
throw ex;
38+
39+
throw;
3940
}
4041
}
4142
}

ImageServer.Core/Services/FileAccess/GridFsAccess.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ public async Task<byte[]> GetFileAsync(HostConfig host, string file)
4141
throw new FileNotFoundException(ex.Message, file);
4242
}
4343

44-
throw ex;
44+
throw;
4545
}
4646

4747
return bytes;
Lines changed: 18 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using System;
22
using System.IO;
3+
using System.Net;
34
using System.Net.Http;
45
using System.Threading.Tasks;
56
using ImageServer.Core.Model;
@@ -10,39 +11,28 @@ public class WebAccess : IFileAccessStrategy
1011
{
1112
public async Task<byte[]> GetFileAsync(HostConfig host, string file)
1213
{
13-
var url = host.Backend + '/' + file;
14-
try
14+
var url = $"{host.Backend}/{file}";
15+
16+
using var stream = new MemoryStream();
17+
using var client = new HttpClient();
18+
using var request = new HttpRequestMessage(HttpMethod.Get, url);
19+
using var response = await client.SendAsync(request);
20+
21+
if (response.StatusCode == HttpStatusCode.NotFound)
1522
{
16-
using (var stream = new MemoryStream())
17-
{
23+
throw new FileNotFoundException("File not found", url);
24+
}
1825

19-
using (var client = new HttpClient())
20-
using (var request = new HttpRequestMessage(HttpMethod.Get, url))
21-
using (var response = await client.SendAsync(request))
22-
{
23-
if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
24-
{
25-
throw new FileNotFoundException("File not found", url);
26-
}
26+
if (response.StatusCode != HttpStatusCode.OK)
27+
{
28+
throw new HttpRequestException($"Http request not OK: {response.StatusCode}, url: {url}");
29+
}
2730

28-
if (response.StatusCode != System.Net.HttpStatusCode.OK)
29-
{
30-
throw new HttpRequestException($"Http request not OK: {response.StatusCode}, url: {url}");
31-
}
31+
using var contentStream = await response.Content.ReadAsStreamAsync();
3232

33-
using (var contentStream = await response.Content.ReadAsStreamAsync())
34-
{
35-
await contentStream.CopyToAsync(stream);
36-
}
37-
}
33+
await contentStream.CopyToAsync(stream);
3834

39-
return stream.TryGetBuffer(out ArraySegment<byte> data) ? data.Array : null;
40-
}
41-
}
42-
catch (Exception ex)
43-
{
44-
throw ex;
45-
}
35+
return stream.TryGetBuffer(out ArraySegment<byte> data) ? data.Array : null;
4636
}
4737
}
4838
}

ImageServer.Core/Startup.cs

Lines changed: 4 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -12,32 +12,19 @@
1212
using Microsoft.Extensions.DependencyInjection;
1313
using Microsoft.Extensions.Hosting;
1414
using Microsoft.Extensions.Logging;
15-
using NLog;
1615
using ILogger = Microsoft.Extensions.Logging.ILogger;
1716

1817
namespace ImageServer.Core
1918
{
2019
public class Startup
2120
{
22-
public IConfigurationRoot Configuration { get; }
21+
private IConfiguration _configuration { get; }
2322

2423
private ILogger _logger;
2524

26-
public Startup(IWebHostEnvironment env)
25+
public Startup(IConfiguration conf)
2726
{
28-
var builder = new ConfigurationBuilder()
29-
.SetBasePath($"{env.ContentRootPath}/conf")
30-
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
31-
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
32-
.AddEnvironmentVariables();
33-
Configuration = builder.Build();
34-
35-
if (env.IsDevelopment())
36-
{
37-
builder.AddUserSecrets("local");
38-
}
39-
40-
//env.ConfigureNLog("nlog.config");
27+
_configuration = conf;
4128
}
4229

4330
// This method gets called by the runtime. Use this method to add services to the container.
@@ -49,11 +36,9 @@ public void ConfigureServices(IServiceCollection services)
4936
// Add framework services.
5037
services.AddRazorPages();
5138

52-
//services.AddSingleton<IConfiguration>(Configuration);
53-
5439
services.AddMemoryCache();
5540

56-
var hosts = Configuration.GetSection("Hosts");
41+
var hosts = _configuration.GetSection("Hosts");
5742
services.Configure<List<HostConfig>>(hosts);
5843

5944
var strategyDictionary = new Dictionary<HostType, IFileAccessStrategy>
@@ -81,9 +66,6 @@ public void ConfigureServices(IServiceCollection services)
8166
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
8267
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime appLifetime, ILoggerFactory loggerFactory)
8368
{
84-
// passing kibana address to nlog
85-
LogManager.Configuration.Variables["tcpAddress"] = $"{Configuration["Logging:tcpAddress"]}";
86-
8769
app.UseRouting();
8870

8971
app.UsePerformanceCounter();

ImageServer.Core/conf/appsettings.json

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
{
2-
"Logging": {
3-
"IncludeScopes": false,
4-
"LogLevel": {
5-
"Default": "Info"
6-
},
7-
"tcpAddress": "tcp://my.kibanaserver.com:8080"
8-
},
2+
//"Logging": {
3+
// "IncludeScopes": false,
4+
// "LogLevel": {
5+
// "Default": "Info"
6+
// },
7+
// "tcpAddress": "tcp://my.kibanaserver.com:8080"
8+
//},
99

1010
"Hosts": [
1111
{
@@ -23,7 +23,7 @@
2323
{
2424
"Slug": "proxy",
2525
"Type": 2,
26-
"Backend": "https://www.portrasdanuvem.com.br/"
26+
"Backend": "https://i.imgur.com/"
2727
},
2828
{
2929
"Slug": "google",

0 commit comments

Comments
 (0)