Commit 13a0ccdd authored by nitroxis's avatar nitroxis

Initial commit.

parents
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
**/Properties/launchSettings.json
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# TypeScript v1 declaration files
typings/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush
.cr/
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.27130.2020
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UrlShortener", "UrlShortener\UrlShortener.csproj", "{A018B4C9-BF91-4EFF-9BF3-AE79CE736EFD}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{A018B4C9-BF91-4EFF-9BF3-AE79CE736EFD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A018B4C9-BF91-4EFF-9BF3-AE79CE736EFD}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A018B4C9-BF91-4EFF-9BF3-AE79CE736EFD}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A018B4C9-BF91-4EFF-9BF3-AE79CE736EFD}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {920210BC-24B2-4085-9C90-0271264DCF13}
EndGlobalSection
EndGlobal
{
"directory": "wwwroot/lib"
}
namespace UrlShortener
{
public static class Base64
{
private static string table = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_-";
public static ulong Decode(string str)
{
ulong n = 0;
for (int i = 0; i < str.Length; ++i)
{
n = (n << 6) | (uint)table.IndexOf(str[i]);
}
return n;
}
public static string Encode(ulong n, int numChars)
{
char[] chars = new char[numChars];
for (int i = chars.Length - 1; i >= 0; --i)
{
chars[i] = table[(int)(n & 63)];
n >>= 6;
}
return new string(chars);
}
}
}
using System;
using System.Diagnostics;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using UrlShortener.Models;
namespace UrlShortener.Controllers
{
public class HomeController : Controller
{
#region Fields
private readonly Database db;
private readonly UriSettings uriSettings;
#endregion
#region Properties
#endregion
#region Constructors
public HomeController(Database db, UriSettings uriSettings)
{
this.db = db;
this.uriSettings = uriSettings;
}
#endregion
#region Methods
private string shorten(string longUri, out string error)
{
error = null;
if (string.IsNullOrWhiteSpace(longUri))
{
error = "No URI specified.";
}
else if (longUri.Length > this.uriSettings.MaxLength)
{
error = "URI too long.";
}
else if (!Uri.TryCreate(longUri, UriKind.Absolute, out Uri uri))
{
error = "Invalid URI.";
}
else if (!this.uriSettings.AllowedSchemes.Contains(uri.Scheme))
{
error = $"URI scheme \"{uri.Scheme}\" is not allowed.";
}
if (error != null)
return null;
int id = this.db.Add(longUri);
ulong pid = IDGenerator.Permute((ulong)id);
string str = Base64.Encode(pid, 5);
error = null;
return this.makeShortUri(str);
}
private string makeShortUri(string id)
{
return $"{this.HttpContext.Request.Scheme}://{this.HttpContext.Request.Host}/{id}";
}
public IActionResult Index()
{
return this.View(new ShortenerModel());
}
[HttpPost]
public IActionResult Index(ShortenerModel model)
{
string longUri = model.LongUri;
model.ShortUri = this.shorten(longUri, out string error);
model.Error = error;
return this.View(model);
}
public IActionResult Shorten()
{
string longUri = this.HttpContext.Request.QueryString.Value;
if (longUri.StartsWith('?'))
longUri = longUri.Substring(1);
string shortUri = this.shorten(longUri, out string error);
if (error != null)
return this.BadRequest(error);
return this.Content(shortUri, "text/plain");
}
public IActionResult RedirectToLongUrl(string str)
{
if (string.IsNullOrWhiteSpace(str))
return this.NotFound();
ulong pid = Base64.Decode(str);
int id = (int)IDGenerator.Permute(pid);
if(!this.db.TryGet(id, out string url))
return this.NotFound();
return this.RedirectPermanent(url);
}
public IActionResult Error()
{
return this.View(new ErrorViewModel {RequestId = Activity.Current?.Id ?? this.HttpContext.TraceIdentifier});
}
#endregion
}
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace UrlShortener
{
/// <summary>
/// URL database.
/// </summary>
public class Database : IDisposable
{
#region Fields
private static readonly Encoding encoding = new UTF8Encoding(false, true);
private static readonly byte[] newLine = {(byte)'\n'};
private readonly int maxUriLength;
private readonly Stream stream;
private DatabaseEntry[] entries;
private int count;
#endregion
#region Properties
#endregion
#region Constructors
public Database(Stream stream, int maxUriLength)
{
this.stream = stream;
this.entries = new DatabaseEntry[4];
this.count = 0;
this.maxUriLength = maxUriLength;
byte[] currentUrl = new byte[maxUriLength];
long currentUrlOffset = stream.Position;
int currentUrlLength = 0;
void addCurrentUrl()
{
if (currentUrlLength == 0)
return;
string url = encoding.GetString(currentUrl, 0, currentUrlLength);
this.addEntry(new DatabaseEntry
{
Offset = currentUrlOffset,
Length = currentUrlLength,
Hash = url.GetHashCode()
});
}
byte[] buffer = new byte[4096];
for (;;)
{
int n = this.stream.Read(buffer, 0, buffer.Length);
if (n == 0)
break;
for (int i = 0; i < n; ++i)
{
if (buffer[i] == '\n')
{
addCurrentUrl();
currentUrlOffset += currentUrlLength + 1;
currentUrlLength = 0;
}
else
{
if (currentUrlLength >= maxUriLength)
throw new InvalidDataException($"URI {this.count + 1} too long.");
currentUrl[currentUrlLength++] = buffer[i];
}
}
}
if (currentUrlLength > 0)
{
// File doesn't end with a new line.
addCurrentUrl();
// Add new line.
this.stream.Write(newLine, 0, newLine.Length);
}
}
#endregion
#region Methods
/// <summary>
/// Adds the specified URI to the database and returns the index.
/// </summary>
/// <param name="uri"></param>
/// <returns></returns>
public int Add(string uri)
{
if (uri == null)
throw new ArgumentNullException(nameof(uri));
if (uri.Length > this.maxUriLength)
throw new ArgumentException("URI is too long.", nameof(uri));
int hash = uri.GetHashCode();
lock (this)
{
for (int i = 0; i < this.count; ++i)
{
if (this.entries[i].Hash == hash && this.TryGet(i, out string uri2) && uri2 == uri)
{
return i;
}
}
int index = this.count;
this.addInternal(uri);
return index;
}
}
/// <summary>
/// Gets the URL at the specified index.
/// </summary>
/// <param name="index"></param>
/// <param name="uri"></param>
/// <returns></returns>
public bool TryGet(int index, out string uri)
{
if (index < 0 || index >= this.count)
{
uri = null;
return false;
}
byte[] data;
lock (this)
{
DatabaseEntry entry = this.entries[index];
data = new byte[entry.Length];
int numBytesRead = 0;
this.stream.Position = entry.Offset;
while (numBytesRead < data.Length)
{
int n = this.stream.Read(data, numBytesRead, data.Length - numBytesRead);
if (n == 0)
throw new EndOfStreamException();
numBytesRead += n;
}
}
uri = encoding.GetString(data);
return true;
}
private void addEntry(DatabaseEntry entry)
{
if (this.count == this.entries.Length)
{
Array.Resize(ref this.entries, this.entries.Length * 2);
}
this.entries[this.count++] = entry;
}
private void addInternal(string uri)
{
byte[] data = encoding.GetBytes(uri);
long offset = this.stream.Length;
this.stream.Position = this.stream.Length;
this.stream.Write(data, 0, data.Length);
this.stream.Write(newLine, 0, newLine.Length);
this.stream.Flush();
this.addEntry(new DatabaseEntry
{
Offset = offset,
Length = data.Length,
Hash = uri.GetHashCode()
});
}
public void Dispose()
{
this.stream?.Dispose();
}
#endregion
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace UrlShortener
{
public struct DatabaseEntry
{
#region Fields
public long Offset;
public int Length;
public int Hash;
#endregion
#region Properties
#endregion
#region Constructors
#endregion
#region Methods
#endregion
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace UrlShortener
{
public static class IDGenerator
{
#region Fields
public const int Characters = 5;
private const int rounds = 10;
private const int bits = Characters * 6;
private const ulong max = 1ul << bits;