Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 1 addition & 5 deletions URLShortener.Data/DBContext/URLShortenerDBContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,7 @@ public URLShortenerDBContext (DbContextOptions<URLShortenerDBContext> options) :
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<URLInfo>()
.HasIndex(x => x.HashedURL);

modelBuilder.Entity<URLInfo>()
.HasIndex(x => new { x.URL, x.HashedURL }).IsUnique();

.HasIndex(x => x.HashedURL).IsUnique();
}

public DbSet<URLInfo> URLInfos { get; set; }
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,7 @@ protected override void Up(MigrationBuilder migrationBuilder)
migrationBuilder.CreateIndex(
name: "IX_URLInfos_HashedURL",
table: "URLInfos",
column: "HashedURL");

migrationBuilder.CreateIndex(
name: "IX_URLInfos_URL_HashedURL",
table: "URLInfos",
columns: new[] { "URL", "HashedURL" },
column: "HashedURL",
unique: true);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,7 @@ protected override void BuildModel(ModelBuilder modelBuilder)

b.HasKey("Id");

b.HasIndex("HashedURL");

b.HasIndex("URL", "HashedURL")
b.HasIndex("HashedURL")
.IsUnique();

b.ToTable("URLInfos");
Expand Down
50 changes: 46 additions & 4 deletions URLShortener/Controllers/ShortURLController.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System;
using System.Threading.Tasks;
using URLShortener.Response;
using URLShortener.Services;

namespace URLShortener.Controllers
{
Expand All @@ -9,10 +13,15 @@ namespace URLShortener.Controllers
public class ShortURLController : ControllerBase
{
private readonly ILogger<ShortURLController> _logger;
private readonly IConfiguration _configuration;
private readonly IURLShortenerService _urlShortenerService;
private const string ServiceURL = "ServiceURL";

public ShortURLController(ILogger<ShortURLController> logger)
public ShortURLController(ILogger<ShortURLController> logger, IURLShortenerService urlShortenerService, IConfiguration configuration)
{
_logger = logger;
_configuration = configuration;
_urlShortenerService = urlShortenerService;
}


Expand All @@ -26,10 +35,43 @@ public ShortURLController(ILogger<ShortURLController> logger)
/// <response code="200">With short url</response>
/// <response code="401">Unauthorized.</response>
[HttpPost]
public async Task<IActionResult> Post()
public async Task<IActionResult> Post([FromQuery]string url)
{
await Task.Delay(10);
return Ok("tiny url");
bool isValidUrl = Uri.TryCreate(url, UriKind.Absolute, out Uri uriResult)
&& (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);

if(!isValidUrl)
{
return BadRequest();
}

var hashedURL = await _urlShortenerService.SaveURL(url);
var serviceURL = _configuration.GetValue<string>(ServiceURL);
var shortURL = String.Concat(serviceURL,"/shorturl/",hashedURL);
var response = new ShortURLResponse() { ShortURL = shortURL, Code = hashedURL };
return Ok(response);
}

/// <summary>
/// Redirect to actual URL on providing shirtURL
/// </summary>
/// <remarks>
/// ### Usage Notes ###
/// 1. A valid User with jwt
/// </remarks>
/// <response code="200">With short url</response>
/// <response code="401">Unauthorized.</response>
[HttpGet]
[Route("{shortURL}")]
[ApiExplorerSettings(IgnoreApi = true)]
public async Task<IActionResult> Get([FromRoute]string shortURL)
{
var url = await _urlShortenerService.GetURL(shortURL);
if(url == null)
{
return NotFound();
}
return Redirect(url);
}
}
}
8 changes: 8 additions & 0 deletions URLShortener/Response/ShortURLResponse.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace URLShortener.Response
{
public class ShortURLResponse
{
public string ShortURL { get; set; }
public string Code { get; set; }
}
}
52 changes: 52 additions & 0 deletions URLShortener/Services/URLShortenerService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using URLShortener.Data.DBContext;
using URLShortener.Data.Entities;
using URLShortener.Utils;

namespace URLShortener.Services
{
public class URLShortenerService : IURLShortenerService
{
private readonly ILogger<URLShortenerService> _logger;
private readonly Func<URLShortenerDBContext> _dbContextProvider;

public URLShortenerService(Func<URLShortenerDBContext> dbContextProvider, ILogger<URLShortenerService> logger)
{
_dbContextProvider = dbContextProvider;
_logger = logger;
}


public async Task<string> GetURL(string hashedURL)
{
using(var dbContext = _dbContextProvider())
{
var urlInfo = await dbContext.URLInfos.AsNoTracking()
.SingleOrDefaultAsync(x => x.HashedURL == hashedURL);
return urlInfo.URL;
}
}

public async Task<string> SaveURL(string url)
{
using (var dbContext = _dbContextProvider())
{
var hashedURL = HashGenerator.Generate_SHA256_Hash(url);
var urlInfo = await dbContext.URLInfos.SingleOrDefaultAsync(x => x.HashedURL == hashedURL);
if(urlInfo == null)
{
urlInfo = new URLInfo() { URL = url, CreatedOn = DateTime.UtcNow };
urlInfo.HashedURL = hashedURL;
dbContext.URLInfos.Add(urlInfo);
await dbContext.SaveChangesAsync();
}
return urlInfo.HashedURL;
}
}
}
}
10 changes: 10 additions & 0 deletions URLShortener/Services/interfaces/IURLShortenerService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
using System.Threading.Tasks;

namespace URLShortener.Services
{
public interface IURLShortenerService
{
Task<string> SaveURL(string url);
Task<string> GetURL(string hashedURL);
}
}
2 changes: 2 additions & 0 deletions URLShortener/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using URLShortener.Data.DBContext;
using URLShortener.Services;

namespace URLShortener
{
Expand All @@ -35,6 +36,7 @@ public void ConfigureServices(IServiceCollection services)
var opt = new DbContextOptionsBuilder<URLShortenerDBContext>()
.UseSqlServer(Configuration.GetConnectionString("URLShortenerDatabase"))
.Options;
services.AddSingleton<IURLShortenerService, URLShortenerService>();
services.AddSingleton<Func<URLShortenerDBContext>>
(
() => new URLShortenerDBContext(opt)
Expand Down
22 changes: 22 additions & 0 deletions URLShortener/Utils/HashGenerator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using System.Security.Cryptography;
using System.Text;

namespace URLShortener.Utils
{
public static class HashGenerator
{
public static string Generate_SHA256_Hash(string value)
{
StringBuilder Sb = new StringBuilder();

using (var hash = SHA256.Create())
{
Encoding enc = Encoding.UTF8;
foreach (byte b in hash.ComputeHash(enc.GetBytes(value)))
Sb.Append(b.ToString("x2"));
}

return Sb.ToString();
}
}
}
1 change: 1 addition & 0 deletions URLShortener/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"Microsoft.Hosting.Lifetime": "Information"
}
},
"ServiceURL": "http://localhost:5011",
"ConnectionStrings": {
"URLShortenerDatabase": "Server=(LocalDb)\\MSSQLLocalDB;Database=URLShortener;Trusted_Connection=True;"
},
Expand Down