├── Statics └── Adsız-2024-12-16-2000.png ├── src └── Web │ ├── UseCases │ ├── UrlToken │ │ ├── SetTokenUsed │ │ │ ├── SetTokenUsedResponse.cs │ │ │ ├── SetTokenUsedCommand.cs │ │ │ └── SetTokenUsedHandler.cs │ │ └── GetUnusedToken │ │ │ ├── GetUnusedTokenResponse.cs │ │ │ ├── GetUnusedTokenQuery.cs │ │ │ └── GetUnusedTokenHandler.cs │ ├── UrlShorten │ │ ├── GetShortenedUrl │ │ │ ├── GetShortenedUrlResponse.cs │ │ │ ├── GetShortenedUrlQuery.cs │ │ │ └── GetShortenedUrlHandler.cs │ │ └── ShortUrl │ │ │ ├── ShortUrlResponse.cs │ │ │ ├── ShortUrlCommand.cs │ │ │ └── ShortUrlHandler.cs │ └── ValidationBehavior.cs │ ├── appsettings.Development.json │ ├── Common │ ├── Constants │ │ └── RedisConstant.cs │ └── Models │ │ ├── Endpoints │ │ ├── UrlShort │ │ │ └── ShortUrlRequest.cs │ │ └── Result.cs │ │ ├── Validators │ │ └── Endpoint │ │ │ └── ShortUrlValidator.cs │ │ └── Options │ │ └── AppSettingModel.cs │ ├── Extensions │ └── ResultExtension.cs │ ├── Data │ ├── Entities │ │ ├── UrlToken.cs │ │ └── UrlShorten.cs │ ├── MongoDbContext.cs │ └── Configurations │ │ ├── UrlShortenConfiguration.cs │ │ └── UrlTokenConfiguration.cs │ ├── Endpoints │ ├── TestEndpoint.cs │ └── UrlShortEndpoint.cs │ ├── Dockerfile │ ├── Properties │ └── launchSettings.json │ ├── Program.cs │ ├── appsettings.json │ ├── Helpers │ ├── JobDistributionHelper.cs │ └── TokenBuilder.cs │ ├── Jobs │ ├── BaseJob.cs │ └── TokenSeedJob.cs │ ├── Filter │ └── ValidationFilter.cs │ ├── Services │ ├── Interfaces │ │ └── ICacheService.cs │ └── Implementations │ │ └── CacheService.cs │ ├── Middlewares │ └── GlobalExceptionMiddleware.cs │ ├── Web.csproj │ └── DependencyInjection.cs ├── .dockerignore ├── test ├── UnitTest │ └── UnitTest.csproj └── LoadTestK6 │ ├── regular_load_test.js │ └── progressive_load_test.js ├── README.md ├── LICENSE ├── docker-compose.yml ├── Shortener.sln └── .gitignore /Statics/Adsız-2024-12-16-2000.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Filiphasan/dotnet-minify-url/HEAD/Statics/Adsız-2024-12-16-2000.png -------------------------------------------------------------------------------- /src/Web/UseCases/UrlToken/SetTokenUsed/SetTokenUsedResponse.cs: -------------------------------------------------------------------------------- 1 | namespace Web.UseCases.UrlToken.SetTokenUsed; 2 | 3 | public class SetTokenUsedResponse 4 | { 5 | 6 | } -------------------------------------------------------------------------------- /src/Web/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/Web/UseCases/UrlToken/GetUnusedToken/GetUnusedTokenResponse.cs: -------------------------------------------------------------------------------- 1 | namespace Web.UseCases.UrlToken.GetUnusedToken; 2 | 3 | public class GetUnusedTokenResponse 4 | { 5 | public string? Token { get; set; } 6 | } -------------------------------------------------------------------------------- /src/Web/UseCases/UrlShorten/GetShortenedUrl/GetShortenedUrlResponse.cs: -------------------------------------------------------------------------------- 1 | namespace Web.UseCases.UrlShorten.GetShortenedUrl; 2 | 3 | public class GetShortenedUrlResponse 4 | { 5 | public string? LongUrl { get; set; } 6 | } -------------------------------------------------------------------------------- /src/Web/UseCases/UrlToken/GetUnusedToken/GetUnusedTokenQuery.cs: -------------------------------------------------------------------------------- 1 | using MediatR; 2 | using Web.Common.Models.Endpoints; 3 | 4 | namespace Web.UseCases.UrlToken.GetUnusedToken; 5 | 6 | public class GetUnusedTokenQuery : IRequest> 7 | { 8 | } -------------------------------------------------------------------------------- /src/Web/UseCases/UrlShorten/ShortUrl/ShortUrlResponse.cs: -------------------------------------------------------------------------------- 1 | namespace Web.UseCases.UrlShorten.ShortUrl; 2 | 3 | public class ShortUrlResponse 4 | { 5 | public string Token { get; set; } = null!; 6 | public string ShortenedUrl { get; set; } = null!; 7 | public string? QrCode { get; set; } 8 | } -------------------------------------------------------------------------------- /src/Web/Common/Constants/RedisConstant.cs: -------------------------------------------------------------------------------- 1 | namespace Web.Common.Constants; 2 | 3 | public static class RedisConstant 4 | { 5 | public static class Key 6 | { 7 | public const string TokenSeedList = "TokenSeedList"; 8 | public const string ShortUrl = "ShortUrl:{0}"; 9 | } 10 | } -------------------------------------------------------------------------------- /src/Web/UseCases/UrlToken/SetTokenUsed/SetTokenUsedCommand.cs: -------------------------------------------------------------------------------- 1 | using MediatR; 2 | using Web.Common.Models.Endpoints; 3 | 4 | namespace Web.UseCases.UrlToken.SetTokenUsed; 5 | 6 | public class SetTokenUsedCommand : IRequest> 7 | { 8 | public string Token { get; set; } = null!; 9 | } -------------------------------------------------------------------------------- /src/Web/UseCases/UrlShorten/GetShortenedUrl/GetShortenedUrlQuery.cs: -------------------------------------------------------------------------------- 1 | using MediatR; 2 | using Web.Common.Models.Endpoints; 3 | 4 | namespace Web.UseCases.UrlShorten.GetShortenedUrl; 5 | 6 | public class GetShortenedUrlQuery : IRequest> 7 | { 8 | public string? Token { get; set; } 9 | } -------------------------------------------------------------------------------- /src/Web/Extensions/ResultExtension.cs: -------------------------------------------------------------------------------- 1 | using Web.Common.Models.Endpoints; 2 | 3 | namespace Web.Extensions; 4 | 5 | public static class ResultExtension 6 | { 7 | public static IResult ToResult(this Result result) where T : class 8 | { 9 | return Results.Json(result, statusCode: result.StatusCode); 10 | } 11 | } -------------------------------------------------------------------------------- /src/Web/Data/Entities/UrlToken.cs: -------------------------------------------------------------------------------- 1 | using MongoDB.Bson; 2 | 3 | namespace Web.Data.Entities; 4 | 5 | public class UrlToken 6 | { 7 | public ObjectId Id { get; set; } 8 | public string Token { get; set; } = null!; 9 | public bool IsUsed { get; set; } 10 | public DateTime CreatedAt { get; set; } 11 | public DateTime? UsedAt { get; set; } 12 | } -------------------------------------------------------------------------------- /src/Web/Data/Entities/UrlShorten.cs: -------------------------------------------------------------------------------- 1 | using MongoDB.Bson; 2 | 3 | namespace Web.Data.Entities; 4 | 5 | public class UrlShorten 6 | { 7 | public ObjectId Id { get; set; } 8 | public string Token { get; set; } = null!; 9 | public string Url { get; set; } = null!; 10 | public DateTime CreatedAt { get; set; } 11 | public DateTime ExpiredAt { get; set; } 12 | } -------------------------------------------------------------------------------- /src/Web/UseCases/UrlShorten/ShortUrl/ShortUrlCommand.cs: -------------------------------------------------------------------------------- 1 | using MediatR; 2 | using Web.Common.Models.Endpoints; 3 | 4 | namespace Web.UseCases.UrlShorten.ShortUrl; 5 | 6 | public class ShortUrlCommand : IRequest> 7 | { 8 | public string? Url { get; set; } 9 | public int? ExpireDay { get; set; } 10 | public bool HasQrCode { get; set; } 11 | } -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | **/.dockerignore 2 | **/.env 3 | **/.git 4 | **/.gitignore 5 | **/.project 6 | **/.settings 7 | **/.toolstarget 8 | **/.vs 9 | **/.vscode 10 | **/.idea 11 | **/*.*proj.user 12 | **/*.dbmdl 13 | **/*.jfm 14 | **/azds.yaml 15 | **/bin 16 | **/charts 17 | **/docker-compose* 18 | **/Dockerfile* 19 | **/node_modules 20 | **/npm-debug.log 21 | **/obj 22 | **/secrets.dev.yaml 23 | **/values.dev.yaml 24 | LICENSE 25 | README.md -------------------------------------------------------------------------------- /src/Web/Common/Models/Endpoints/UrlShort/ShortUrlRequest.cs: -------------------------------------------------------------------------------- 1 | using Web.UseCases.UrlShorten.ShortUrl; 2 | 3 | namespace Web.Common.Models.Endpoints.UrlShort; 4 | 5 | public class ShortUrlRequest 6 | { 7 | public string? Url { get; set; } 8 | public int? ExpireDay { get; set; } 9 | public bool HasQrCode { get; set; } = false; 10 | 11 | public ShortUrlCommand ToCommand() 12 | { 13 | return new ShortUrlCommand 14 | { 15 | Url = Url, 16 | ExpireDay = ExpireDay, 17 | HasQrCode = HasQrCode, 18 | }; 19 | } 20 | } -------------------------------------------------------------------------------- /src/Web/Common/Models/Validators/Endpoint/ShortUrlValidator.cs: -------------------------------------------------------------------------------- 1 | using FluentValidation; 2 | using Web.Common.Models.Endpoints.UrlShort; 3 | 4 | namespace Web.Common.Models.Validators.Endpoint; 5 | 6 | public class ShortUrlValidator : AbstractValidator 7 | { 8 | public ShortUrlValidator() 9 | { 10 | RuleFor(x => x.Url) 11 | .Must(x => !string.IsNullOrWhiteSpace(x)) 12 | .WithMessage("Url is required"); 13 | 14 | RuleFor(x => x.Url) 15 | .Must(x => Uri.TryCreate(x, UriKind.RelativeOrAbsolute, out _)) 16 | .WithMessage("Url is invalid"); 17 | } 18 | } -------------------------------------------------------------------------------- /src/Web/Endpoints/TestEndpoint.cs: -------------------------------------------------------------------------------- 1 | using Carter; 2 | using Web.Common.Models.Options; 3 | using Web.Helpers; 4 | 5 | namespace Web.Endpoints; 6 | 7 | public class TestEndpoint : ICarterModule 8 | { 9 | public void AddRoutes(IEndpointRouteBuilder app) 10 | { 11 | app.MapGet("/test", (AppSettingModel setting) => 12 | { 13 | var tokenBuilder = new TokenBuilder() 14 | .WithEpoch(setting.UrlToken.EpochDate) 15 | .WithAdditionalCharLength(3); 16 | 17 | var token = tokenBuilder.Build(); 18 | 19 | return Results.Ok(token); 20 | }); 21 | } 22 | } -------------------------------------------------------------------------------- /src/Web/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM mcr.microsoft.com/dotnet/aspnet:9.0 AS base 2 | USER $APP_UID 3 | WORKDIR /app 4 | EXPOSE 8080 5 | EXPOSE 8081 6 | 7 | FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build 8 | ARG BUILD_CONFIGURATION=Release 9 | WORKDIR /src 10 | COPY ["src/Web/Web.csproj", "src/Web/"] 11 | RUN dotnet restore "src/Web/Web.csproj" 12 | COPY . . 13 | WORKDIR "/src/src/Web" 14 | RUN dotnet build "Web.csproj" -c $BUILD_CONFIGURATION -o /app/build 15 | 16 | FROM build AS publish 17 | ARG BUILD_CONFIGURATION=Release 18 | RUN dotnet publish "Web.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false 19 | 20 | FROM base AS final 21 | WORKDIR /app 22 | COPY --from=publish /app/publish . 23 | ENTRYPOINT ["dotnet", "Web.dll"] 24 | -------------------------------------------------------------------------------- /src/Web/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/launchsettings.json", 3 | "profiles": { 4 | "http": { 5 | "commandName": "Project", 6 | "dotnetRunMessages": true, 7 | "launchBrowser": false, 8 | "applicationUrl": "http://localhost:5259", 9 | "environmentVariables": { 10 | "ASPNETCORE_ENVIRONMENT": "Development" 11 | } 12 | }, 13 | "https": { 14 | "commandName": "Project", 15 | "dotnetRunMessages": true, 16 | "launchBrowser": false, 17 | "applicationUrl": "https://localhost:7155;http://localhost:5259", 18 | "environmentVariables": { 19 | "ASPNETCORE_ENVIRONMENT": "Development" 20 | } 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /test/UnitTest/UnitTest.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net9.0 5 | enable 6 | enable 7 | false 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /src/Web/Program.cs: -------------------------------------------------------------------------------- 1 | using Carter; 2 | using Scalar.AspNetCore; 3 | using Web; 4 | using Web.Middlewares; 5 | 6 | var builder = WebApplication.CreateBuilder(args); 7 | 8 | // Add services to the container. 9 | // Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi 10 | builder.Services.AddOpenApi(); 11 | builder.Services.AddCarter(); 12 | builder.Services.AddWeb(builder.Configuration); 13 | builder.Services.AddExceptionHandler(); 14 | 15 | var app = builder.Build(); 16 | 17 | // Configure the HTTP request pipeline. 18 | app.MapOpenApi(); 19 | app.MapScalarApiReference(opt => 20 | { 21 | opt.WithTitle("URL Shortener") 22 | .WithDarkMode(true) 23 | .WithDefaultHttpClient(ScalarTarget.CSharp, ScalarClient.HttpClient); 24 | }); 25 | 26 | app.UseHttpsRedirection(); 27 | 28 | app.MapCarter(); 29 | await app.RunAsync(); -------------------------------------------------------------------------------- /src/Web/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*", 9 | "Settings": { 10 | "Server": { 11 | "Scheme": "https", 12 | "Host": "localhost", 13 | "Port": 7155 14 | }, 15 | "MongoDb": { 16 | "User": "admin", 17 | "Password": "2D1wIPm5wzvJNa8OXMYShLGN", 18 | "Host": "127.0.0.1", 19 | "Port": 27017, 20 | "Database": "minifyurl" 21 | }, 22 | "Redis": { 23 | "Host": "127.0.0.1", 24 | "Port": "6379", 25 | "Password": "8mn1JpZ5oumuU2zTNwgK", 26 | "Database": "0" 27 | }, 28 | "UrlToken": { 29 | "PoolingSize": 50000, 30 | "ExtendSize": 10000, 31 | "ExpirationDays": 120, 32 | "EpochDate": "2024-12-01" 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/Web/Helpers/JobDistributionHelper.cs: -------------------------------------------------------------------------------- 1 | namespace Web.Helpers; 2 | 3 | public static class JobDistributionHelper 4 | { 5 | private static readonly List Jobs = []; 6 | 7 | public static JobStatusRecord GetOrAddJob(string name) 8 | { 9 | var job = Jobs.Find(x => x.Name == name); 10 | if (job is not null) 11 | { 12 | return job; 13 | } 14 | 15 | job = new JobStatusRecord{ Name = name, Lock = false }; 16 | Jobs.Add(job); 17 | return job; 18 | } 19 | 20 | public static void Lock(this JobStatusRecord job) 21 | { 22 | job.Lock = true; 23 | } 24 | 25 | public static void Unlock(this JobStatusRecord job) 26 | { 27 | job.Lock = false; 28 | } 29 | } 30 | 31 | public class JobStatusRecord 32 | { 33 | public string Name { get; set; } = null!; 34 | public bool Lock { get; set; } 35 | } -------------------------------------------------------------------------------- /src/Web/UseCases/UrlToken/SetTokenUsed/SetTokenUsedHandler.cs: -------------------------------------------------------------------------------- 1 | using MediatR; 2 | using MongoDB.Driver; 3 | using Web.Common.Models.Endpoints; 4 | using Web.Data; 5 | 6 | namespace Web.UseCases.UrlToken.SetTokenUsed; 7 | 8 | public class SetTokenUsedHandler(MongoDbContext dbContext) : IRequestHandler> 9 | { 10 | public async Task> Handle(SetTokenUsedCommand request, CancellationToken cancellationToken) 11 | { 12 | var filter = Builders.Filter 13 | .Eq(x => x.Token, request.Token); 14 | var updateFilter = Builders.Update 15 | .Set(x => x.IsUsed, true) 16 | .Set(x => x.UsedAt, DateTime.UtcNow); 17 | await dbContext.UrlTokens.UpdateOneAsync(filter, updateFilter, cancellationToken: cancellationToken); 18 | return Result.Success(new SetTokenUsedResponse()); 19 | } 20 | } -------------------------------------------------------------------------------- /src/Web/Jobs/BaseJob.cs: -------------------------------------------------------------------------------- 1 | using Quartz; 2 | using Web.Helpers; 3 | 4 | namespace Web.Jobs; 5 | 6 | public abstract class BaseJob(ILogger logger) : IJob 7 | where TJob : class 8 | { 9 | protected abstract Task ExecuteAsync(IJobExecutionContext context); 10 | 11 | public async Task Execute(IJobExecutionContext context) 12 | { 13 | var methodName = typeof(TJob).Name; 14 | var job = JobDistributionHelper.GetOrAddJob(methodName); 15 | try 16 | { 17 | if (job.Lock) 18 | { 19 | logger.LogInformation("{MethodName} is locked", methodName); 20 | return; 21 | } 22 | 23 | job.Lock(); 24 | 25 | await ExecuteAsync(context); 26 | 27 | job.Unlock(); 28 | } 29 | catch (Exception ex) 30 | { 31 | job.Unlock(); 32 | logger.LogError(ex, "{MethodName} exception", methodName); 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /src/Web/UseCases/ValidationBehavior.cs: -------------------------------------------------------------------------------- 1 | using FluentValidation; 2 | using MediatR; 3 | using Web.Common.Models.Endpoints; 4 | 5 | namespace Web.UseCases; 6 | 7 | public class ValidationBehavior(IEnumerable> validators) 8 | : IPipelineBehavior 9 | where TRequest : IRequest 10 | where TResponse : Result 11 | { 12 | public async Task Handle(TRequest request, RequestHandlerDelegate next, CancellationToken cancellationToken) 13 | { 14 | if (!validators.Any()) 15 | { 16 | return await next(); 17 | } 18 | 19 | var results = await Task.WhenAll(validators.Select(v => v.ValidateAsync(request, cancellationToken))); 20 | var failures = results.SelectMany(r => r.Errors).Where(f => f != null).ToList(); 21 | if (failures.Count > 0) 22 | { 23 | throw new ValidationException(failures); 24 | } 25 | 26 | return await next(); 27 | } 28 | } -------------------------------------------------------------------------------- /test/LoadTestK6/regular_load_test.js: -------------------------------------------------------------------------------- 1 | import http from 'k6/http'; 2 | import { check } from 'k6'; 3 | 4 | export let options = { 5 | vus: 30, 6 | duration: '10s' 7 | } 8 | 9 | export default function () { 10 | const uniqueId = getUniqueId(); 11 | const postUrl = "http://localhost:5001/api/url-shorts" 12 | 13 | const longUrl = `https://www.google.com/search?q=${uniqueId}`; 14 | const payload = JSON.stringify({ 15 | url: longUrl, 16 | hasQrCode: true 17 | }); 18 | const params = { 19 | headers: { 20 | 'Content-Type': 'application/json' 21 | }, 22 | } 23 | 24 | let res = http.post(postUrl, payload, params); 25 | 26 | check(res, { 27 | 'status is 200': (r) => r.status === 200, 28 | }); 29 | } 30 | 31 | function getUniqueId() { 32 | const ticks = new Date().getTime(); 33 | let uniqueId = ticks.toString(16); 34 | const randomNum = Math.floor(Math.random() * 10000); 35 | uniqueId += randomNum; 36 | return uniqueId; 37 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Dotnet Minify Url 2 | Dotnet 9 URL Shortener REST API Project example with MongoDB 3 | 4 | # Architecture 5 | ![Dotnet Minfiy Url Architecture](Statics/Adsız-2024-12-16-2000.png) 6 | 7 | # Dependencies 8 | - [MongoDB](https://www.mongodb.com/try/download/community) 9 | - [Redis](https://redis.io/download) 10 | - [Docker](https://www.docker.com/products/docker-desktop) 11 | - [Docker Compose](https://docs.docker.com/compose/install/) 12 | - [Dotnet 9](https://dotnet.microsoft.com/download/dotnet/9.0) 13 | 14 | # How to run 15 | - Clone the repository with `git clone` 16 | - Go to the project current directory 17 | - Run `docker-compose up -d` to start MongoDB and Redis and the project 18 | 19 | # Load Test With K6 20 | - Install K6 with `brew install k6` or `choco install k6` or go to [K6 Download](https://grafana.com/docs/k6/latest/set-up/install-k6/) 21 | - Open Terminal on the project directory 22 | - Go to `test/LoadTestK6` directory 23 | - Run `k6 run regular_load_test.js` to run the regular load test 24 | - Run `k6 run progressive_load_test.js` to run the progressive load test 25 | -------------------------------------------------------------------------------- /src/Web/Filter/ValidationFilter.cs: -------------------------------------------------------------------------------- 1 | using FluentValidation; 2 | using Web.Common.Models.Endpoints; 3 | using Web.Extensions; 4 | 5 | namespace Web.Filter; 6 | 7 | public class ValidationFilter(IValidator validator) : IEndpointFilter where T : class 8 | { 9 | public async ValueTask InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next) 10 | { 11 | if (context.Arguments.FirstOrDefault(x => x is T) is not T model) 12 | { 13 | var result = Result.Invalid("Invalid Request"); 14 | return result.ToResult(); 15 | } 16 | 17 | var validationResult = await validator.ValidateAsync(model); 18 | if (!validationResult.IsValid) 19 | { 20 | var errors = validationResult.Errors.GroupBy(x => x.PropertyName).ToDictionary(x => x.Key, x => x.Select(m => m.ErrorMessage).FirstOrDefault()); 21 | var result = Result.Invalid("Invalid Request", errors); 22 | return result.ToResult(); 23 | } 24 | 25 | return await next(context); 26 | } 27 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2025 Hasan Erdal 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /test/LoadTestK6/progressive_load_test.js: -------------------------------------------------------------------------------- 1 | import http from 'k6/http'; 2 | import { check, sleep } from 'k6'; 3 | 4 | export let options = { 5 | stages: [ 6 | { duration: '1m', target: 10 }, 7 | { duration: '2m', target: 50 }, 8 | { duration: '1m', target: 20 }, 9 | { duration: '1m', target: 0 }, 10 | ] 11 | } 12 | 13 | export default function () { 14 | const uniqueId = getUniqueId(); 15 | const postUrl = "http://localhost:5001/api/url-shorts" 16 | 17 | const longUrl = `https://www.google.com/search?q=${uniqueId}`; 18 | const payload = JSON.stringify({ 19 | url: longUrl, 20 | hasQrCode: true 21 | }); 22 | const params = { 23 | headers: { 24 | 'Content-Type': 'application/json' 25 | }, 26 | } 27 | 28 | let res = http.post(postUrl, payload, params); 29 | 30 | check(res, { 31 | 'status is 200': (r) => r.status === 200, 32 | }); 33 | 34 | sleep(0.01); 35 | } 36 | 37 | function getUniqueId() { 38 | const ticks = new Date().getTime(); 39 | let uniqueId = ticks.toString(16); 40 | const randomNum = Math.floor(Math.random() * 10000); 41 | uniqueId += randomNum; 42 | return uniqueId; 43 | } -------------------------------------------------------------------------------- /src/Web/Services/Interfaces/ICacheService.cs: -------------------------------------------------------------------------------- 1 | namespace Web.Services.Interfaces; 2 | 3 | public interface ICacheService 4 | { 5 | Task PingAsync(CancellationToken cancellationToken = default); 6 | Task SetAsync(string key, TModel value, TimeSpan expiration, CancellationToken cancellationToken = default) 7 | where TModel : class; 8 | Task SetAsync(string key, TModel value, DateTimeOffset expiration, CancellationToken cancellationToken = default) 9 | where TModel : class; 10 | Task GetAsync(string key, CancellationToken cancellationToken = default) 11 | where TModel : class; 12 | Task ExistsAsync(string key, CancellationToken cancellationToken = default); 13 | Task RemoveAsync(string key, CancellationToken cancellationToken = default); 14 | Task AddListRightAsync(string key, TModel value, CancellationToken cancellationToken = default) 15 | where TModel : class; 16 | Task AddListRightBulkAsync(string key, TModel[] values, CancellationToken cancellationToken = default) 17 | where TModel : class; 18 | Task ListLeftPopAsync(string key, CancellationToken cancellationToken = default) 19 | where TModel : class; 20 | } -------------------------------------------------------------------------------- /src/Web/Data/MongoDbContext.cs: -------------------------------------------------------------------------------- 1 | using MongoDB.Driver; 2 | using Web.Common.Models.Options; 3 | using Web.Data.Configurations; 4 | using Web.Data.Entities; 5 | 6 | namespace Web.Data; 7 | 8 | public class MongoDbContext 9 | { 10 | public MongoDbContext(IMongoClient client, AppSettingModel appSettingModel) 11 | { 12 | var databaseName = appSettingModel.MongoDb.Database; 13 | Database = client.GetDatabase(databaseName); 14 | 15 | ConfigureEntities(); 16 | } 17 | 18 | private void ConfigureEntities() 19 | { 20 | // Configure entities 21 | UrlTokenConfiguration.Configure(); 22 | UrlShortenConfiguration.Configure(); 23 | 24 | // Configure indexes 25 | UrlTokens.Indexes.CreateMany(UrlTokenConfiguration.CreateIndexes); 26 | UrlShortens.Indexes.CreateMany(UrlShortenConfiguration.CreateIndexes); 27 | } 28 | 29 | // Database 30 | private IMongoDatabase Database { get; } 31 | 32 | // Collection 33 | public IMongoCollection UrlTokens => GetCollection(); 34 | public IMongoCollection UrlShortens => GetCollection(); 35 | 36 | private IMongoCollection GetCollection(string? name = null) 37 | { 38 | name ??= typeof(T).Name; 39 | return Database.GetCollection(name); 40 | } 41 | } -------------------------------------------------------------------------------- /src/Web/Middlewares/GlobalExceptionMiddleware.cs: -------------------------------------------------------------------------------- 1 | using FluentValidation; 2 | using Microsoft.AspNetCore.Diagnostics; 3 | using Web.Common.Models.Endpoints; 4 | 5 | namespace Web.Middlewares; 6 | 7 | public class GlobalExceptionMiddleware(ILogger logger) : IExceptionHandler 8 | { 9 | public async ValueTask TryHandleAsync(HttpContext httpContext, Exception exception, CancellationToken cancellationToken) 10 | { 11 | logger.LogError(exception, "An unhandled exception has occurred while executing the request"); 12 | 13 | httpContext.Response.ContentType = "application/json"; 14 | 15 | Result response; 16 | if (exception is ValidationException validationException) 17 | { 18 | var errors = validationException.Errors.GroupBy(x => x.PropertyName).ToDictionary(x => x.Key, x => x.Select(y => y.ErrorMessage).FirstOrDefault()); 19 | response = Result.Invalid("Invalid", errors); 20 | } 21 | else 22 | { 23 | response = Result.Error(500, "An unhandled exception has occurred while executing the request"); 24 | } 25 | 26 | httpContext.Response.StatusCode = response.StatusCode; 27 | await httpContext.Response.WriteAsJsonAsync(response, cancellationToken); 28 | 29 | return true; 30 | } 31 | } -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | volumes: 2 | dotnet-minify-url: 3 | driver: local 4 | 5 | services: 6 | mongodb: 7 | image: mongo 8 | container_name: mongodb 9 | restart: always 10 | ports: 11 | - "27017:27017" 12 | volumes: 13 | - dotnet-minify-url:/data/db 14 | environment: 15 | - MONGO_INITDB_ROOT_USERNAME=admin 16 | - MONGO_INITDB_ROOT_PASSWORD=2D1wIPm5wzvJNa8OXMYShLGN 17 | 18 | redis: 19 | image: redis 20 | container_name: redis 21 | restart: always 22 | ports: 23 | - "6379:6379" 24 | volumes: 25 | - dotnet-minify-url:/data/db 26 | environment: 27 | - REDIS_PASSWORD=8mn1JpZ5oumuU2zTNwgK 28 | command: 29 | - redis-server 30 | 31 | minify-url: 32 | image: minify-url 33 | container_name: minify-url 34 | build: 35 | context: . 36 | dockerfile: src/Web/Dockerfile 37 | restart: always 38 | ports: 39 | - "5001:8080" 40 | volumes: 41 | - dotnet-minify-url:/app/MinifyUrl/MinifyUrl.Web/wwwroot 42 | depends_on: 43 | - mongodb 44 | - redis 45 | environment: 46 | - ASPNETCORE_ENVIRONMENT=Development 47 | - Settings:Server:Port=5001 48 | - Settings:MongoDb:Host=mongodb 49 | - Settings:Redis:Host=redis 50 | - Settings:UrlToken:PoolingSize=500000 51 | - Settings:UrlToken:ExtendSize=100000 -------------------------------------------------------------------------------- /src/Web/Web.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net9.0 5 | enable 6 | enable 7 | Linux 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | .dockerignore 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /src/Web/Endpoints/UrlShortEndpoint.cs: -------------------------------------------------------------------------------- 1 | using Carter; 2 | using MediatR; 3 | using Web.Common.Models.Endpoints; 4 | using Web.Common.Models.Endpoints.UrlShort; 5 | using Web.Extensions; 6 | using Web.Filter; 7 | using Web.UseCases.UrlShorten.GetShortenedUrl; 8 | using Web.UseCases.UrlShorten.ShortUrl; 9 | 10 | namespace Web.Endpoints; 11 | 12 | public class UrlShortEndpoint : ICarterModule 13 | { 14 | public void AddRoutes(IEndpointRouteBuilder app) 15 | { 16 | var group = app.MapGroup("/api/url-shorts") 17 | .WithTags("Url Shorten Endpoint"); 18 | 19 | group.MapPost("", ShortUrlAsync) 20 | .Produces>() 21 | .Produces>(400) 22 | .AddEndpointFilter>(); 23 | 24 | app.MapGet("/{token}", GetShortenedUrlAsync) 25 | .WithTags("Url Shorten Endpoint"); 26 | } 27 | 28 | private static async Task ShortUrlAsync(ShortUrlRequest request, ISender sender) 29 | { 30 | var command = request.ToCommand(); 31 | var result = await sender.Send(command); 32 | return result.ToResult(); 33 | } 34 | 35 | private static async Task GetShortenedUrlAsync(string? token, ISender sender) 36 | { 37 | var result = await sender.Send(new GetShortenedUrlQuery { Token = token }); 38 | return result.StatusCode == 200 ? Results.Redirect(result.Data!.LongUrl!) : result.ToResult(); 39 | } 40 | } -------------------------------------------------------------------------------- /src/Web/Common/Models/Options/AppSettingModel.cs: -------------------------------------------------------------------------------- 1 | namespace Web.Common.Models.Options; 2 | 3 | public class AppSettingModel 4 | { 5 | public required AppSettingServerModel Server { get; set; } 6 | public required AppSettingMongoModel MongoDb { get; set; } 7 | public required AppSettingRedisModel Redis { get; set; } 8 | public required AppSettingUrlTokenModel UrlToken { get; set; } 9 | } 10 | 11 | public class AppSettingServerModel 12 | { 13 | public required string Scheme { get; set; } 14 | public required string Host { get; set; } 15 | public required string Port { get; set; } 16 | 17 | public string Url => $"{Scheme}://{Host}:{Port}"; 18 | } 19 | 20 | public class AppSettingMongoModel 21 | { 22 | public required string User { get; set; } 23 | public required string Password { get; set; } 24 | public required string Host { get; set; } 25 | public required string Port { get; set; } 26 | public required string Database { get; set; } 27 | 28 | public string ConnectionString => $"mongodb://{User}:{Password}@{Host}:{Port}"; 29 | } 30 | 31 | public class AppSettingRedisModel 32 | { 33 | public required string Host { get; set; } 34 | public required string Port { get; set; } 35 | public required string Password { get; set; } 36 | public required int Database { get; set; } 37 | } 38 | 39 | public class AppSettingUrlTokenModel 40 | { 41 | public required int PoolingSize { get; set; } 42 | public required int ExtendSize { get; set; } 43 | public required int ExpirationDays { get; set; } 44 | public required string EpochDate { get; set; } 45 | } -------------------------------------------------------------------------------- /src/Web/Data/Configurations/UrlShortenConfiguration.cs: -------------------------------------------------------------------------------- 1 | using MongoDB.Bson.Serialization; 2 | using MongoDB.Driver; 3 | using Web.Data.Entities; 4 | 5 | namespace Web.Data.Configurations; 6 | 7 | public static class UrlShortenConfiguration 8 | { 9 | public static void Configure() 10 | { 11 | BsonClassMap.RegisterClassMap(u => 12 | { 13 | u.AutoMap(); 14 | u.SetIgnoreExtraElements(true); 15 | u.MapIdProperty(x => x.Id) 16 | .SetElementName("_id"); 17 | u.MapProperty(x => x.Token) 18 | .SetElementName("token") 19 | .SetIsRequired(true); 20 | u.MapProperty(x => x.Url) 21 | .SetElementName("url") 22 | .SetIsRequired(true); 23 | u.MapProperty(x => x.CreatedAt) 24 | .SetElementName("createdAt") 25 | .SetIsRequired(true); 26 | u.MapProperty(x => x.ExpiredAt) 27 | .SetElementName("expiredAt") 28 | .SetIsRequired(true); 29 | }); 30 | } 31 | 32 | public static List> CreateIndexes => 33 | [ 34 | new( 35 | Builders.IndexKeys 36 | .Ascending(x => x.Token), 37 | new CreateIndexOptions { Name = "Ix_Asc_Token", Unique = true } 38 | ), 39 | new( 40 | Builders.IndexKeys 41 | .Ascending(x => x.Url) 42 | .Ascending(x => x.ExpiredAt), 43 | new CreateIndexOptions { Name = "Ix_Asc_Url_Asc_ExpiredAt" } 44 | ) 45 | ]; 46 | } -------------------------------------------------------------------------------- /src/Web/Data/Configurations/UrlTokenConfiguration.cs: -------------------------------------------------------------------------------- 1 | using MongoDB.Bson.Serialization; 2 | using MongoDB.Driver; 3 | using Web.Data.Entities; 4 | 5 | namespace Web.Data.Configurations; 6 | 7 | public static class UrlTokenConfiguration 8 | { 9 | public static void Configure() 10 | { 11 | BsonClassMap.RegisterClassMap(u => 12 | { 13 | u.AutoMap(); 14 | u.SetIgnoreExtraElements(true); 15 | u.MapIdProperty(x => x.Id) 16 | .SetElementName("_id"); 17 | u.MapProperty(x => x.Token) 18 | .SetElementName("token") 19 | .SetIsRequired(true); 20 | u.MapProperty(x => x.IsUsed) 21 | .SetElementName("isUsed") 22 | .SetIsRequired(true) 23 | .SetDefaultValue(false); 24 | u.MapProperty(x => x.CreatedAt) 25 | .SetElementName("createdAt") 26 | .SetIsRequired(true); 27 | u.MapProperty(x => x.UsedAt) 28 | .SetElementName("usedAt") 29 | .SetIsRequired(false); 30 | }); 31 | } 32 | 33 | public static List> CreateIndexes => 34 | [ 35 | new( 36 | Builders.IndexKeys 37 | .Ascending(x => x.IsUsed) 38 | .Ascending(x => x.CreatedAt), 39 | new CreateIndexOptions { Name = "Ix_Asc_IsUsed_Asc_CreatedAt" } 40 | ), 41 | new( 42 | Builders.IndexKeys 43 | .Ascending(x => x.Token), 44 | new CreateIndexOptions { Name = "Ix_Asc_Token", Unique = true } 45 | ) 46 | ]; 47 | } -------------------------------------------------------------------------------- /src/Web/UseCases/UrlShorten/GetShortenedUrl/GetShortenedUrlHandler.cs: -------------------------------------------------------------------------------- 1 | using MediatR; 2 | using MongoDB.Driver; 3 | using Web.Common.Constants; 4 | using Web.Common.Models.Endpoints; 5 | using Web.Data; 6 | using Web.Services.Interfaces; 7 | 8 | namespace Web.UseCases.UrlShorten.GetShortenedUrl; 9 | 10 | public class GetShortenedUrlHandler(ICacheService cacheService, MongoDbContext dbContext) : IRequestHandler> 11 | { 12 | public async Task> Handle(GetShortenedUrlQuery request, CancellationToken cancellationToken) 13 | { 14 | if (string.IsNullOrWhiteSpace(request.Token)) 15 | { 16 | return Result.Invalid("Token is required."); 17 | } 18 | 19 | var cacheKey = string.Format(RedisConstant.Key.ShortUrl, request.Token); 20 | var url = await cacheService.GetAsync(cacheKey, cancellationToken); 21 | if (!string.IsNullOrEmpty(url)) 22 | { 23 | return Result.Success(new GetShortenedUrlResponse { LongUrl = url }); 24 | } 25 | 26 | var shortUrl = await dbContext.UrlShortens.Find(x => x.Token == request.Token).FirstOrDefaultAsync(cancellationToken); 27 | if (shortUrl is null) 28 | { 29 | return Result.Error(404, "Shortened URL not found."); 30 | } 31 | 32 | url = shortUrl.Url; 33 | await cacheService.SetAsync(cacheKey, url, shortUrl.ExpiredAt, cancellationToken); 34 | 35 | return Result.Success(new GetShortenedUrlResponse { LongUrl = url }); 36 | } 37 | } -------------------------------------------------------------------------------- /src/Web/Common/Models/Endpoints/Result.cs: -------------------------------------------------------------------------------- 1 | namespace Web.Common.Models.Endpoints; 2 | 3 | public class Result where T : class 4 | { 5 | public int StatusCode { get; private init; } 6 | public string? Message { get; private init; } 7 | public T? Data { get; private init; } 8 | public Dictionary? ValidationErrors { get; private init; } 9 | 10 | private Result() 11 | { 12 | } 13 | 14 | public static Result Success(T data) 15 | { 16 | return new Result 17 | { 18 | StatusCode = 200, 19 | Message = "Success", 20 | Data = data, 21 | ValidationErrors = null, 22 | }; 23 | } 24 | 25 | public static Result Error(int statusCode, string? message) 26 | { 27 | return new Result 28 | { 29 | StatusCode = statusCode, 30 | Message = message, 31 | Data = null, 32 | ValidationErrors = null, 33 | }; 34 | } 35 | 36 | public static Result Error(Result result) where TOther : class 37 | { 38 | return new Result 39 | { 40 | StatusCode = result.StatusCode, 41 | Message = result.Message, 42 | Data = null, 43 | ValidationErrors = result.ValidationErrors, 44 | }; 45 | } 46 | 47 | public static Result Invalid(string? message) 48 | { 49 | return new Result 50 | { 51 | StatusCode = 400, 52 | Message = message, 53 | Data = null 54 | }; 55 | } 56 | 57 | public static Result Invalid(string? message, Dictionary messages) 58 | { 59 | return new Result 60 | { 61 | StatusCode = 400, 62 | Message = message, 63 | ValidationErrors = messages, 64 | Data = null 65 | }; 66 | } 67 | } -------------------------------------------------------------------------------- /src/Web/Helpers/TokenBuilder.cs: -------------------------------------------------------------------------------- 1 | using System.Globalization; 2 | using System.Security.Cryptography; 3 | using System.Text; 4 | 5 | namespace Web.Helpers; 6 | 7 | public class TokenBuilder 8 | { 9 | private const string Charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; 10 | private const int CharsetLength = 62; 11 | 12 | private long _epoch; 13 | private int _additionalCharLength = 2; 14 | 15 | public TokenBuilder WithEpoch(string epochDate) 16 | { 17 | _epoch = DateTimeOffset.Parse(epochDate, new DateTimeFormatInfo 18 | { 19 | FullDateTimePattern = "yyyy-MM-dd" 20 | }).ToUnixTimeMilliseconds(); 21 | return this; 22 | } 23 | 24 | public TokenBuilder WithAdditionalCharLength(int length) 25 | { 26 | _additionalCharLength = length; 27 | return this; 28 | } 29 | 30 | public string Build() 31 | { 32 | var epochToken = GenerateTokenFromEpoch(); 33 | var additionalToken = GenerateToken(); 34 | return $"{epochToken}{additionalToken}"; 35 | } 36 | 37 | private string GenerateTokenFromEpoch() 38 | { 39 | var timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - _epoch; 40 | var token = new StringBuilder(); 41 | 42 | while (timestamp > CharsetLength) 43 | { 44 | token.Append(Charset[(int)(timestamp % CharsetLength)]); 45 | timestamp /= CharsetLength; 46 | } 47 | 48 | return token.ToString(); 49 | } 50 | 51 | private string GenerateToken() 52 | { 53 | if (_additionalCharLength <= 0) 54 | { 55 | return string.Empty; 56 | } 57 | 58 | var token = new StringBuilder(); 59 | for (var i = 0; i < _additionalCharLength; i++) 60 | { 61 | token.Append(Charset[RandomNumberGenerator.GetInt32(0, CharsetLength)]); 62 | } 63 | 64 | return token.ToString(); 65 | } 66 | } -------------------------------------------------------------------------------- /src/Web/UseCases/UrlToken/GetUnusedToken/GetUnusedTokenHandler.cs: -------------------------------------------------------------------------------- 1 | using MediatR; 2 | using MongoDB.Driver; 3 | using Web.Common.Constants; 4 | using Web.Common.Models.Endpoints; 5 | using Web.Common.Models.Options; 6 | using Web.Data; 7 | using Web.Helpers; 8 | using Web.Services.Interfaces; 9 | using Web.UseCases.UrlToken.SetTokenUsed; 10 | 11 | namespace Web.UseCases.UrlToken.GetUnusedToken; 12 | 13 | public class GetUnusedTokenHandler(ISender sender, ICacheService cacheService, MongoDbContext dbContext, AppSettingModel appSettingModel) 14 | : IRequestHandler> 15 | { 16 | private const int MaxTryCount = 5; 17 | 18 | public async Task> Handle(GetUnusedTokenQuery request, CancellationToken cancellationToken) 19 | { 20 | bool sendTokenUsed = true; 21 | var token = await cacheService.ListLeftPopAsync(RedisConstant.Key.TokenSeedList, cancellationToken); 22 | if (string.IsNullOrEmpty(token)) 23 | { 24 | int tryCount = 0; 25 | var tokenBuilder = new TokenBuilder() 26 | .WithEpoch(appSettingModel.UrlToken.EpochDate) 27 | .WithAdditionalCharLength(3); 28 | do 29 | { 30 | token = tokenBuilder.Build(); 31 | tryCount++; 32 | } while (tryCount <= MaxTryCount && await dbContext.UrlTokens.Find(x => x.Token == token).AnyAsync(cancellationToken)); 33 | 34 | var now = DateTime.UtcNow; 35 | await dbContext.UrlTokens.InsertOneAsync(new Data.Entities.UrlToken 36 | { 37 | Token = token, 38 | IsUsed = true, 39 | CreatedAt = now, 40 | UsedAt = now, 41 | }, cancellationToken: cancellationToken); 42 | sendTokenUsed = false; 43 | } 44 | 45 | if (sendTokenUsed) 46 | { 47 | await sender.Send(new SetTokenUsedCommand { Token = token }, cancellationToken); 48 | } 49 | return Result.Success(new GetUnusedTokenResponse { Token = token }); 50 | } 51 | } -------------------------------------------------------------------------------- /Shortener.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{29A40445-132C-4FBC-98E5-6B1FE105D2B0}" 4 | EndProject 5 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{5172C0ED-2B91-4279-B764-EF0EF371A4FD}" 6 | EndProject 7 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Web", "src\Web\Web.csproj", "{A27EFE01-095E-42BC-86F0-985B9ABBEFF1}" 8 | EndProject 9 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnitTest", "test\UnitTest\UnitTest.csproj", "{898E384A-5F3B-4518-9AEC-D20EE9D12F6F}" 10 | EndProject 11 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "SolutionItems", "SolutionItems", "{E9AF23DF-3777-4EAE-8754-FE375B9325D3}" 12 | ProjectSection(SolutionItems) = preProject 13 | .gitignore = .gitignore 14 | docker-compose.yml = docker-compose.yml 15 | README.md = README.md 16 | EndProjectSection 17 | EndProject 18 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "LoadTestK6", "LoadTestK6", "{70E23C75-E5D3-4D31-A4EC-C132E905BC6D}" 19 | ProjectSection(SolutionItems) = preProject 20 | test\LoadTestK6\regular_load_test.js = test\LoadTestK6\regular_load_test.js 21 | test\LoadTestK6\progressive_load_test.js = test\LoadTestK6\progressive_load_test.js 22 | EndProjectSection 23 | EndProject 24 | Global 25 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 26 | Debug|Any CPU = Debug|Any CPU 27 | Release|Any CPU = Release|Any CPU 28 | EndGlobalSection 29 | GlobalSection(NestedProjects) = preSolution 30 | {A27EFE01-095E-42BC-86F0-985B9ABBEFF1} = {29A40445-132C-4FBC-98E5-6B1FE105D2B0} 31 | {898E384A-5F3B-4518-9AEC-D20EE9D12F6F} = {5172C0ED-2B91-4279-B764-EF0EF371A4FD} 32 | {70E23C75-E5D3-4D31-A4EC-C132E905BC6D} = {5172C0ED-2B91-4279-B764-EF0EF371A4FD} 33 | EndGlobalSection 34 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 35 | {A27EFE01-095E-42BC-86F0-985B9ABBEFF1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 36 | {A27EFE01-095E-42BC-86F0-985B9ABBEFF1}.Debug|Any CPU.Build.0 = Debug|Any CPU 37 | {A27EFE01-095E-42BC-86F0-985B9ABBEFF1}.Release|Any CPU.ActiveCfg = Release|Any CPU 38 | {A27EFE01-095E-42BC-86F0-985B9ABBEFF1}.Release|Any CPU.Build.0 = Release|Any CPU 39 | {898E384A-5F3B-4518-9AEC-D20EE9D12F6F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 40 | {898E384A-5F3B-4518-9AEC-D20EE9D12F6F}.Debug|Any CPU.Build.0 = Debug|Any CPU 41 | {898E384A-5F3B-4518-9AEC-D20EE9D12F6F}.Release|Any CPU.ActiveCfg = Release|Any CPU 42 | {898E384A-5F3B-4518-9AEC-D20EE9D12F6F}.Release|Any CPU.Build.0 = Release|Any CPU 43 | EndGlobalSection 44 | EndGlobal 45 | -------------------------------------------------------------------------------- /src/Web/UseCases/UrlShorten/ShortUrl/ShortUrlHandler.cs: -------------------------------------------------------------------------------- 1 | using MediatR; 2 | using MongoDB.Driver; 3 | using QRCoder; 4 | using Web.Common.Constants; 5 | using Web.Common.Models.Endpoints; 6 | using Web.Common.Models.Options; 7 | using Web.Data; 8 | using Web.Services.Interfaces; 9 | using Web.UseCases.UrlToken.GetUnusedToken; 10 | 11 | namespace Web.UseCases.UrlShorten.ShortUrl; 12 | 13 | public class ShortUrlHandler(ISender sender, MongoDbContext dbContext, ICacheService cacheService, AppSettingModel appSettingModel) 14 | : IRequestHandler> 15 | { 16 | public async Task> Handle(ShortUrlCommand request, CancellationToken cancellationToken) 17 | { 18 | var expireDay = request.ExpireDay ?? appSettingModel.UrlToken.ExpirationDays; 19 | string token; 20 | 21 | var urlExist = await dbContext.UrlShortens.Find(x => x.Url == request.Url && x.ExpiredAt > DateTime.UtcNow).FirstOrDefaultAsync(cancellationToken); 22 | if (urlExist is not null) 23 | { 24 | token = urlExist.Token; 25 | expireDay = (urlExist.ExpiredAt - DateTime.UtcNow).Days; 26 | } 27 | else 28 | { 29 | var getTokenResult = await sender.Send(new GetUnusedTokenQuery(), cancellationToken); 30 | if (getTokenResult.StatusCode != 200) 31 | { 32 | return Result.Error(getTokenResult); 33 | } 34 | 35 | token = getTokenResult.Data!.Token!; 36 | var urlShorten = new Data.Entities.UrlShorten 37 | { 38 | Url = request.Url!, 39 | Token = token, 40 | CreatedAt = DateTime.UtcNow, 41 | ExpiredAt = DateTime.UtcNow.AddDays(expireDay) 42 | }; 43 | await dbContext.UrlShortens.InsertOneAsync(urlShorten, null, cancellationToken); 44 | } 45 | 46 | var response = new ShortUrlResponse 47 | { 48 | Token = token, 49 | ShortenedUrl = $"{appSettingModel.Server.Url}/{token}", 50 | }; 51 | response.QrCode = GetQrBase64(request, response.ShortenedUrl); 52 | await cacheService.SetAsync(string.Format(RedisConstant.Key.ShortUrl, token), request.Url!, TimeSpan.FromDays(expireDay), cancellationToken); 53 | 54 | return Result.Success(response); 55 | } 56 | 57 | private static string? GetQrBase64(ShortUrlCommand request, string url) 58 | { 59 | if (!request.HasQrCode) 60 | { 61 | return null; 62 | } 63 | 64 | var qrGenerator = new QRCodeGenerator(); 65 | var data = qrGenerator.CreateQrCode(url, QRCodeGenerator.ECCLevel.Q); 66 | var code = new Base64QRCode(data); 67 | return code.GetGraphic(20); 68 | } 69 | } -------------------------------------------------------------------------------- /src/Web/Services/Implementations/CacheService.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json; 2 | using StackExchange.Redis; 3 | using Web.Common.Models.Options; 4 | using Web.Services.Interfaces; 5 | 6 | namespace Web.Services.Implementations; 7 | 8 | public class CacheService(IConnectionMultiplexer connectionMultiplexer, AppSettingModel appSettingModel) : ICacheService 9 | { 10 | private readonly IDatabase _database = connectionMultiplexer.GetDatabase(appSettingModel.Redis.Database); 11 | 12 | public async Task PingAsync(CancellationToken cancellationToken = default) 13 | { 14 | var ts = await _database.PingAsync(); 15 | return ts.TotalMilliseconds > 0; 16 | } 17 | 18 | public async Task SetAsync(string key, TModel value, TimeSpan expiration, CancellationToken cancellationToken = default) where TModel : class 19 | { 20 | var redisValue = JsonSerializer.Serialize(value); 21 | await _database.StringSetAsync(key, redisValue, expiration); 22 | } 23 | 24 | public async Task SetAsync(string key, TModel value, DateTimeOffset expiration, CancellationToken cancellationToken = default) where TModel : class 25 | { 26 | var redisValue = JsonSerializer.Serialize(value); 27 | await _database.StringSetAsync(key, redisValue, TimeSpan.FromTicks(expiration.Ticks)); 28 | } 29 | 30 | public async Task GetAsync(string key, CancellationToken cancellationToken = default) where TModel : class 31 | { 32 | var redisValue = await _database.StringGetAsync(key); 33 | return redisValue.HasValue 34 | ? JsonSerializer.Deserialize(redisValue.ToString()) 35 | : null; 36 | } 37 | 38 | public async Task ExistsAsync(string key, CancellationToken cancellationToken = default) 39 | { 40 | return await _database.KeyExistsAsync(key); 41 | } 42 | 43 | public async Task RemoveAsync(string key, CancellationToken cancellationToken = default) 44 | { 45 | await _database.KeyDeleteAsync(key); 46 | } 47 | 48 | public async Task AddListRightAsync(string key, TModel value, CancellationToken cancellationToken = default) where TModel : class 49 | { 50 | var redisValue = new RedisValue(JsonSerializer.Serialize(value)); 51 | return await _database.ListRightPushAsync(key, redisValue); 52 | } 53 | 54 | public async Task AddListRightBulkAsync(string key, TModel[] values, CancellationToken cancellationToken = default) where TModel : class 55 | { 56 | var redisValues = values.AsParallel().Select(x => new RedisValue(JsonSerializer.Serialize(x))).ToArray(); 57 | return await _database.ListRightPushAsync(key, redisValues); 58 | } 59 | 60 | public async Task ListLeftPopAsync(string key, CancellationToken cancellationToken = default) where TModel : class 61 | { 62 | var redisValue = await _database.ListLeftPopAsync(key); 63 | return redisValue.HasValue ? JsonSerializer.Deserialize(redisValue.ToString()) : null; 64 | } 65 | } -------------------------------------------------------------------------------- /src/Web/Jobs/TokenSeedJob.cs: -------------------------------------------------------------------------------- 1 | using MongoDB.Driver; 2 | using Quartz; 3 | using Web.Common.Constants; 4 | using Web.Common.Models.Options; 5 | using Web.Data; 6 | using Web.Data.Entities; 7 | using Web.Helpers; 8 | using Web.Services.Interfaces; 9 | 10 | namespace Web.Jobs; 11 | 12 | public class TokenSeedJob(ILogger logger, MongoDbContext dbContext, ICacheService cacheService, AppSettingModel appSettingModel) 13 | : BaseJob(logger) 14 | { 15 | private readonly ILogger _logger = logger; 16 | 17 | protected override async Task ExecuteAsync(IJobExecutionContext context) 18 | { 19 | var cancellationToken = context.CancellationToken; 20 | _logger.LogInformation("Token seed job started"); 21 | 22 | try 23 | { 24 | int unusedTokenCount = await GetUnusedTokenCountAsync(cancellationToken); 25 | _logger.LogInformation("Token seed job found {Count} unused tokens", unusedTokenCount); 26 | 27 | if (ShouldGenerateMoreTokens(unusedTokenCount)) 28 | { 29 | int tokensToGenerate = CalculateTokensToGenerate(unusedTokenCount); 30 | _logger.LogInformation("Generating {NewTokenCount} new tokens", tokensToGenerate); 31 | 32 | await GenerateTokensInParallelAsync(tokensToGenerate, cancellationToken); 33 | } 34 | } 35 | catch (Exception ex) 36 | { 37 | _logger.LogError(ex, "An error occurred while executing the token seed job: {Message}", ex.Message); 38 | } 39 | 40 | _logger.LogInformation("Token seed job completed"); 41 | } 42 | 43 | private async Task GetUnusedTokenCountAsync(CancellationToken cancellationToken) 44 | { 45 | var unusedFilter = Builders.Filter.Where(x => !x.IsUsed); 46 | return (int)await dbContext.UrlTokens.CountDocumentsAsync(unusedFilter, cancellationToken: cancellationToken); 47 | } 48 | 49 | private bool ShouldGenerateMoreTokens(int unusedTokenCount) 50 | { 51 | return unusedTokenCount < appSettingModel.UrlToken.PoolingSize; 52 | } 53 | 54 | private int CalculateTokensToGenerate(int unusedTokenCount) 55 | { 56 | return appSettingModel.UrlToken.PoolingSize - unusedTokenCount + appSettingModel.UrlToken.ExtendSize; 57 | } 58 | 59 | private async Task GenerateTokensInParallelAsync(int count, CancellationToken cancellationToken) 60 | { 61 | var tokenBuilder = new TokenBuilder() 62 | .WithEpoch(appSettingModel.UrlToken.EpochDate) 63 | .WithAdditionalCharLength(3); 64 | 65 | var parallelOptions = new ParallelOptions 66 | { 67 | CancellationToken = cancellationToken, 68 | MaxDegreeOfParallelism = 10 69 | }; 70 | 71 | await Parallel.ForAsync(0, count, parallelOptions, async (_, ct) => 72 | { 73 | try 74 | { 75 | var token = tokenBuilder.Build(); 76 | await dbContext.UrlTokens.InsertOneAsync(new UrlToken 77 | { 78 | Token = token, 79 | IsUsed = false, 80 | CreatedAt = DateTime.UtcNow, 81 | }, null, ct); 82 | await cacheService.AddListRightAsync(RedisConstant.Key.TokenSeedList, token, ct); 83 | } 84 | catch (Exception ex) 85 | { 86 | _logger.LogError(ex, "An error occurred while generating token: {Message}", ex.Message); 87 | } 88 | }); 89 | } 90 | } -------------------------------------------------------------------------------- /src/Web/DependencyInjection.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using MongoDB.Driver; 3 | using Quartz; 4 | using Quartz.AspNetCore; 5 | using StackExchange.Redis; 6 | using Web.Data; 7 | using Web.Jobs; 8 | using FluentValidation; 9 | using MediatR; 10 | using Web.Common.Models.Options; 11 | using Web.Services.Implementations; 12 | using Web.Services.Interfaces; 13 | using Web.UseCases; 14 | 15 | namespace Web; 16 | 17 | public static class DependencyInjection 18 | { 19 | public static IServiceCollection AddWeb(this IServiceCollection services, IConfiguration configuration) 20 | { 21 | services.AddModels(configuration) 22 | .AddMongoDb() 23 | .AddFluentValidation() 24 | .AddCacheServices() 25 | .AddQuartzJob() 26 | .AddUseCases(); 27 | return services; 28 | } 29 | 30 | private static IServiceCollection AddModels(this IServiceCollection services, IConfiguration configuration) 31 | { 32 | var appSettingModel = configuration.GetSection("Settings").Get(); 33 | ArgumentNullException.ThrowIfNull(appSettingModel); 34 | services.AddSingleton(appSettingModel); 35 | return services; 36 | } 37 | 38 | private static IServiceCollection AddMongoDb(this IServiceCollection services) 39 | { 40 | var settings = services.BuildServiceProvider().GetRequiredService(); 41 | ArgumentNullException.ThrowIfNull(settings); 42 | 43 | var mongoClient = new MongoClient(settings.MongoDb.ConnectionString); 44 | services.AddSingleton(mongoClient); 45 | services.AddSingleton(); 46 | 47 | return services; 48 | } 49 | 50 | private static IServiceCollection AddFluentValidation(this IServiceCollection services) 51 | { 52 | services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly()); 53 | return services; 54 | } 55 | 56 | private static IServiceCollection AddCacheServices(this IServiceCollection services) 57 | { 58 | var settings = services.BuildServiceProvider().GetRequiredService(); 59 | ArgumentNullException.ThrowIfNull(settings); 60 | 61 | var redisOptions = ConfigurationOptions.Parse($"{settings.Redis.Host}:{settings.Redis.Port}"); 62 | redisOptions.Password = settings.Redis.Password; 63 | redisOptions.AbortOnConnectFail = false; 64 | var connectionMultiplexer = ConnectionMultiplexer.Connect(redisOptions); 65 | services.AddSingleton(connectionMultiplexer); 66 | services.AddSingleton(); 67 | 68 | return services; 69 | } 70 | 71 | private static IServiceCollection AddQuartzJob(this IServiceCollection services) 72 | { 73 | var settings = services.BuildServiceProvider().GetRequiredService(); 74 | ArgumentNullException.ThrowIfNull(settings); 75 | 76 | services.AddQuartz(quartz => 77 | { 78 | quartz.SchedulerName = "UrlShortenScheduler"; 79 | quartz.MisfireThreshold = TimeSpan.FromSeconds(300); 80 | 81 | var tokenSeedJobKey = new JobKey(nameof(TokenSeedJob), "Shortener"); 82 | quartz.AddJob(tokenSeedJobKey, job => job.WithDescription("Token Seed Job")); 83 | quartz.AddTrigger(trigger => trigger 84 | .WithIdentity("TokenSeedJobTrigger") 85 | .ForJob(tokenSeedJobKey) 86 | .WithCronSchedule("0 0/5 * * * ?") 87 | .WithDescription("Token Seed Job Trigger")); 88 | }); 89 | services.AddQuartzServer(opt => opt.WaitForJobsToComplete = false); 90 | return services; 91 | } 92 | 93 | private static IServiceCollection AddUseCases(this IServiceCollection services) 94 | { 95 | services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>)); 96 | services.AddMediatR(config => 97 | { 98 | config.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly()); 99 | }); 100 | return services; 101 | } 102 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Ll]og/ 33 | [Ll]ogs/ 34 | 35 | # Visual Studio 2015/2017 cache/options directory 36 | .vs/ 37 | # Uncomment if you have tasks that create the project's static files in wwwroot 38 | #wwwroot/ 39 | 40 | # Visual Studio 2017 auto generated files 41 | Generated\ Files/ 42 | 43 | # MSTest test Results 44 | [Tt]est[Rr]esult*/ 45 | [Bb]uild[Ll]og.* 46 | 47 | # NUnit 48 | *.VisualState.xml 49 | TestResult.xml 50 | nunit-*.xml 51 | 52 | # Build Results of an ATL Project 53 | [Dd]ebugPS/ 54 | [Rr]eleasePS/ 55 | dlldata.c 56 | 57 | # Benchmark Results 58 | BenchmarkDotNet.Artifacts/ 59 | 60 | # .NET Core 61 | project.lock.json 62 | project.fragment.lock.json 63 | artifacts/ 64 | 65 | # ASP.NET Scaffolding 66 | ScaffoldingReadMe.txt 67 | 68 | # StyleCop 69 | StyleCopReport.xml 70 | 71 | # Files built by Visual Studio 72 | *_i.c 73 | *_p.c 74 | *_h.h 75 | *.ilk 76 | *.meta 77 | *.obj 78 | *.iobj 79 | *.pch 80 | *.pdb 81 | *.ipdb 82 | *.pgc 83 | *.pgd 84 | *.rsp 85 | *.sbr 86 | *.tlb 87 | *.tli 88 | *.tlh 89 | *.tmp 90 | *.tmp_proj 91 | *_wpftmp.csproj 92 | *.log 93 | *.tlog 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio 6 auto-generated project file (contains which files were open etc.) 298 | *.vbp 299 | 300 | # Visual Studio 6 workspace and project file (working project files containing files to include in project) 301 | *.dsw 302 | *.dsp 303 | 304 | # Visual Studio 6 technical files 305 | *.ncb 306 | *.aps 307 | 308 | # Visual Studio LightSwitch build output 309 | **/*.HTMLClient/GeneratedArtifacts 310 | **/*.DesktopClient/GeneratedArtifacts 311 | **/*.DesktopClient/ModelManifest.xml 312 | **/*.Server/GeneratedArtifacts 313 | **/*.Server/ModelManifest.xml 314 | _Pvt_Extensions 315 | 316 | # Paket dependency manager 317 | .paket/paket.exe 318 | paket-files/ 319 | 320 | # FAKE - F# Make 321 | .fake/ 322 | 323 | # CodeRush personal settings 324 | .cr/personal 325 | 326 | # Python Tools for Visual Studio (PTVS) 327 | __pycache__/ 328 | *.pyc 329 | 330 | # Cake - Uncomment if you are using it 331 | # tools/** 332 | # !tools/packages.config 333 | 334 | # Tabs Studio 335 | *.tss 336 | 337 | # Telerik's JustMock configuration file 338 | *.jmconfig 339 | 340 | # BizTalk build output 341 | *.btp.cs 342 | *.btm.cs 343 | *.odx.cs 344 | *.xsd.cs 345 | 346 | # OpenCover UI analysis results 347 | OpenCover/ 348 | 349 | # Azure Stream Analytics local run output 350 | ASALocalRun/ 351 | 352 | # MSBuild Binary and Structured Log 353 | *.binlog 354 | 355 | # NVidia Nsight GPU debugger configuration file 356 | *.nvuser 357 | 358 | # MFractors (Xamarin productivity tool) working folder 359 | .mfractor/ 360 | 361 | # Local History for Visual Studio 362 | .localhistory/ 363 | 364 | # Visual Studio History (VSHistory) files 365 | .vshistory/ 366 | 367 | # BeatPulse healthcheck temp database 368 | healthchecksdb 369 | 370 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 371 | MigrationBackup/ 372 | 373 | # Ionide (cross platform F# VS Code tools) working folder 374 | .ionide/ 375 | 376 | # Fody - auto-generated XML schema 377 | FodyWeavers.xsd 378 | 379 | # VS Code files for those working on multiple tools 380 | .vscode/* 381 | !.vscode/settings.json 382 | !.vscode/tasks.json 383 | !.vscode/launch.json 384 | !.vscode/extensions.json 385 | *.code-workspace 386 | 387 | # Local History for Visual Studio Code 388 | .history/ 389 | 390 | # Windows Installer files from build outputs 391 | *.cab 392 | *.msi 393 | *.msix 394 | *.msm 395 | *.msp 396 | 397 | # JetBrains Rider 398 | *.sln.iml 399 | .idea 400 | --------------------------------------------------------------------------------